repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
mxposed/sickle
https://github.com/mxposed/sickle
593d848d7a084f70e1616e8ba0f73a67b3d2f623
7cec65f05be54645f1c367d0f1da598e4a489bba
c4d097280a0ad0ac2d2789b17128ec1470f58967
refs/heads/master
2020-03-27T22:16:20.546239
2018-09-07T14:30:05
2018-09-07T14:30:05
147,218,205
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.545188307762146, "alphanum_fraction": 0.5757322311401367, "avg_line_length": 36.359375, "blob_id": "1e8b056e0e0f39971e6f1771dc759790df6b943f", "content_id": "774a9fa41968b0300dd0837284014fa55f015e9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2390, "license_type": "no_license", "max_line_length": 88, "num_lines": 64, "path": "/03-evaluate-seurat/main.R", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "SCE_CACHE_DIR <- file.path(dirname(dirname(sys.frame(1)$ofile)), '01-cluster-sc01-sc02')\nCACHE_DIR <- dirname(sys.frame(1)$ofile)\n\npdfPlot <- function(filename, plot, width=8, height=6) {\n pdf(file=file.path(CACHE_DIR, filename))\n result <- plot()\n dev.off()\n return(result)\n}\n\nmain <- function() {\n cache_file <- file.path(CACHE_DIR, 'comb.rds')\n sc01 <- readRDS(file.path(SCE_CACHE_DIR, 'SC01.rds'))\n sc03 <- readRDS(file.path(SCE_CACHE_DIR, 'SC03.rds'))\n \n if (file.exists(cache_file)) {\n comb <- readRDS(cache_file)\n } else {\n g.1 <- head(rownames([email protected]), 1000)\n g.2 <- head(rownames([email protected]), 1000)\n genes.use <- unique(c(g.1,g.2))\n genes.use <- intersect(genes.use, rownames([email protected]))\n genes.use <- intersect(genes.use, rownames([email protected]))\n \n comb <- RunCCA(sc01, sc03, genes.use = genes.use, num.cc=30,\n add.cell.id1='SC01',\n add.cell.id2='SC03')\n comb <- CalcVarExpRatio(comb, reduction.type=\"pca\",\n grouping.var=\"orig.ident\",\n dims.use = 1:26)\n comb <- AlignSubspace(comb, reduction.type=\"cca\",\n grouping.var=\"orig.ident\",\n dims.align = 1:26)\n comb <- RunTSNE(comb, reduction.use = \"cca.aligned\", dims.use=1:26, do.fast=TRUE)\n }\n pdfPlot(\"comb-metagene-bicor.pdf\", function() {\n cache_file <- file.path(CACHE_DIR, 'bicor.rds')\n if (file.exists(cache_file)) {\n bicor.data <- readRDS(cache_file)\n } else {\n bicor.data <- MetageneBicorPlot(comb, \n grouping.var = 'orig.ident', \n dims.eval=1:30,\n return.mat=TRUE)\n saveRDS(bicor.data, file=cache_file)\n }\n MetageneBicorPlot(comb, bicor.data, grouping.var = 'orig.ident', dims.eval=1:30)\n })\n \n pdfPlot(\"comb-tsne.pdf\", function() {\n TSNEPlot(comb) \n })\n pdfPlot(\"comb-tsne-outliers.pdf\", function() {\n TSNEPlot(comb, [email protected][[email protected]$var.ratio.pca < 0.8]) \n })\n pdfPlot(\"comb-tsne-sc03-plasma.pdf\", function() {\n TSNEPlot(comb, cells.highlight=paste(\"SC03\", [email protected][sc03@ident == 7], sep=\"_\")) \n })\n pdfPlot(\"comb-hist-outliers.pdf\", function() {\n hist([email protected]$var.ratio.pca[[email protected]$var.ratio.pca < 2], breaks=50) \n })\n}\n\nmain()" }, { "alpha_fraction": 0.6183473467826843, "alphanum_fraction": 0.6715686321258545, "avg_line_length": 33.02381134033203, "blob_id": "b46d7e02bd3d7658caaca77070c6ca08de435ee5", "content_id": "5d366562fd1e28ce0f3b4acad2ff58609ab3600c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1428, "license_type": "no_license", "max_line_length": 87, "num_lines": 42, "path": "/05-catboost-eva/main.R", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "require(Seurat)\nrequire(scmap)\n\nCURRENT_DIR <- dirname(sys.frame(1)$ofile)\nCODE_ROOT <- dirname(CURRENT_DIR)\nSCE_CACHE_DIR <- file.path(CODE_ROOT, '01-cluster-sc01-sc02')\nMETADATA_DIR <- file.path(CODE_ROOT, '00-metadata')\n\npdfPlot <- function(filename, plot, width=8, height=6) {\n pdf(file=file.path(CURRENT_DIR, filename))\n result <- plot()\n dev.off()\n return(result)\n}\n\nmain <- function() {\n sc01 <- readRDS(file.path(SCE_CACHE_DIR, 'SC01.rds'))\n sc01.clusters <- read.csv(file.path(METADATA_DIR, 'SC01_clusters.csv'), header=FALSE)\n sc01.clusters$V1 <- sub(\"C\", \"\", sc01.clusters$V1)\n \n mca.clusters <- read.csv(file.path(CURRENT_DIR, 'MCA_clusters.csv'))\n \n preds <- read.csv(file.path(CURRENT_DIR, 'sc01-preds.csv'))\n preds$X0 <- sub(\"-1\", \"\", preds$X0)\n preds <- merge([email protected], preds, by.x=\"x\", by.y=\"X0\")\n sc01 <- StashIdent(sc01, save.name = 'orig')\n sc01 <- SetIdent(sc01, ident.use = preds$X0.1)\n pdfPlot('sc01-catboost-tsne.pdf', function() {\n TSNEPlot(sc01)\n })\n pdfPlot('sc01-catboost-probs.pdf', function() {\n hist(preds$prob, breaks=100)\n })\n \n labels1 <- sc01.clusters$V2[match([email protected]$orig, sc01.clusters$V1)]\n labels2 <- mca.clusters$Annotation[match(sc01@ident, mca.clusters$ClusterID)]\n levels(labels2) <- c(levels(labels2), \"Unassigned\")\n labels2[is.na(labels2)] <- \"Unassigned\"\n plot(getSankey(labels1, labels2, plot_width = 800, plot_height = 800))\n}\n\nmain()" }, { "alpha_fraction": 0.7596656084060669, "alphanum_fraction": 0.762800395488739, "avg_line_length": 44.57143020629883, "blob_id": "74a384b8fd391530c58bdaa58d442c98afe34bc9", "content_id": "33bafa62ba000098a23ac7d00ef018757b46361d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 957, "license_type": "no_license", "max_line_length": 176, "num_lines": 21, "path": "/05-catboost-eva/README.md", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "## Evaluation of catboost on MCA with nested cross-validation\n\n### Code\n\n`find_best_params.py`: code to search for best params on all CV splits and dump results as csv\n\n`train_predict.py`: code to train model with best parameters from the previous step and predict the test part for each CV split. Predictions are stored in `cv*-predictions.csv`\n\n`dump_cv_idx.py`: code to dump CV splits as cell ids. Dumps to `cv-idx` folder\n\n`seurat_classify_cells.R`: code to run Seurat's `ClassifyCells` random forest algorithm on CV splits from the previous steps. Predictios are stored in `cv*-preds-seurat.csv`\n\n`score.py`: code to read Seurat and catboost prediction from previous steps and score them. Final table is in `scores.csv`\n\n`cv_confusion_matrix.py`: code to plot confusion matrix for CV run #3. Figure 3\n\n### Cached files\n\n`cv*-predictions.csv`: best catboost predictions for each CV run\n\n`scores.csv`: scores for Seurat and catboost performance. Table 1\n" }, { "alpha_fraction": 0.5987135171890259, "alphanum_fraction": 0.6160316467285156, "avg_line_length": 27.46478843688965, "blob_id": "ff3cd0832f58922c4df4f9119557a97d12401250", "content_id": "8d221181c4285f7a8f076cecc9d91e7cbfc38101", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2021, "license_type": "no_license", "max_line_length": 110, "num_lines": 71, "path": "/05-catboost-eva/cv_confusion_matrix.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\n\nimport pandas as pd\n\nimport utils\nimport seaborn\nimport matplotlib.pyplot as plt\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef results_matrix(x, y, x_cols=None, y_cols=None):\n if x_cols is None:\n x_cols = sorted(x.unique())\n if y_cols is None:\n y_cols = sorted(y.unique())\n res = pd.DataFrame(index=x_cols, columns=y_cols)\n for i in res.index:\n res.loc[i, :] = y[(x[x == i]).index].value_counts(sort=False).sort_index()\n res.fillna(0, inplace=True)\n sums = res.sum(axis=1)\n return res.div(sums, axis=0)\n\n\ndef draw(cv_num):\n mca_clusters = pd.read_csv(\n os.path.join(CUR_DIR, 'MCA_clusters.csv'),\n index_col=1,\n )\n mca_clusters.index = mca_clusters.index.astype(int) - 1\n y_test = utils.load_mca_assignments()\n predictions = pd.read_csv(\n os.path.join(CUR_DIR, 'cv{}-predictions.csv'.format(cv_num)),\n index_col=0,\n )\n predictions.columns = mca_clusters.Annotation\n y_pred = predictions.idxmax(axis=1)\n y_test = mca_clusters.Annotation[y_test[y_pred.index]]\n y_test.index = y_pred.index\n\n confusion = results_matrix(y_test, y_pred, x_cols=mca_clusters.Annotation, y_cols=mca_clusters.Annotation)\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(1, 1, 1)\n cbar_ax = fig.add_axes((0.08, 0.2, 0.2, 0.02))\n ax = seaborn.heatmap(\n confusion,\n square=True,\n ax=ax,\n cmap=\"Blues\",\n cbar_ax=cbar_ax,\n cbar_kws={\n 'orientation': 'horizontal',\n }\n )\n ax.figure.axes[-1].tick_params(direction='inout', length=10)\n ax.figure.axes[-1].set_xlabel('Fraction of cells in row', fontsize=13)\n ax.set_xlabel('Predicted cell type', fontsize=16)\n ax.set_ylabel('Annotated cell type', fontsize=16)\n\n plt.tight_layout()\n ax.figure.savefig(os.path.join(CUR_DIR, 'cv{}-confusion.pdf'.format(cv_num)))\n\n\ndef main():\n draw(3)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6098252534866333, "alphanum_fraction": 0.6206896305084229, "avg_line_length": 28, "blob_id": "e68112c72a02cb61c9b4448416f6179e73922edf", "content_id": "a867330421e64f0925c5c3426aa50dc299403859", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2117, "license_type": "no_license", "max_line_length": 83, "num_lines": 73, "path": "/05-catboost-eva/seurat_classify_cells.R", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "require(Seurat)\nrequire(dplyr)\n\n\nthisFile <- function() {\n cmdArgs <- commandArgs(trailingOnly = FALSE)\n needle <- \"--file=\"\n match <- grep(needle, cmdArgs)\n if (length(match) > 0) {\n # Rscript\n return(normalizePath(sub(needle, \"\", cmdArgs[match])))\n } else {\n # 'source'd via R console\n return(normalizePath(sys.frames()[[1]]$ofile))\n }\n}\n\n\nCURRENT_DIR <- dirname(thisFile())\nROOT <- dirname(dirname(CURRENT_DIR))\n\n\nmain <- function() {\n l1 <- read.csv(file.path(ROOT, 'rmbatch_dge', 'Lung1_rm.batch_dge.txt'), sep=' ')\n l2 <- read.csv(file.path(ROOT, 'rmbatch_dge', 'Lung2_rm.batch_dge.txt'), sep=' ')\n l3 <- read.csv(file.path(ROOT, 'rmbatch_dge', 'Lung3_rm.batch_dge.txt'), sep=' ')\n\n l1 <- as.data.frame(t(l1))\n l2 <- as.data.frame(t(l2))\n l3 <- as.data.frame(t(l3))\n\n lung <- bind_rows(lapply(list(l1, l2, l3), add_rownames))\n rownames(lung) <- lung$rowname\n lung$rowname <- NULL\n lung[is.na(lung)] <- 0\n lungs <- CreateSeuratObject(as.data.frame(t(lung)))\n\n cell_types <- read.csv(file.path(ROOT, 'MCA_assign.csv'))\n cell_types <- cell_types[cell_types$Tissue == 'Lung',]\n cell_types$ClusterID <- as.numeric(sub('Lung_', '', cell_types$ClusterID))\n cell_types$ClusterID <- cell_types$ClusterID - 1\n rownames(cell_types) <- cell_types$Cell.name\n\n for (i in 1:5) {\n train_cells <- read.csv(file.path(\n CURRENT_DIR,\n 'cv-idx',\n sprintf('cv%d-train.csv', i)\n ), header=FALSE)\n test_cells <- read.csv(file.path(\n CURRENT_DIR,\n 'cv-idx',\n sprintf('cv%d-test.csv', i)\n ), header=FALSE)\n train <- SubsetData(lungs, cells.use = as.vector(train_cells$V2))\n train <- CreateSeuratObject(train@data)\n test <- SubsetData(lungs, cells.use = as.vector(test_cells$V2))\n test <- CreateSeuratObject(test@data)\n pred <- ClassifyCells(\n train,\n training.classes = cell_types[[email protected], 'ClusterID'],\n new.data = test@data\n )\n pred <- data.frame(pred = pred)\n rownames(pred) <- [email protected]\n write.csv(pred, file.path(\n CURRENT_DIR,\n sprintf('cv%d-preds-seurat.csv', i)\n ))\n }\n}\n\nmain()\n" }, { "alpha_fraction": 0.5596491098403931, "alphanum_fraction": 0.5631579160690308, "avg_line_length": 34.625, "blob_id": "f96b0a82f344f21dfdeab9088e57ab4d5af92006", "content_id": "a814b08cc648cd3bf9dd22ab677bd1a1fd916274", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 570, "license_type": "no_license", "max_line_length": 69, "num_lines": 16, "path": "/09-leave-cell-type-out/cross_val.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n\ndef leave_cell_type_out(X, y):\n for cls in sorted(y.unique()):\n y_train = y[y != cls]\n y_test = y[y == cls]\n X_train = X.loc[y_train.index, :]\n X_test = X.loc[y_test.index, :]\n X_train, X_test_add, y_train, y_test_add = train_test_split(\n X_train, y_train, test_size=0.1, stratify=y_train,\n )\n X_test = pd.concat([X_test, X_test_add])\n y_test = pd.concat([y_test, y_test_add])\n yield X_train, y_train, X_test, y_test\n" }, { "alpha_fraction": 0.6110910773277283, "alphanum_fraction": 0.6489017009735107, "avg_line_length": 33.712501525878906, "blob_id": "004f80931506a3fa497e7297803c6ce884206d73", "content_id": "4b65e99ec848808fa3431943bfe44abbc3e86ab1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2777, "license_type": "no_license", "max_line_length": 101, "num_lines": 80, "path": "/05-catboost-eva/utils.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\n\nimport matplotlib\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use('Agg')\nimport numpy as np\nimport pandas as pd\nimport scanpy.api as sc\n\n\nCUR_DIR = os.path.dirname(__file__)\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef load_10x_scanpy(path, batch_label):\n sc01 = sc.read('{}/matrix.mtx'.format(path), cache=True).T\n sc01.var_names = pd.read_table('{}/genes.tsv'.format(path), header=None)[1]\n sc01.obs_names = pd.read_table('{}/barcodes.tsv'.format(path), header=None)[0]\n sc01.obs_names = sc01.obs_names.str.replace('-1', '')\n sc01.var_names_make_unique()\n sc.pp.filter_cells(sc01, min_genes=200)\n sc.pp.filter_genes(sc01, min_cells=3)\n\n sc01.obs['n_UMI'] = np.sum(sc01.X, axis=1).A1\n\n mito_genes = sc01.var_names[sc01.var_names.str.match(r'^mt-')]\n sc01.obs['percent_mito'] = np.sum(sc01[:, mito_genes].X, axis=1).A1 / sc01.obs['n_UMI']\n\n ribo_genes = sc01.var_names[sc01.var_names.str.match(r'^(Rpl|Rps|Mrpl|Mrps)')]\n sc01.obs['percent_ribo'] = np.sum(sc01[:, ribo_genes].X, axis=1).A1 / sc01.obs['n_UMI']\n\n assgn = pd.read_csv('{}/{}_assgn.csv'.format(\n os.path.join(CUR_DIR, '..', '01-cluster-sc01-sc02'),\n batch_label,\n ), index_col=0)\n assgn.columns = ['cluster']\n\n sc01.obs['cluster'] = assgn.cluster[sc01.obs.index]\n return sc01\n\n\ndef load_10x(path, batch_label):\n sc01 = load_10x_scanpy(path, batch_label)\n exp = pd.DataFrame(sc01.X.todense(), index=sc01.obs_names, columns=sc01.var_names)\n exp['Batch'] = batch_label\n exp.fillna(0, inplace=True)\n\n exp['cluster'] = sc01.obs.cluster[exp.index]\n exp = exp[~exp.cluster.isna()]\n return exp[exp.columns[:-1]], exp.cluster\n\n\ndef path(*args):\n return os.path.join(ROOT, *args)\n\n\ndef load_mca_assignments():\n cell_types = pd.read_csv(path('MCA_assign.csv'), index_col=0)\n cell_types = cell_types[cell_types.Tissue == 'Lung']\n cell_types.ClusterID = cell_types.ClusterID.str.replace('Lung_', '').astype('int')\n cell_types.ClusterID = cell_types.ClusterID - 1\n return cell_types.set_index('Cell.name').ClusterID\n\n\ndef load_mca_lung():\n lung1 = pd.read_csv(path('rmbatch_dge/Lung1_rm.batch_dge.txt'), header=0, sep=' ', quotechar='\"')\n lung2 = pd.read_csv(path('rmbatch_dge/Lung2_rm.batch_dge.txt'), header=0, sep=' ', quotechar='\"')\n lung3 = pd.read_csv(path('rmbatch_dge/Lung3_rm.batch_dge.txt'), header=0, sep=' ', quotechar='\"')\n\n lung1 = lung1.transpose()\n lung2 = lung2.transpose()\n lung3 = lung3.transpose()\n lung = pd.concat([lung1, lung2, lung3])\n\n lung = lung.join(load_mca_assignments())\n lung = lung[~lung.ClusterID.isna()]\n lung.fillna(0, inplace=True)\n\n X = lung[lung.columns[lung.columns != 'ClusterID']]\n return X, lung.ClusterID\n" }, { "alpha_fraction": 0.714640200138092, "alphanum_fraction": 0.7543424367904663, "avg_line_length": 30, "blob_id": "8ad7e08635af54d8343f5aa2cfc5e76e98a19116", "content_id": "1d5ad7c822351662000f17efc5f239e14f57851c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 403, "license_type": "no_license", "max_line_length": 131, "num_lines": 13, "path": "/10-catboost-sc01/README.md", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "## Model preparation for SC01\n\n### Code\n\n`params_search.py`: code to search for best params to train SC01 model (SC01v2 clustering)\n\n`train_predict.py`: code to train model with best parameters from the previous step and predict SC02. Result is in `sc02-preds.csv`\n\n`analyse.py`: code to score and plot predictions from previous steps. Figure 4B\n\n### Cached files\n\n`sc02-preds.csv`: predictions of SC02\n" }, { "alpha_fraction": 0.5752128958702087, "alphanum_fraction": 0.5879848599433899, "avg_line_length": 28.34722137451172, "blob_id": "ec3e4cccbd02111cce0d5ee085f3d2d2c8938698", "content_id": "84acf1b709ac68d848ca26ccc867318a5a4e570e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2114, "license_type": "no_license", "max_line_length": 88, "num_lines": 72, "path": "/05-catboost-eva/train_predict.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\nimport sys\n\nimport catboost\nimport pandas as pd\nfrom sklearn.model_selection import StratifiedKFold\n\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef train(params, X_train, y_train):\n clf = catboost.CatBoostClassifier(\n l2_leaf_reg=params['l2_leaf_reg'],\n learning_rate=params['learning_rate'],\n depth=params['depth'],\n iterations=200,\n random_seed=42,\n logging_level='Silent',\n loss_function='MultiClass',\n eval_metric='TotalF1',\n thread_count=20,\n )\n\n clf.fit(\n X_train,\n y_train,\n )\n return clf\n\n\ndef main(number):\n runs = []\n for i in range(1, 11):\n runs.append(\n pd.read_csv(os.path.join(\n CUR_DIR,\n './search-{}+{}-of-10.csv'.format(number, i)\n ),\n index_col=0)\n )\n runs = pd.concat(runs, ignore_index=True)\n best_row = runs.score.idxmax(axis=0)\n best_params = eval(runs.params[best_row])\n\n X, y = utils.load_mca_lung()\n skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n splits = list(skf.split(X, y))\n for tr_idx, test_idx in splits[number - 1:number]:\n X_train, y_train = X.iloc[tr_idx, :], y.iloc[tr_idx]\n X_test, y_text = X.iloc[test_idx, :], y.iloc[test_idx]\n\n model = train(best_params, X_train, y_train)\n model.save_model(os.path.join(CUR_DIR, 'model-cv{}.cbm'.format(number)))\n\n importances = pd.DataFrame(model._feature_importance, X_train.columns)\n importances[importances[0] > 0].sort_values(\n 0,\n ascending=False\n ).to_csv(os.path.join(CUR_DIR, 'model-cv{}-features.csv'.format(number)))\n predictions = pd.DataFrame(model.predict_proba(X_test), index=X_test.index)\n predictions.to_csv(os.path.join(CUR_DIR, 'cv{}-predictions.csv'.format(number)))\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('Usage: {} <N>'.format(__file__), file=sys.stderr)\n sys.exit(1)\n main(int(sys.argv[1]))\n\n" }, { "alpha_fraction": 0.7182539701461792, "alphanum_fraction": 0.7519841194152832, "avg_line_length": 32.599998474121094, "blob_id": "da22b992d6b60da12f11c59fa8b3e5c21a5b5c61", "content_id": "7aab397de08436d1913b60d2bb9f74371597b3d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 504, "license_type": "no_license", "max_line_length": 139, "num_lines": 15, "path": "/11-catboost-sc03/README.md", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "## Model preparation for SC03\n\n### Code\n\n`params_search.py`: code to search for best params to train SC03 model\n\n`train_predict.py`: code to train model with best parameters from the previous step and predict SC01 and SC02. Result is in `sc*-preds.csv`\n\n`analyse.py`: code to score and plot predictions from previous steps\n\n`plot_plasma_predictions.py`: code to plot cells that got predicted as _Plasma cells_ from SC01 and SC02. Figure 7\n\n### Cached files\n\n`sc*-preds.csv`: predictions of SC01 and SC02\n" }, { "alpha_fraction": 0.725395917892456, "alphanum_fraction": 0.766968309879303, "avg_line_length": 61.03508758544922, "blob_id": "79651ee09dba713e21da296344f29d98e12565f2", "content_id": "93c4c680dfc6e19717ba689f325983cd3b65083a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3550, "license_type": "no_license", "max_line_length": 286, "num_lines": 57, "path": "/README.md", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "# Evaluation of machine learning strategies for classification and unbiased discovery of the new cell types in the single cell RNA-seq datasets\nCode for M.Sc. thesis project\n\n## Dependencies\nCode is written in python 3 and R. Python requirements are in `requirements.txt`, R requirements are as follow:\n * Seurat\n * scmap\n * scran\n * ggplot2\n * MUDAN (optional; https://jef.works/MUDAN/)\n * SeuratConverter\n * irr\n\nDatasets are expected to be in the parent folder of this code root, like this:\n\n`<folder>/`\n * `sickle/` this repo\n * `rmbatch_dge/` MCA data with Lung batches unzipped\n * `SC01/` Reyfman _et al._ samples\n * `SC02/`\n * `SC03/`\n\n## General notes\nThis repo contains several data files in `00-metadata`, and other data files are cached after they were created by scripts, and can be reproduced from datasets.\n\nPython scripts are expected to be run with `run.sh <script>` (it adds `lib` to PYTHONPATH).\n\n## Code structure\n`lib`: common code extracted from python scripts. Includes loading datasets, predictions, mapping and quantifying cross-dataset predictions, drawing Sankey diagrams.\n\n`00-metadata`: data files with cluster names and cluster correspondence between datasets\n\n`01-cluster-sc01-sc02`: code to cluster SC01, SC02 and SC03 datasets and cache them. Code for Figure 2. Code to inspect _B cells_ split in initial clustering of SC02\n\n`02-evaluate-mnn`: code to test MNN batch correction between SC01 and SC03. Haghverdi,L. et al. (2018) Batch effects in single-cell RNA-sequencing data are corrected by matching mutual nearest neighbors. Nat. Biotechnol., 36, 421–427.\n\n`03-evaluate-seurat`: code to test CCA-based batch correction approach from Seurat between SC01 and SC03. Butler,A. et al. (2018) Integrating single-cell transcriptomic data across different conditions, technologies, and species. Nat. Biotechnol., 36, 411–420.\n\n`04-evaluate-scmap`: code to test scmap projection method. Code to quantify and plot SC03 projection onto SC02 dataset with scmap-cluster method, Figure 10 (left part). Kiselev,V.Y. et al. (2018) Scmap: Projection of single-cell RNA-seq data across data sets. Nat. Methods, 15, 359–362.\n\n`05-catboost-eva`: evaluation of catboost on MCA dataset using nested-cv. Code to get baseline predictions. Plotting of Figure 3.\n\n`06-select-measure`: code to test how different metrics and measures for clustering comparison react to different cluster perturbations. Sketch of custom measure “mapScore”\n\n`07-catboost-sc02`: code to select and train best catboost model for SC02, predict SC01 and SC03 with it, plot and quantify. Figure 4 (left part). Figure 8.\n\n`08-unseen-sc02`: code to test several ensemble models trained on SC02, predict SC03, quantify and plot predictions. Figure 9. Figure 10 (right part).\n\n`09-leave-cell-type-out`: code to run leave-one-cluster-out cross-validation for ensemble method, and to search for the best threshold for “novel cell type” detection on SC02.\n\n`10-catboost-sc01`: code to select and train best model for SC01, predict, plot and quantify SC02. Figure 4 (right part).\n\n`11-catboost-sc03`: code to select and train best model for SC03; predict SC01 and SC02, plot and quantify; plot cells predicted as _Plasma cells_. Figure 7.\n\n`12-catboost-mca`: code to select and train best model for MCA; predict SC01, SC02 and SC03, plot and quantify; run correlation analysis and plot correlation plots.\n\n`13-cluster-mca`: cell type assignment table for our clustering of MCA Lung dataset. Clustering itself is available at https://osf.io/agc98/\n" }, { "alpha_fraction": 0.5262663960456848, "alphanum_fraction": 0.5409631133079529, "avg_line_length": 29.75, "blob_id": "3d8cc40cd1e3e4ff020b9eb6cc9356f108b5860a", "content_id": "d0c43837b91a5298138e77d8d5ab88763b0135bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3198, "license_type": "no_license", "max_line_length": 88, "num_lines": 104, "path": "/12-catboost-mca/params_search.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import sickle\n\nimport os\nimport sys\n\nimport catboost\nimport numpy as np\nimport pandas as pd\nimport sklearn.model_selection\nimport sklearn.metrics\nimport timeit\n\n\nCUR_DIR, ROOT = sickle.paths(__file__)\n\n\ndef cross_val(X, y, params, cv=5):\n skf = sklearn.model_selection.StratifiedKFold(\n n_splits=cv,\n shuffle=True,\n random_state=42\n )\n\n scores = []\n splits = list(skf.split(X, y))\n for i, (tr_ind, val_ind) in enumerate(splits):\n print('({}/{})'.format(i + 1, len(splits)), file=sys.stderr, end='')\n sys.stderr.flush()\n\n X_train, y_train = X.iloc[tr_ind, :], y.iloc[tr_ind]\n X_valid, y_valid = X.iloc[val_ind, :], y.iloc[val_ind]\n\n clf = catboost.CatBoostClassifier(\n l2_leaf_reg=params['l2_leaf_reg'],\n learning_rate=params['learning_rate'],\n depth=params['depth'],\n iterations=50,\n random_seed=42,\n logging_level='Silent',\n loss_function='MultiClass',\n eval_metric='TotalF1',\n thread_count=20,\n )\n\n clf.fit(\n X_train,\n y_train,\n )\n\n y_pred = clf.predict(X_valid)\n score = sklearn.metrics.f1_score(y_valid, y_pred, average='weighted')\n scores.append(score)\n print('\\b\\b\\b\\b\\b', file=sys.stderr, end='')\n sys.stderr.flush()\n return np.mean(scores)\n\n\ndef catboost_GridSearchCV(X, y, params_space, record, cv=5, splits=1, current_split=1):\n max_score = 0\n best_params = None\n all_params = list(sklearn.model_selection.ParameterGrid(params_space))\n divider = current_split - 1\n my_params = [all_params[i] for i in range(len(all_params)) if i % splits == divider]\n for i, params in enumerate(my_params):\n print('{:3d}% '.format(i * 100 // len(my_params)), file=sys.stderr, end='')\n sys.stderr.flush()\n start = timeit.default_timer()\n score = cross_val(X, y, params, cv=cv)\n if score > max_score:\n max_score = score\n best_params = params\n record.append([repr(params), score, timeit.default_timer() - start])\n print('\\r' + ' ' * 20 + '\\r', file=sys.stderr, end='')\n sys.stderr.flush()\n return max_score, best_params\n\n\ndef main(splits, current_split):\n X, y = sickle.load_mca_lung('MCAv2')\n params_space = {\n 'l2_leaf_reg': [1, 3, 5, 7, 9],\n 'learning_rate': np.linspace(1e-3, 8e-1, num=10),\n 'depth': [6, 8, 10],\n }\n record = []\n score, best_params = catboost_GridSearchCV(X, y, params_space,\n record, cv=5,\n splits=splits,\n current_split=current_split)\n pd.DataFrame(record, columns=['params', 'score', 'time']).to_csv(\n os.path.join(\n CUR_DIR,\n 'search-{}-of-{}.csv'.format(current_split, splits)\n )\n )\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 3:\n print('Usage: {} <N> <K>'.format(__file__), file=sys.stderr)\n sys.exit(1)\n splits = int(sys.argv[1])\n my_split = int(sys.argv[2])\n main(splits, my_split)\n" }, { "alpha_fraction": 0.5845984220504761, "alphanum_fraction": 0.6028153300285339, "avg_line_length": 29.191667556762695, "blob_id": "4d09efc1bf35a1450b2427219099b4321049586e", "content_id": "2b088c50fcf5c5a823745ae00a4ca6a839fa8f65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3623, "license_type": "no_license", "max_line_length": 88, "num_lines": 120, "path": "/05-catboost-eva/prediction_score.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\nimport sys\n\nimport catboost\nimport numpy as np\nimport pandas as pd\nimport sklearn.metrics\nimport sklearn.model_selection\n#import timeit\n\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef eval_params(params, X_train, y_train, X_valid, y_valid):\n clf = catboost.CatBoostRegressor(\n iterations=100,\n learning_rate=params['learning_rate'],\n depth=params['depth'],\n l2_leaf_reg=params['l2_leaf_reg'],\n random_seed=42,\n logging_level='Silent',\n thread_count=20,\n loss_function='MAE',\n )\n\n clf.fit(\n X_train,\n y_train,\n )\n\n y_pred = clf.predict(X_valid)\n return sklearn.metrics.mean_absolute_error(y_valid, y_pred)\n\n\ndef cross_val(X, y, params, cv=5):\n skf = sklearn.model_selection.KFold(n_splits=cv, shuffle=True, random_state=42)\n\n scores = []\n splits = list(skf.split(X, y))\n for i, (tr_ind, val_ind) in enumerate(splits):\n print('({}/{})'.format(i + 1, len(splits)), file=sys.stderr, end='')\n sys.stderr.flush()\n\n X_train, y_train = X.iloc[tr_ind, :], y.iloc[tr_ind]\n X_valid, y_valid = X.iloc[val_ind, :], y.iloc[val_ind]\n\n scores.append(eval_params(params, X_train, y_train, X_valid, y_valid))\n print('\\b\\b\\b\\b\\b', file=sys.stderr, end='')\n sys.stderr.flush()\n return np.mean(scores)\n\n\ndef find_best_params(X, y, params_space, splits=1, current_split=1):\n min_score = None\n best_params = None\n all_params = list(sklearn.model_selection.ParameterGrid(params_space))\n divider = current_split - 1\n my_params = [all_params[i] for i in range(len(all_params)) if i % splits == divider]\n for i, params in enumerate(my_params):\n print('{:3d}% '.format(i * 100 // len(my_params)), file=sys.stderr, end='')\n sys.stderr.flush()\n #start = timeit.default_timer()\n score = cross_val(X, y, params)\n if min_score is None or score < min_score:\n min_score = score\n best_params = params\n #record.append([repr(params), score, timeit.default_timer() - start])\n print('\\r' + ' ' * 20 + '\\r', file=sys.stderr, end='')\n sys.stderr.flush()\n return min_score, best_params\n\n\ndef process():\n X, _ = utils.load_10x(os.path.join(ROOT, 'SC01'), 'SC01v2')\n X.drop(columns=['Batch'], inplace=True)\n\n predictions = pd.read_csv(os.path.join(CUR_DIR, 'sc01-best-preds.csv'), index_col=0)\n predictions.index = predictions.index.str.replace('-1', '')\n y = predictions.loc[X.index, :].max(axis=1)\n\n params_space = {\n 'l2_leaf_reg': [1, 3, 5, 7, 9],\n 'learning_rate': np.linspace(1e-3, 8e-1, num=10),\n 'depth': [6, 8, 10],\n }\n\n score, best_params = find_best_params(X, y, params_space)\n print('Best params score: {}'.format(score))\n print('Best params: {}'.format(repr(best_params)))\n\n model = catboost.CatBoostRegressor(\n iterations=500,\n learning_rate=best_params['learning_rate'],\n depth=best_params['depth'],\n l2_leaf_reg=best_params['l2_leaf_reg'],\n random_seed=42,\n logging_level='Silent',\n thread_count=20,\n loss_function='MAE',\n )\n model.fit(X, y)\n model.save_model(os.path.join(CUR_DIR, 'sc01-pred-score.cbm'))\n\n importances = pd.DataFrame(model._feature_importance, X.columns)\n importances[importances[0] > 0].sort_values(\n 0,\n ascending=False\n ).to_csv(os.path.join(CUR_DIR, 'sc01-pred-score-features.csv'))\n\n\ndef main():\n process()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5427830815315247, "alphanum_fraction": 0.5626620650291443, "avg_line_length": 21.25, "blob_id": "7973575dc7ec58130aaf6af45918f061274eda90", "content_id": "e769f032b755f792bc29dd629c98e3dc192c99c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1157, "license_type": "no_license", "max_line_length": 72, "num_lines": 52, "path": "/04-evaluate-scmap/analyse.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import sickle\n\nimport os\n\nimport pandas as pd\nimport seaborn\n\nimport sankey\n\n\nCUR_DIR, ROOT = sickle.paths(__file__)\n\n\ndef process(exp, reference, query, tag=None):\n exp_clusters = sickle.assignments(query)\n\n clusters = sickle.load_clusters(query)\n\n preds = pd.read_csv(\n os.path.join(CUR_DIR, '{}-preds.csv'.format(exp)),\n index_col=0,\n )\n preds = preds.reindex(exp_clusters.index)\n\n seaborn.set(font_scale=1)\n mapping = sickle.mapping(query, reference)\n s = sankey.sankey(\n clusters.iloc[:, 0].loc[exp_clusters],\n preds.x,\n alpha=.7,\n left_order=sickle.sankey_order(),\n mapping=mapping,\n tag=tag\n )\n s.savefig(os.path.join(CUR_DIR, '{}-sankey.pdf'.format(exp)))\n\n if mapping:\n open(os.path.join(CUR_DIR, '{}-f1.txt'.format(exp)), 'w').write(\n 'F1 score: {:.4f}'.format(\n mapping.f1(clusters.iloc[:, 0].loc[exp_clusters],\n preds.x)\n )\n )\n\n\ndef main():\n process('sc03-cluster', 'SC02v2', 'SC03', tag='A')\n process('sc03-cell', 'SC02v2', 'SC03')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6002066135406494, "alphanum_fraction": 0.6126033067703247, "avg_line_length": 25.16216278076172, "blob_id": "ad3b8c6a2e9e5b10d9010a414076f12b29154699", "content_id": "f2023282e263d543943832fe1cdd4cd068688174", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 968, "license_type": "no_license", "max_line_length": 99, "num_lines": 37, "path": "/09-leave-cell-type-out/main.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\n\nimport cross_val as cv\nimport predict\nimport split\nimport train\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef get_reference():\n global _reference\n if '_reference' not in globals():\n _reference = utils.load_10x(os.path.join(ROOT, 'SC02'), 'SC02v2')\n return _reference\n\n\ndef experiment(**kwargs):\n X, y = get_reference()\n i = 1\n for X_train, y_train, X_test, y_test in cv.leave_cell_type_out(X, y):\n splits = split.split(\n X_train, y_train,\n other_proportion=4,\n split_order='cumsum',\n )\n models = train.models(splits, iterations=kwargs['catboost_iters'], label='cv-{}'.format(i))\n result_path = os.path.join(CUR_DIR, 'cv-{}.csv'.format(i))\n predict.predict(models, X_train.columns, X_test).to_csv(result_path)\n i += 1\n\n\nif __name__ == '__main__':\n experiment(catboost_iters=50)\n" }, { "alpha_fraction": 0.5687204003334045, "alphanum_fraction": 0.6062704920768738, "avg_line_length": 25.631067276000977, "blob_id": "c30c3593535a5899c2481b95d8818cd966c8aac3", "content_id": "fcbb9bb1ac4ce76e3d104cfceb179754a874a31c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2743, "license_type": "no_license", "max_line_length": 85, "num_lines": 103, "path": "/01-cluster-sc01-sc02/plot_sc02_10.R", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "require(Seurat)\nrequire(ggplot2)\n\n\nthisFile <- function() {\n cmdArgs <- commandArgs(trailingOnly = FALSE)\n needle <- \"--file=\"\n match <- grep(needle, cmdArgs)\n if (length(match) > 0) {\n # Rscript\n return(normalizePath(sub(needle, \"\", cmdArgs[match])))\n } else {\n # 'source'd via R console\n return(normalizePath(sys.frames()[[1]]$ofile))\n }\n}\n\nCURRENT_DIR <- dirname(thisFile())\nCODE_ROOT <- dirname(CURRENT_DIR)\nSCE_CACHE_DIR <- file.path(CODE_ROOT, '01-cluster-sc01-sc02')\nMETADATA_DIR <- file.path(CODE_ROOT, '00-metadata')\n\npdfPlot <- function(filename, plot, width=8, height=6) {\n pdf(file=file.path(CURRENT_DIR, filename), width=width, height=height)\n result <- plot()\n dev.off()\n return(result)\n}\n\nplotHeatmap <- function(sc02) {\n p <- DoHeatmap(\n sc02,\n genes.use = c(\"Irf8\", \"Cd209a\", \"Itgae\", \"Ccr7\"),\n cells.use = WhichCells(sc02, 10),\n slim.col.label = TRUE,\n group.by = NULL,\n draw.line = FALSE,\n group.spacing = 0\n )\n data <- [email protected][c(\"Irf8\", \"Cd209a\", \"Itgae\", \"Ccr7\"), WhichCells(sc02, 10)]\n data_gene <- 10 - apply(data, 2, which.max)\n data_max <- apply(data, 2, max)\n custom_order <- names(data_max)[order(data_gene, data_max, decreasing = TRUE)]\n p$data$cell <- factor(p$data$cell, levels = custom_order)\n p <- p + labs(x=\"Cells from cluster #10 in SC02\", tag=\"B\") +\n theme(\n axis.title.x = element_text(size=14),\n axis.text.y = element_text(size=14),\n plot.tag.position = \"topright\",\n plot.tag = element_text(size = 20)\n ) + guides(fill=guide_colorbar(\n barheight=7.8,\n title = \"Gene expression z-score\",\n title.position = \"right\",\n title.theme = element_text(angle=90, size = 10),\n label.theme = element_text(size=8, angle = 0),\n title.vjust = 0.5\n )) +\n geom_tile(colour=NA)\n plot(p)\n}\n\nplotTsne <- function(sc02) {\n p <- TSNEPlot(\n sc02,\n do.label = TRUE,\n do.return = TRUE,\n pt.size = 0.1,\n label.size = 3.5\n )\n p$layers[[1]]$aes_params$alpha = 0.7\n p <- p + theme(\n axis.text = element_blank(),\n axis.ticks = element_blank(),\n axis.title = element_text(size = 8),\n plot.tag.position = \"topright\",\n plot.tag = element_text(size = 20)\n ) + guides(colour=guide_legend(\n ncol = 2,\n override.aes = list(size = 3, alpha = 1),\n title = \"Cluster\",\n title.position = \"top\",\n title.theme = element_text(size = 10),\n title.hjust = 0.5\n )) + labs(tag = \"A\")\n plot(p)\n}\n\nmain <- function() {\n sc02 <- readRDS(file.path(SCE_CACHE_DIR, 'SC02v2.rds'))\n\n pdfPlot('sc02v2_tsne_final.pdf', function() {\n plotTsne(sc02)\n }, width = 5, height = 4)\n\n pdfPlot('sc02_cluster10.pdf', function() {\n plotHeatmap(sc02)\n }, width = 5, height = 2)\n\n\n}\n\nmain()\n" }, { "alpha_fraction": 0.5410959124565125, "alphanum_fraction": 0.568493127822876, "avg_line_length": 17.25, "blob_id": "a7028b31f25f220fa277f880b4b50b7cf166b16f", "content_id": "96071fffd43ded7545fa5e1c8bb8dea80c7a7e17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 146, "license_type": "no_license", "max_line_length": 41, "num_lines": 8, "path": "/run.sh", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ndir=$(dirname \"$0\")\nif [ \"$1\" = \"shell\" ]; then\n PYTHONPATH=\"$dir/lib/\" ipython\nelse\n PYTHONPATH=\"$dir/lib/\" python3.6 \"$@\"\nfi\n" }, { "alpha_fraction": 0.6256641745567322, "alphanum_fraction": 0.6445270776748657, "avg_line_length": 32.60714340209961, "blob_id": "2d7242522b98bd776afe9b98e3f846c2b5643a80", "content_id": "1ab93565c3f6c4aa94a6547d8131277d3af86189", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3764, "license_type": "no_license", "max_line_length": 115, "num_lines": 112, "path": "/05-catboost-eva/best_model_analyse.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport sklearn\nimport catboost\nimport scipy.sparse\nimport matplotlib\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport seaborn\nimport os.path\n\nimport sankey\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef load_predictions(path):\n clusters = pd.read_csv(os.path.join(CUR_DIR, 'MCA_clusters.csv'))\n preds = pd.read_csv(path, index_col=0)\n preds.columns = clusters.Annotation\n preds.index = preds.index.str.replace('-1', '')\n return preds\n\n\ndef heatmap(predictions):\n preds = predictions.copy()\n preds.columns = list(range(len(preds.columns)))\n preds['cluster'] = preds.idxmax(axis=1)\n preds['max_score'] = predictions.max(axis=1)\n preds.sort_values(['cluster', 'max_score'], ascending=[True, False], inplace=True)\n preds = predictions.reindex(preds.index)\n plt.figure(figsize=(16, 40))\n ax = seaborn.heatmap(preds, yticklabels=[])\n return ax.get_figure()\n\n\ndef get_second_maxes(predictions):\n second_choices = pd.DataFrame(index=predictions.columns, columns=predictions.columns)\n second_choices.fillna(0, inplace=True)\n for cell in predictions.index:\n cell_type = predictions.loc[cell, :].idxmax()\n score = predictions.loc[cell, cell_type]\n second_cell_type = predictions.loc[cell, :][predictions.loc[cell, :] < score].idxmax()\n second_choices.loc[cell_type, second_cell_type] += 1\n sums = second_choices.sum(axis=1)\n sums[sums == 0] = 1\n second_choices = second_choices.div(sums, axis='index')\n total = second_choices.sum(axis=0)\n second_choices = second_choices.reindex_axis(sorted(second_choices.columns, key=lambda x: -total[x]), axis=1)\n return second_choices\n\n\ndef plot_second_maxes(maxes):\n plt.figure(figsize=(14,14))\n sums = maxes.sum(axis=0)\n ax = seaborn.clustermap(maxes,\n xticklabels=[maxes.columns[i] + ' ({:.2f})'.format(sums[i]) for i in range(len(sums))],\n col_cluster=False,\n )\n ax.ax_heatmap.set_ylabel('Main cell type')\n ax.ax_heatmap.set_xlabel('Second cell type')\n return ax\n\n\ndef process(exp, query):\n sankey_order = pd.read_csv(\n os.path.join(os.path.dirname(CUR_DIR), 'sankey_order.csv')\n )\n exp_clusters = pd.read_csv('{}/{}_assgn.csv'.format(\n os.path.join(CUR_DIR, '..', '01-cluster-sc01-sc02'),\n query\n ), index_col=0)\n exp_clusters.columns = ['cluster']\n\n clusters = pd.read_csv('{}/{}_clusters.csv'.format(\n os.path.join(os.path.dirname(CUR_DIR), '00-metadata'),\n query\n ), index_col=0, header=None)\n clusters.index = clusters.index.str.replace('C', '').astype(int)\n\n preds = '{}-best-preds.csv'.format(exp)\n sc01 = load_predictions(os.path.join(CUR_DIR, preds))\n sc01_second_maxes = get_second_maxes(sc01)\n sc01_second_maxes.sum(axis=0).to_csv(os.path.join(CUR_DIR, '{}-second-max-total.csv'.format(exp)))\n maxes_heatmap = plot_second_maxes(sc01_second_maxes)\n maxes_heatmap.savefig(os.path.join(CUR_DIR, '{}-second-max-heatmap.png'.format(exp)))\n\n s = sankey.sankey(\n clusters.iloc[:, 0].loc[exp_clusters.cluster],\n sc01.idxmax(axis=1)[exp_clusters.index],\n alpha=.5,\n left_order=sankey_order.order\n )\n s.savefig(os.path.join(CUR_DIR, '{}-sankey.png'.format(exp)))\n\n\n sc01 = heatmap(sc01)\n sc01.savefig(os.path.join(CUR_DIR, '{}-best-heatmap.png'.format(exp)))\n\n\ndef main():\n process('sc01', 'SC01v2')\n #process('sc01-noise', 'sc01-noise-preds.csv')\n process('sc02', 'SC02v2')\n process('sc03', 'SC03')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5738858580589294, "alphanum_fraction": 0.6012510061264038, "avg_line_length": 32.07758712768555, "blob_id": "b48aba05fd88b1d0cf83ebd5a33f94a1e41cd266", "content_id": "b2868f6b2722499588eae390d3373a0256fdcdec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3837, "license_type": "no_license", "max_line_length": 81, "num_lines": 116, "path": "/11-catboost-sc03/plot_plasma_predictions.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import sickle\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scanpy.api as sc\nimport seaborn\n\n\nCUR_DIR, ROOT = sickle.paths(__file__)\n\n\ndef get_normalised_jchain(exp, annotation):\n cache_file = os.path.join(CUR_DIR, '{}-jchain.csv'.format(exp.lower()))\n if os.path.exists(cache_file):\n return pd.read_csv(cache_file, index_col=0, header=None, squeeze=True)\n\n data = sickle.load_sc_scanpy(exp, annotation)\n data = data[data.obs['n_genes'] < 4000, :]\n data = data[data.obs['n_genes'] > 300, :]\n data = data[data.obs['percent_mito'] < 0.1, :]\n sc.pp.normalize_per_cell(data, counts_per_cell_after=1e4)\n sc.pp.log1p(data)\n jchain = pd.Series(list(data[:, 'Jchain'].X), index=data.obs_names)\n jchain.to_csv(cache_file)\n return jchain\n\n\ndef plot(exp, annotation, preds, figsize=(7, 2.5), subfig=None):\n jchain = get_normalised_jchain(exp, annotation)\n preds = sickle.load_predictions(os.path.join(CUR_DIR, preds), 'SC03')\n preds.columns = preds.columns.str.replace('classical/', 'classical +\\n')\n cluster = preds.idxmax(axis=1)\n jchain_expr = pd.DataFrame(\n index=jchain.index,\n columns=preds.columns\n )\n jchain_expr.fillna(0, inplace=True)\n for column in preds.columns:\n idx = cluster.index[cluster == column]\n jchain_expr.loc[idx, column] = jchain.loc[idx]\n\n jchain_expr = jchain_expr.loc[jchain_expr.sum(axis=1) > 2, :]\n jchain_expr = jchain_expr.loc[:, jchain_expr.sum(axis=0) > 2]\n sorted_expr = jchain_expr.sum(axis=1).sort_values()\n jchain_expr = jchain_expr.reindex(sorted_expr.index)\n\n more_than_5_row = sorted_expr.index[sorted_expr >= 5][0]\n more_than_5_col = jchain_expr.loc[more_than_5_row, :].idxmax()\n less_than_5_row = sorted_expr.index[sorted_expr < 5][-1]\n less_than_5_col = jchain_expr.loc[less_than_5_row, :].idxmax()\n annot = pd.DataFrame(index=jchain_expr.index, columns=jchain_expr.columns)\n annot.fillna('', inplace=True)\n annot.loc[more_than_5_row, more_than_5_col] = '{:.1f}'.format(\n jchain_expr.loc[more_than_5_row, more_than_5_col]\n )\n annot.loc[less_than_5_row, less_than_5_col] = '{:.1f}'.format(\n jchain_expr.loc[less_than_5_row, less_than_5_col]\n )\n\n fig = plt.figure(figsize=figsize)\n grid_kws = {\"height_ratios\": (.9, .05), \"hspace\": .5}\n ax, cbar_ax = fig.subplots(2, gridspec_kw=grid_kws)\n\n ax = seaborn.heatmap(\n jchain_expr.T,\n xticklabels=[],\n cmap=\"Oranges\",\n linewidths=1,\n annot=annot.T,\n fmt='',\n annot_kws={\n 'fontsize': 10,\n 'color': 'white',\n 'weight': 'bold',\n },\n ax=ax,\n cbar_ax = cbar_ax,\n cbar_kws={\n 'orientation': 'horizontal',\n 'ticks': [0, 2.5, 5, 7],\n 'label': 'log-normalised $\\it{Jchain}$ expression'\n }\n )\n ax.figure.axes[-1].tick_params(reset=True)\n ax.figure.axes[-1].tick_params(\n labelsize=9,\n direction='inout',\n color='black',\n width=.5,\n length=6,\n pad=2,\n top=False,\n labeltop=False,\n )\n ax.figure.axes[-1].xaxis.label.set_size(14)\n ax.set_xlabel('Cells from {} dataset'.format(exp))\n ax.set_ylabel('')\n plt.tight_layout()\n if subfig:\n text_ax = ax.figure.add_axes((0.02, 0.1, 0.05, 0.05), frame_on=False)\n text_ax.set_axis_off()\n plt.text(0, 0, subfig, fontsize=30, transform=text_ax.transAxes)\n ax.figure.subplots_adjust(left=0.3, top=1, right=0.98, bottom=0.20)\n ax.figure.savefig(os.path.join(CUR_DIR, '{}-jchain.pdf'.format(exp.lower())))\n\n\ndef main():\n plot('SC01', 'SC01v2', 'sc01-preds.csv', subfig='A')\n plot('SC02', 'SC02v2', 'sc02-preds.csv', subfig='B')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5899834632873535, "alphanum_fraction": 0.6235553026199341, "avg_line_length": 30.894737243652344, "blob_id": "3ecb4cade4589db431f62b486fecd98cf7c2e138", "content_id": "576daa3fb7ad08ca30937f4bba0f0d8e58d6a421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1817, "license_type": "no_license", "max_line_length": 103, "num_lines": 57, "path": "/02-evaluate-mnn/main.R", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "SCE_CACHE_DIR <- file.path(dirname(dirname(sys.frame(1)$ofile)), '01-cluster-sc01-sc02')\nCACHE_DIR <- dirname(sys.frame(1)$ofile)\n\npdfPlot <- function(filename, plot, width=8, height=6) {\n pdf(file=file.path(CACHE_DIR, filename))\n result <- plot()\n dev.off()\n return(result)\n}\n\nmain <- function() {\n cache_file <- file.path(CACHE_DIR, 'comb.rds')\n sc01 <- readRDS(file.path(SCE_CACHE_DIR, 'SC01.rds'))\n sc03 <- readRDS(file.path(SCE_CACHE_DIR, 'SC03.rds'))\n \n if (file.exists(cache_file)) {\n comb <- readRDS(cache_file)\n } else {\n [email protected] <- \"SC01\"\n [email protected] <- \"SC03\"\n [email protected]$orig.ident <- \"SC01\"\n [email protected]$orig.ident <- \"SC03\"\n comb <- MergeSeurat(sc01, sc03, do.normalize = FALSE, add.cell.id1 = 'SC01', add.cell.id2 = 'SC03')\n \n # computes more than 2 hrs\n corrected_file <- file.path(CACHE_DIR, 'corrected.rds')\n if (file.exists(corrected_file)) {\n corrected <- readRDS(corrected_file)\n } else {\n corrected <- mnnCorrect(\n as.matrix(comb@data[,[email protected]$orig.ident == \"SC01\"]), \n as.matrix(comb@data[,[email protected]$orig.ident == \"SC03\"])\n )\n saveRDS(corrected, corrected_file)\n }\n \n [email protected] <- cbind(corrected$corrected[[1]], corrected$corrected[[2]])\n colnames([email protected]) <- [email protected]\n comb <- RunPCA(comb, pc.genes = rownames(comb@data), do.print = FALSE, pcs.compute = 40)\n comb <- RunTSNE(comb, dims.use=1:15, do.fast=TRUE)\n saveRDS(comb, cache_file)\n }\n\n \n pdfPlot(\"comb-tsne.pdf\", function() {\n TSNEPlot(comb) \n })\n pdfPlot(\"comb-tsne-sc03-plasma.pdf\", function() {\n TSNEPlot(comb, cells.highlight=paste(\"SC03\", [email protected][sc03@ident == 7], sep=\"_\")) \n })\n pdfPlot(\"comb-pc-elbow.pdf\", function() {\n plot(PCElbowPlot(comb, num.pc=40))\n })\n\n}\n\nmain()" }, { "alpha_fraction": 0.5760430693626404, "alphanum_fraction": 0.5899506211280823, "avg_line_length": 27.94805145263672, "blob_id": "caed6fbad238823cdd9b6953b8b6cdb402657bc9", "content_id": "09289c4f9f3f2c93f064cd12e9d2b099e8e6afc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2229, "license_type": "no_license", "max_line_length": 106, "num_lines": 77, "path": "/12-catboost-mca/train_predict.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import sickle\n\nimport os\nimport sys\n\nimport catboost\nimport pandas as pd\n\n\nCUR_DIR, ROOT = sickle.paths(__file__)\n\n\ndef predict(model, input_columns, experiment):\n missing_columns = input_columns[~ input_columns.isin(experiment.columns)]\n experiment = experiment.copy()\n experiment[list(missing_columns)] = pd.DataFrame([[0] * len(missing_columns)], index=experiment.index)\n return pd.DataFrame(model.predict_proba(experiment[input_columns]), index=experiment.index)\n\n\ndef train(splits):\n runs = []\n for i in range(1, splits + 1):\n runs.append(\n pd.read_csv(os.path.join(\n CUR_DIR,\n './search-{}-of-{}.csv'.format(i, splits)\n ),\n index_col=0)\n )\n runs = pd.concat(runs, ignore_index=True)\n best_row = runs.score.idxmax(axis=0)\n best_params = eval(runs.params[best_row])\n\n X, y = sickle.load_mca_lung('MCAv2')\n model = catboost.CatBoostClassifier(\n l2_leaf_reg=best_params['l2_leaf_reg'],\n learning_rate=best_params['learning_rate'],\n depth=best_params['depth'],\n iterations=200,\n random_seed=42,\n logging_level='Silent',\n loss_function='MultiClass',\n eval_metric='TotalF1',\n thread_count=20,\n )\n model_path = os.path.join(CUR_DIR, 'mca-model.cbm')\n if os.path.exists(model_path):\n model.load_model(model_path)\n else:\n model.fit(X, y)\n model.save_model(model_path)\n importances = pd.DataFrame(model._feature_importance, X.columns)\n importances[importances[0] > 0].sort_values(\n 0,\n ascending=False\n ).to_csv(os.path.join(CUR_DIR, 'mca-features.csv'))\n return model, X.columns\n\n\ndef main(splits):\n model, input_columns = train(splits)\n\n for exp in ('SC01v2', 'SC02v2', 'SC03'):\n data, _ = sickle.load_sc(exp)\n preds = predict(model, input_columns, data)\n preds.to_csv(os.path.join(\n CUR_DIR,\n '{}-preds.csv'.format(exp[:4].lower())\n ))\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('Usage: {} <N>'.format(__file__), file=sys.stderr)\n sys.exit(1)\n splits = int(sys.argv[1])\n main(splits)\n" }, { "alpha_fraction": 0.7321739196777344, "alphanum_fraction": 0.7617391347885132, "avg_line_length": 37.33333206176758, "blob_id": "3275830f6571e7da25e624631b9cb9d48eef2df5", "content_id": "2c20811c11a602bc712ad9f12d55a99fc60a17e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 575, "license_type": "no_license", "max_line_length": 148, "num_lines": 15, "path": "/12-catboost-mca/README.md", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "## Model preparation for MCA\n\n### Code\n\n`params_search.py`: code to search for best params to train MCA model (our clustering)\n\n`train_predict.py`: code to train model with best parameters from the previous step and predict SC01, SC02 and SC03. Result is in `sc*-preds.csv`\n\n`analyse.py`: code to score and plot predictions from previous steps. Figure 5\n\n`prediction_correlation.py`: code to test correlation between technical variables and prediction probability of the model on SC01. Table 2, Figure 6\n\n### Cached files\n\n`sc*-preds.csv`: predictions of SC01, SC02 and SC03\n" }, { "alpha_fraction": 0.5449541211128235, "alphanum_fraction": 0.5642201900482178, "avg_line_length": 22.191490173339844, "blob_id": "7244939bcb83b620139bfbd82ecc0400249717a7", "content_id": "8a0ea4a589ee69e12813b6765160fe27da2143f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1090, "license_type": "no_license", "max_line_length": 68, "num_lines": 47, "path": "/05-catboost-eva/dump_cv_idx.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import StratifiedKFold\n\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef path(*args):\n return os.path.join(ROOT, *args)\n\n\ndef dump(*args):\n d = os.path.join(CUR_DIR, 'cv-idx')\n if not os.path.exists(d):\n os.mkdir(d)\n return os.path.join(d, *args)\n\n\ndef main():\n X, y = utils.load_mca_lung()\n params_space = {\n 'l2_leaf_reg': [1, 3, 5, 7, 9],\n 'learning_rate': np.linspace(1e-3, 8e-1, num=10),\n 'depth': [6, 8, 10],\n }\n skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n splits = list(skf.split(X, y))\n for i, (tr_idx, test_idx) in enumerate(splits):\n y_train = y.iloc[tr_idx]\n y_test = y.iloc[test_idx]\n \n pd.Series(y_train.index).to_csv(dump(\n 'cv{}-train.csv'.format(i + 1)\n ))\n pd.Series(y_test.index).to_csv(dump(\n 'cv{}-test.csv'.format(i + 1)\n ))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5634581446647644, "alphanum_fraction": 0.5762754678726196, "avg_line_length": 32.15833282470703, "blob_id": "a278ebd403ee461b563c78c1de1a271b90dfebd5", "content_id": "0eea2293f1940e0cd3fe6b3705c6565317064945", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3979, "license_type": "no_license", "max_line_length": 88, "num_lines": 120, "path": "/05-catboost-eva/find_best_params.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport timeit\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import ParameterGrid\nimport catboost\nimport sklearn.metrics\n\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef path(*args):\n return os.path.join(ROOT, *args)\n\n\ndef save_record(record, label):\n pd.DataFrame(record, columns=['params', 'score', 'time']).to_csv(\n os.path.join(CUR_DIR, '{}.csv'.format(label))\n )\n\n\ndef eval_params(params, X_train, y_train, X_valid, y_valid):\n clf = catboost.CatBoostClassifier(\n l2_leaf_reg=params['l2_leaf_reg'],\n learning_rate=params['learning_rate'],\n depth=params['depth'],\n iterations=params.get('iters', 50),\n random_seed=42,\n logging_level='Silent',\n loss_function='MultiClass',\n eval_metric='TotalF1',\n thread_count=10,\n )\n\n clf.fit(\n X_train,\n y_train,\n )\n\n y_pred = clf.predict(X_valid)\n return sklearn.metrics.f1_score(y_valid, y_pred, average='weighted')\n\n\ndef cross_val(X, y, params, cv=5):\n skf = StratifiedKFold(n_splits=cv, shuffle=True, random_state=42)\n\n scores = []\n splits = list(skf.split(X, y))\n for i, (tr_ind, val_ind) in enumerate(splits):\n print('({}/{})'.format(i + 1, len(splits)), file=sys.stderr, end='')\n sys.stderr.flush()\n\n X_train, y_train = X.iloc[tr_ind, :], y.iloc[tr_ind]\n X_valid, y_valid = X.iloc[val_ind, :], y.iloc[val_ind]\n\n scores.append(eval_params(params, X_train, y_train, X_valid, y_valid))\n print('\\b\\b\\b\\b\\b', file=sys.stderr, end='')\n sys.stderr.flush()\n return np.mean(scores)\n\n\ndef catboost_GridSearchCV(X, y, params_space, record, cv=5, splits=1, current_split=1):\n max_score = 0\n best_params = None\n all_params = list(ParameterGrid(params_space))\n divider = current_split - 1\n my_params = [all_params[i] for i in range(len(all_params)) if i % splits == divider]\n for i, params in enumerate(my_params):\n print('{:3d}% '.format(i * 100 // len(my_params)), file=sys.stderr, end='')\n sys.stderr.flush()\n start = timeit.default_timer()\n score = cross_val(X, y, params, cv=cv)\n if score > max_score:\n max_score = score\n best_params = params\n record.append([repr(params), score, timeit.default_timer() - start])\n print('\\r' + ' ' * 20 + '\\r', file=sys.stderr, end='')\n sys.stderr.flush()\n return max_score, best_params\n\n\ndef main(outer_split, inner_split, inner_splits, record):\n X, y = utils.load_mca_lung()\n params_space = {\n 'l2_leaf_reg': [1, 3, 5, 7, 9],\n 'learning_rate': np.linspace(1e-3, 8e-1, num=10),\n 'depth': [6, 8, 10],\n }\n skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n splits = list(skf.split(X, y))\n for tr_idx, val_idx in splits[outer_split - 1:outer_split]:\n X_train, y_train = X.iloc[tr_idx, :], y.iloc[tr_idx]\n X_valid, y_valid = X.iloc[val_idx, :], y.iloc[val_idx]\n\n score, best_params = catboost_GridSearchCV(X_train, y_train,\n params_space, \n record, cv=5,\n splits=inner_splits,\n current_split=inner_split)\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 4:\n print('Usage: {} <N> <K> <T>'.format(__file__), file=sys.stderr)\n sys.exit(1)\n outer_split = int(sys.argv[1])\n inner_split = int(sys.argv[2])\n inner_splits = int(sys.argv[3])\n record = []\n main(outer_split, inner_split, inner_splits, record)\n save_record(record,\n 'search-{}+{}-of-{}'.format(outer_split, inner_split, inner_splits))\n" }, { "alpha_fraction": 0.5745912790298462, "alphanum_fraction": 0.636239767074585, "avg_line_length": 33.541175842285156, "blob_id": "a32ccf95cda389bc38601806bdb44361885cadce", "content_id": "9bed89c882fe61f7feced716fc0a286b2ea2db21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2936, "license_type": "no_license", "max_line_length": 89, "num_lines": 85, "path": "/04-evaluate-scmap/sc02.R", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "require(scmap)\nrequire(SingleCellExperiment)\nrequire(SeuratConverter)\nrequire(irr)\n\nCURRENT_DIR <- dirname(sys.frame(1)$ofile)\nCODE_ROOT <- dirname(CURRENT_DIR)\nSCE_CACHE_DIR <- file.path(CODE_ROOT, '01-cluster-sc01-sc02')\nMETADATA_DIR <- file.path(CODE_ROOT, '00-metadata')\n\n\ngetSC02 <- function() {\n cache <- file.path(CURRENT_DIR, 'sc02.rds')\n if (!file.exists(cache)) {\n sc02.seurat <- readRDS(file.path(SCE_CACHE_DIR, 'SC02v2.rds'))\n sc02 <- as(sc02.seurat, \"SingleCellExperiment\")\n counts(sc02) <- as.matrix(assay(sc02, \"raw.data\"))\n logcounts(sc02) <- log2(counts(sc02) + 1)\n rowData(sc02)$feature_symbol <- rownames(sc02)\n colData(sc02)$cell_type1 <- sc02.seurat@ident\n sc02 <- selectFeatures(sc02)\n sc02 <- indexCluster(sc02)\n sc02 <- indexCell(sc02)\n saveRDS(sc02, cache)\n } else {\n sc02 <- readRDS(cache)\n }\n return(sc02)\n}\n\n\ngetSC03 <- function() {\n cache <- file.path(CURRENT_DIR, 'sc03.rds')\n if (!file.exists(cache)) {\n sc03.seurat <- readRDS(file.path(SCE_CACHE_DIR, 'SC03.rds'))\n sc03 <- as(sc03.seurat, \"SingleCellExperiment\")\n counts(sc03) <- as.matrix(assay(sc03, \"raw.data\"))\n logcounts(sc03) <- log2(counts(sc03) + 1)\n rowData(sc03)$feature_symbol <- rownames(sc03)\n colData(sc03)$cell_type1 <- sc03.seurat@ident\n saveRDS(sc03, cache)\n } else {\n sc03 <- readRDS(cache)\n }\n return(sc03)\n}\n\n\nmain <- function() {\n sc02.clusters <- read.csv(file.path(METADATA_DIR, 'SC02v2_clusters.csv'), header=FALSE)\n sc02.clusters$V1 <- sub(\"C\", \"\", sc02.clusters$V1)\n \n sc03.clusters <- read.csv(file.path(METADATA_DIR, 'SC03_clusters.csv'), header=FALSE)\n sc03.clusters$V1 <- sub(\"C\", \"\", sc03.clusters$V1)\n \n sc02 <- getSC02()\n sc03 <- getSC03()\n \n scmap_result <- scmapCluster(projection=sc03, \n index_list=list(\n ref=metadata(sc02)$scmap_cluster_index\n ))\n labels1 <- sc03.clusters$V2[match(colData(sc03)$cell_type1, sc03.clusters$V1)]\n labels2 <- sc02.clusters$V2[match(scmap_result$combined_labs, sc02.clusters$V1)]\n names(labels2) <- rownames(colData(sc03))\n levels(labels2) <- c(levels(labels2), \"Novel cell type\")\n labels2[is.na(labels2)] <- \"Novel cell type\"\n write.csv(labels2, file.path(CURRENT_DIR, 'sc03-cluster-preds.csv'))\n \n scmap_result <- scmapCell(projection=sc03, \n index_list=list(\n ref=metadata(sc02)$scmap_cell_index\n ))\n scmap_clusters <- scmapCell2Cluster(\n scmap_result, \n list(as.character(colData(sc02)$cell_type1))\n )\n labels2 <- sc02.clusters$V2[match(scmap_clusters$combined_labs, sc02.clusters$V1)]\n names(labels2) <- rownames(colData(sc03))\n levels(labels2) <- c(levels(labels2), \"Novel cell type\")\n labels2[is.na(labels2)] <- \"Novel cell type\"\n write.csv(labels2, file.path(CURRENT_DIR, 'sc03-cell-preds.csv'))\n}\n\nmain()\n" }, { "alpha_fraction": 0.44329896569252014, "alphanum_fraction": 0.6701030731201172, "avg_line_length": 15.166666984558105, "blob_id": "1cb1c942d6f85a326629ba1d421c9cf56e23b34a", "content_id": "2f82cb26b2cb08f2a7f8275f2b746526c94ced77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 97, "license_type": "no_license", "max_line_length": 20, "num_lines": 6, "path": "/requirements.txt", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "catboost==0.8.1.1\nnumpy==1.14.2\npandas==0.22.0\nscanpy==1.2.2\nscikit-learn==0.19.1\nseaborn==0.8.1\n" }, { "alpha_fraction": 0.5837818384170532, "alphanum_fraction": 0.5859346985816956, "avg_line_length": 36.66216278076172, "blob_id": "3b05a9ccc344c6bbda62f5d4348205c7c1e624fc", "content_id": "235318b047249221d3e2d82ebca62b0cdc65cffc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2787, "license_type": "no_license", "max_line_length": 79, "num_lines": 74, "path": "/08-unseen-sc02/split.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import math\n\nimport pandas as pd\n\n\ndef split(X, y, other_proportion=1, splits=None, split_order=None, other=None):\n if other not in ('equal', 'proportional'):\n raise ValueError('other should be equal or proportional')\n result = []\n class_splits = split_y(y, splits=splits, split_order=split_order)\n for classes in class_splits:\n membership = y.isin(classes)\n cls_idx = y[membership].index\n inverse_idx = y[~membership].index\n X_cls = X.loc[cls_idx, :]\n X_other = X.loc[inverse_idx, :]\n y_cls = y.loc[cls_idx]\n y_other = y.loc[inverse_idx]\n\n y_cls = y_cls.replace({x: i for i, x in enumerate(classes)})\n\n def to_take(x):\n if other == 'equal':\n return len(y_cls) * other_proportion // len(y_other.unique())\n else:\n total = len(y_cls) * other_proportion\n class_frac = (y == x[0]).sum() / len(y)\n return int(total * class_frac)\n other_sample = y_other.groupby(y_other).apply(\n lambda x: x.sample(to_take(x), replace=len(x) < to_take(x))\n )\n other_sample.index = other_sample.index.droplevel('cluster')\n other_idx = other_sample.index\n X_cls = pd.concat([X_cls, X_other.loc[other_idx, :]])\n y_cls = pd.concat([y_cls, pd.Series(len(classes), index=other_idx)])\n result.append((classes, X_cls, y_cls))\n return result\n\n\ndef split_y(y, other_proportion=1, splits=None, split_order=None):\n result = []\n unique_classes = sorted(y.unique())\n if splits is None:\n splits = len(unique_classes)\n if splits > len(unique_classes):\n raise ValueError('number of splits too large, max {}'.format(\n len(unique_classes)\n ))\n if split_order not in ('cumsum', 'interleaved'):\n raise ValueError('split_order should be cumsum or interleaved')\n max_classes_in_split = math.ceil(len(unique_classes) / splits)\n max_items_in_split = len(y) / splits\n\n order_idx = list(range(len(unique_classes)))\n if split_order == 'interleaved':\n order = []\n for i in range(splits):\n order += order_idx[i::splits]\n order_idx = order\n\n current_split_classes = []\n current_sum = 0\n for cls, count in y.value_counts().sort_index()[order_idx].iteritems():\n current_split_classes.append(cls)\n current_sum += count\n if len(result) + 1 < splits \\\n and (current_sum >= max_items_in_split \\\n or len(current_split_classes) >= max_classes_in_split):\n result.append(current_split_classes)\n current_split_classes = []\n current_sum = 0\n if len(current_split_classes):\n result.append(current_split_classes)\n return result\n" }, { "alpha_fraction": 0.5998663902282715, "alphanum_fraction": 0.6479625701904297, "avg_line_length": 32.266666412353516, "blob_id": "f772697fd23d5eb6387788dd48eb2e255ea5ab01", "content_id": "5fca34ae31ebe8b01736e8244ea8366b984a30d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1497, "license_type": "no_license", "max_line_length": 91, "num_lines": 45, "path": "/08-unseen-sc02/utils.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import matplotlib\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use('Agg')\n\nimport numpy as np\nimport pandas as pd\nimport scanpy.api as sc\n\nimport os\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\ndef load_10x_scanpy(path, batch_label):\n sc01 = sc.read('{}/matrix.mtx'.format(path), cache=True).T\n sc01.var_names = pd.read_table('{}/genes.tsv'.format(path), header=None)[1]\n sc01.obs_names = pd.read_table('{}/barcodes.tsv'.format(path), header=None)[0]\n sc01.obs_names = sc01.obs_names.str.replace('-1', '')\n sc01.var_names_make_unique()\n sc.pp.filter_cells(sc01, min_genes=200)\n sc.pp.filter_genes(sc01, min_cells=3)\n\n mito_genes = sc01.var_names[sc01.var_names.str.match(r'^mt-')]\n sc01.obs['n_UMI'] = np.sum(sc01.X, axis=1).A1\n sc01.obs['percent_mito'] = np.sum(sc01[:, mito_genes].X, axis=1).A1 / sc01.obs['n_UMI']\n\n assgn = pd.read_csv('{}/{}_assgn.csv'.format(\n os.path.join(CUR_DIR, '..', '01-cluster-sc01-sc02'),\n batch_label,\n ), index_col=0)\n assgn.columns = ['cluster']\n\n sc01.obs['cluster'] = assgn.cluster[sc01.obs.index]\n return sc01\n\n\ndef load_10x(path, batch_label):\n sc01 = load_10x_scanpy(path, batch_label)\n exp = pd.DataFrame(sc01.X.todense(), index=sc01.obs_names, columns=sc01.var_names)\n #exp['Batch'] = batch_label\n exp.fillna(0, inplace=True)\n\n exp['cluster'] = sc01.obs.cluster[exp.index]\n exp = exp[~exp.cluster.isna()]\n return exp[exp.columns[:-1]], exp.cluster\n" }, { "alpha_fraction": 0.5665236115455627, "alphanum_fraction": 0.5885959267616272, "avg_line_length": 28.926605224609375, "blob_id": "03ac64a7986651b5ef6438c335ee9fd17a8c13f6", "content_id": "c9eedb40690b5971f00e512a36cb98306d800435", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3262, "license_type": "no_license", "max_line_length": 101, "num_lines": 109, "path": "/07-catboost-sc02/find_best_params.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport scipy.sparse\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import ParameterGrid\nimport catboost\nimport sklearn.metrics\n\nimport os\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef path(*args):\n return os.path.join(ROOT, *args)\n\n\ndef load_10x(path, batch_label):\n mtx = pd.read_csv('{}/matrix.mtx'.format(path), skiprows=3, sep=' ', header=None)\n genes = pd.read_table('{}/genes.tsv'.format(path), header=None, index_col=1)\n cells = pd.read_table('{}/barcodes.tsv'.format(path), header=None, index_col=0)\n assgn = pd.read_csv('{}/{}_assgn.csv'.format(\n os.path.join(CUR_DIR, '..', '01-cluster-sc01-sc02'),\n batch_label,\n ), index_col=0)\n assgn.columns = ['cluster']\n exp = scipy.sparse.csc_matrix((mtx[2], (mtx[0] - 1, mtx[1] - 1)), shape=(len(genes), len(cells)))\n exp = pd.SparseDataFrame(exp)\n exp.columns = cells.index.str.replace('-1', '')\n exp = exp.transpose()\n exp.columns = genes.index\n exp = exp.to_dense()\n exp['Batch'] = batch_label\n exp.fillna(0, inplace=True)\n cols = exp.columns.unique()\n exp = exp.groupby(level=0, axis=1).sum()\n exp = exp.reindex(columns=cols)\n exp = exp.join(assgn)\n exp = exp[~exp.cluster.isna()]\n return exp\n\n\ndef cross_val(X, y, params, cv=5):\n skf = StratifiedKFold(n_splits=cv, shuffle=True)\n\n scores = []\n\n for tr_ind, val_ind in skf.split(X, y):\n X_train, y_train = X.iloc[tr_ind, :], y.iloc[tr_ind]\n X_valid, y_valid = X.iloc[val_ind, :], y.iloc[val_ind]\n\n clf = catboost.CatBoostClassifier(\n l2_leaf_reg=params['l2_leaf_reg'],\n learning_rate=params['learning_rate'],\n depth=params['depth'],\n iterations=30,\n random_seed=42,\n logging_level='Silent',\n loss_function='MultiClass',\n eval_metric='TotalF1',\n #thread_count=20,\n )\n\n clf.fit(\n X_train,\n y_train,\n cat_features=[X.shape[1] - 1],\n )\n\n y_pred = clf.predict(X_valid)\n score = sklearn.metrics.f1_score(y_valid, y_pred, average='weighted')\n print(params)\n print('Score: {}'.format(score))\n print('-'*20)\n scores.append(score)\n return np.mean(scores)\n\n\ndef catboost_GridSearchCV(X, y, params_space, cv=5):\n max_score = 0\n best_params = None\n for params in list(ParameterGrid(params_space)):\n score = cross_val(X, y, params, cv=cv)\n if score > max_score:\n max_score = score\n best_params = params\n return best_params\n\n\ndef main():\n sc02 = load_10x(path('SC02'), 'SC02')\n X, y = sc02[sc02.columns[:-1]], sc02.cluster\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.1, stratify=y,\n )\n params_space = {\n 'l2_leaf_reg': [1, 3, 5, 7, 9],\n 'learning_rate': np.linspace(1e-3, 8e-1, num=10),\n 'depth': [6, 8, 10],\n }\n best_params = catboost_GridSearchCV(X_train, y_train, params_space, cv=5)\n print(best_params)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6075388193130493, "alphanum_fraction": 0.6513303518295288, "avg_line_length": 33.03773498535156, "blob_id": "5b01876e8afef9049bab1abb98c7064ff41406da", "content_id": "14401941e2d2be35bfdd45b76ea64bc7d357c881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1804, "license_type": "no_license", "max_line_length": 98, "num_lines": 53, "path": "/08-unseen-sc02/main.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\n\nimport predict\nimport split\nimport train\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef get_reference():\n global _reference\n if '_reference' not in globals():\n _reference = utils.load_10x(os.path.join(ROOT, 'SC02'), 'SC02v2')\n return _reference\n\n\ndef get_query():\n global _query\n if '_query' not in globals():\n _query = utils.load_10x(os.path.join(ROOT, 'SC03'), 'SC03')\n return _query\n\n\ndef experiment(label=None, **kwargs):\n result_path = os.path.join(CUR_DIR, 'sc03-{}.csv'.format(label))\n if not os.path.exists(result_path):\n X, y = get_reference()\n splits = split.split(\n X, y,\n other_proportion=kwargs.get('other_proportion', 1),\n splits=kwargs.get('splits'),\n split_order=kwargs.get('split_order', 'cumsum'),\n other=kwargs.get('other', 'equal')\n )\n models = train.models(splits, iterations=kwargs['catboost_iters'], label=label)\n\n sc03x, sc03y = get_query()\n predict.predict(models, X.columns, sc03x).to_csv(result_path)\n\n\nif __name__ == '__main__':\n experiment(label='it30-oth1', catboost_iters=30)\n experiment(label='it100-oth2', catboost_iters=100, other_proportion=2)\n experiment(label='it50-oth4', catboost_iters=50, other_proportion=4)\n # TODO\n experiment(label='it50-oth4-pro', catboost_iters=50, other_proportion=4, other='proportional')\n experiment(label='it200-cum2', catboost_iters=200, splits=2)\n experiment(label='it200-cum4', catboost_iters=200, splits=4)\n experiment(label='it200-int2', catboost_iters=200, splits=2, split_order='interleaved')\n experiment(label='it200-int4', catboost_iters=200, splits=4, split_order='interleaved')\n" }, { "alpha_fraction": 0.5771121978759766, "alphanum_fraction": 0.6061689853668213, "avg_line_length": 29.2297306060791, "blob_id": "58457d821573adfdbc6764838769f1e603bfbb90", "content_id": "19a855d8734efdae0f44a0ae8cdef390014cd7d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2237, "license_type": "no_license", "max_line_length": 106, "num_lines": 74, "path": "/11-catboost-sc03/train_predict.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\n\nimport pandas as pd\nimport catboost\n\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef path(*args):\n return os.path.join(ROOT, *args)\n\n\ndef predict(model, input_columns, experiment):\n missing_columns = input_columns[~ input_columns.isin(experiment.columns)]\n experiment = experiment.copy()\n experiment[list(missing_columns)] = pd.DataFrame([[0] * len(missing_columns)], index=experiment.index)\n return pd.DataFrame(model.predict_proba(experiment[input_columns]), index=experiment.index)\n\n\ndef main():\n runs = []\n for i in range(1, 6):\n runs.append(\n pd.read_csv(os.path.join(\n CUR_DIR,\n './search-{}-of-5.csv'.format(i)\n ),\n index_col=0)\n )\n runs = pd.concat(runs, ignore_index=True)\n best_row = runs.score.idxmax(axis=0)\n best_params = eval(runs.params[best_row])\n\n X, y = utils.load_10x(path('SC03'), 'SC03')\n best_model = catboost.CatBoostClassifier(\n l2_leaf_reg=best_params['l2_leaf_reg'],\n learning_rate=best_params['learning_rate'],\n depth=best_params['depth'],\n iterations=200,\n random_seed=42,\n logging_level='Silent',\n loss_function='MultiClass',\n eval_metric='TotalF1',\n thread_count=20,\n )\n model_path = os.path.join(CUR_DIR, 'sc03-model.cbm')\n if os.path.exists(model_path):\n best_model.load_model(model_path)\n else:\n best_model.fit(\n X, y, [X.shape[1] - 1]\n )\n best_model.save_model(model_path)\n importances = pd.DataFrame(best_model._feature_importance, X.columns)\n importances[importances[0] > 0].sort_values(\n 0,\n ascending=False\n ).to_csv(os.path.join(CUR_DIR, 'sc03-features.csv'))\n\n sc01, _ = utils.load_10x(path('SC01'), 'SC01v2')\n sc01_preds = predict(best_model, X.columns, sc01)\n sc01_preds.to_csv(os.path.join(CUR_DIR, 'sc01-preds.csv'))\n\n sc02, _ = utils.load_10x(path('SC02'), 'SC02v2')\n sc02_preds = predict(best_model, X.columns, sc02)\n sc02_preds.to_csv(os.path.join(CUR_DIR, 'sc02-preds.csv'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.701886773109436, "alphanum_fraction": 0.7490565776824951, "avg_line_length": 34.33333206176758, "blob_id": "a6f960da4e6738180bad4f2aad0d4739b2563767", "content_id": "0c3780debb30ad4f44b61bd620480e7fce3e27ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 530, "license_type": "no_license", "max_line_length": 141, "num_lines": 15, "path": "/07-catboost-sc02/README.md", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "## Model preparation for SC02\n\n### Code\n\n`find_best_params_v2.py`: code to search for best params to train SC02 model (SC02v2 clustering)\n\n`best_model_predict_v2.py`: code to train model with best parameters from the previous step and predict SC03. Result is in `sc03v2-preds.csv`\n\n`predict_sc01.py`: code to dump predict SC01. Result is in `sc01-preds.csv`\n\n`best_model_analyse_v2.py`: code to score and plot predictions from previous steps. Figure 4A, Figure 8\n\n### Cached files\n\n`sc*-preds.csv`: predictions by best SC02 model\n" }, { "alpha_fraction": 0.7843137383460999, "alphanum_fraction": 0.7843137383460999, "avg_line_length": 50, "blob_id": "c936ce9ea093615fcd373e2bc2eaaefedc495d4c", "content_id": "990121d671dbd4bbbc9fbb9c5ad3c8c7d1013e3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 255, "license_type": "no_license", "max_line_length": 151, "num_lines": 5, "path": "/00-metadata/README.md", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "## Cluster names and cluster correspondence\n\n`*_clisters.csv`: cluster names for our samples and MCA.\n\n`*_to_*.csv`: cluster correspondence tables between datasets. Entries in the table are classified as correct predictions, everything else as incorrect.\n" }, { "alpha_fraction": 0.5927051901817322, "alphanum_fraction": 0.6191489100456238, "avg_line_length": 35.153846740722656, "blob_id": "1af7ec034297f69c9a36135bf519f39299ab5caa", "content_id": "743d093128fe4518b35b3716d1adb0ed4a644dd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3290, "license_type": "no_license", "max_line_length": 102, "num_lines": 91, "path": "/01-cluster-sc01-sc02/sc02.R", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "require(Seurat)\n\n\nthisFile <- function() {\n cmdArgs <- commandArgs(trailingOnly = FALSE)\n needle <- \"--file=\"\n match <- grep(needle, cmdArgs)\n if (length(match) > 0) {\n # Rscript\n return(normalizePath(sub(needle, \"\", cmdArgs[match])))\n } else {\n # 'source'd via R console\n return(normalizePath(sys.frames()[[1]]$ofile))\n }\n}\n\nCURRENT_DIR <- dirname(thisFile())\nCODE_ROOT <- dirname(CURRENT_DIR)\nSCE_CACHE_DIR <- file.path(CODE_ROOT, '01-cluster-sc01-sc02')\nMETADATA_DIR <- file.path(CODE_ROOT, '00-metadata')\n\npdfPlot <- function(filename, plot, width=8, height=6) {\n pdf(file=file.path(CURRENT_DIR, filename), width=width, height=height)\n result <- plot()\n dev.off()\n return(result)\n}\n\ncluster <- function(dataset, save_as=NULL, num_pcs=NULL, resolution=0.5) {\n if (is.null(save_as)) {\n save_as <- dataset\n }\n cache_file <- paste(CURRENT_DIR, paste(save_as, \"rds\", sep='.'), sep='/')\n\n if (file.exists(cache_file)) {\n sce <- readRDS(cache_file)\n } else {\n data <- Read10X(data.dir = file.path(CODE_ROOT, \"..\", dataset, sep='/'))\n sce <- CreateSeuratObject(raw.data=data, min.cells=3, min.genes=200)\n mito.genes <- grep(pattern=\"^mt-\", x=rownames(sce@data), value=TRUE)\n percent.mito <- Matrix::colSums([email protected][mito.genes, ])/Matrix::colSums([email protected])\n sce <- AddMetaData(sce, metadata=percent.mito, col.name=\"percent.mito\")\n sce <- FilterCells(sce, subset.names = c(\"nGene\", \"percent.mito\"),\n low.thresholds = c(300, -Inf),\n high.thresholds = c(4000, 0.1))\n sce <- NormalizeData(sce)\n sce <- ScaleData(sce, vars.to.regress = c(\"nUMI\", \"percent.mito\"))\n sce <- FindVariableGenes(sce, x.low.cutoff=0.0125, x.high.cutoff=3, y.cutoff=0.5, do.plot = FALSE)\n sce <- RunPCA(sce, pc.genes = [email protected], do.print = FALSE, pcs.compute = 40)\n sce <- ProjectPCA(sce, do.print=FALSE)\n }\n\n pdfPlot(paste0(save_as, '_elbow.pdf'), function() {\n plot(PCElbowPlot(sce, num.pc = 40))\n })\n\n sce <- RunTSNE(sce, dims.use = 1:num_pcs, check_duplicates = FALSE, do.fast=TRUE)\n sce <- FindClusters(sce, dims.use = 1:num_pcs, resolution=resolution,\n print.output = FALSE, save.SNN = TRUE, force.recalc = TRUE)\n\n #sce <- SetIdent(sce, cells.use = WhichCells(sce, ident=3), 0)\n sce <- ValidateSpecificClusters(sce, 2, 0)\n ident <- as.numeric(levels(sce@ident)[sce@ident])\n ident[ident > 2] <- ident[ident > 2] - 1\n sce <- SetIdent(sce, ident.use = ident)\n\n write.csv(sce@ident, file.path(CURRENT_DIR, paste0(save_as, '_assgn.csv')))\n\n pdfPlot(paste0(save_as, '_tsne.pdf'), function() {\n TSNEPlot(sce, do.label = TRUE)\n }, width=12, height=10)\n\n saveRDS(sce, cache_file)\n return(sce)\n}\n\nmarkers <- function(sce, save_as, num_pcs, resolution) {\n markers <- FindAllMarkers(sce, only.pos = TRUE,\n min.pct = 0.25, thresh.use = 0.5,\n max.cells.per.ident = 200)\n markers_file <- file.path(CURRENT_DIR,\n paste0(save_as, \"_markers_PC1-\", num_pcs, \"res\", resolution, \".csv\"))\n write.csv(markers, markers_file)\n}\n\nmain <- function() {\n sc02 <- cluster(\"SC02\", save_as=\"SC02v2\", num_pcs = 25, resolution = 0.5)\n markers(sc02, \"SC02v2\", num_pcs = 25, resolution = 0.5)\n}\n\nmain()\n" }, { "alpha_fraction": 0.5242597460746765, "alphanum_fraction": 0.5454093217849731, "avg_line_length": 27.707143783569336, "blob_id": "c511849977f9c45559ecdd06cf187b2068cb4a12", "content_id": "88d66522addce2b0aa8bbfa828a96ebd15f7026f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4019, "license_type": "no_license", "max_line_length": 92, "num_lines": 140, "path": "/12-catboost-mca/prediction_correlation.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import sickle\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy.stats\n\n\nCUR_DIR, ROOT = sickle.paths(__file__)\nVARS = ['n_UMI', 'n_genes', 'percent_mito', 'percent_ribo']\n\n\ndef spearman(x, y):\n \"Spearman Rho\"\n return scipy.stats.spearmanr(x, y)\n\n\ndef pearson(x, y):\n \"Pearson\"\n return scipy.stats.pearsonr(x, y)\n\n\ndef plot(x, y, xlabel=None, ylabel=None, tag=None, file=None):\n fig = plt.figure(figsize=(4, 4))\n plt.plot(\n x,\n y,\n 'o',\n ms=5,\n alpha=0.4,\n markeredgewidth=0\n )\n # todo\n plt.xlabel(xlabel, fontsize=12)\n plt.ylabel(ylabel, fontsize=12)\n plt.tick_params(labelsize=8)\n fig.subplots_adjust(0.14, 0.12, 0.98, 0.98)\n if tag:\n text_ax = fig.add_axes((0.02, 0.02, 0.05, 0.05), frame_on=False)\n text_ax.set_axis_off()\n plt.text(0, 0, tag, fontsize=30, transform=text_ax.transAxes)\n fig.savefig(\n file,\n dpi=200,\n )\n\ndef main(exp, assignment, function, plot_largest=0):\n sc01 = sickle.load_sc_scanpy(exp, assignment)\n\n sc01p = sickle.load_predictions(os.path.join(\n CUR_DIR,\n '{}-preds.csv'.format(exp.lower())\n ), 'MCA')\n\n prediction = sc01p.idxmax(axis=1)\n pred_score = sc01p.max(axis=1)\n\n data = sc01.obs.copy()\n data['prediction'] = prediction[data.index]\n data['pred_score'] = pred_score[data.index]\n\n result = []\n for x in data.prediction.unique():\n datax = data.loc[data.prediction == x, VARS + ['pred_score']]\n if datax.shape[0] < 30:\n continue\n for idx, var in enumerate(VARS):\n corr, pval = function(datax['pred_score'], datax[var])\n result.append((x, datax.shape[0], var , corr, pval))\n\n datax = data[VARS + ['pred_score']]\n for idx, var in enumerate(VARS):\n corr, pval = function(datax['pred_score'], datax[var])\n result.append(('All', datax.shape[0], var, corr, pval))\n\n result = pd.DataFrame(\n result,\n columns=['Cell type', 'Size', 'Variable', function.__doc__, 'p-value']\n )\n result = result[result['p-value'] < .05]\n above_mean = result.loc[\n result[function.__doc__].abs() > result[function.__doc__].abs().mean(),\n :\n ]\n order = above_mean[function.__doc__].abs().sort_values(ascending=False)\n above_mean.reindex(order.index).to_csv(os.path.join(\n CUR_DIR,\n 'sc01-pred-score-{}.csv'.format(function.__name__)\n ), float_format='%.4g')\n\n out = \"\"\"{}\n===============\nRows: {}\nAvg correlation: {:.4f}\nAvg log10 pval: {}\nMax corr row:\n {}\n\"\"\"\n print(out.format(\n function.__doc__,\n result.shape[0],\n result[function.__doc__].abs().mean(),\n np.mean(np.log10(result.loc[result['p-value'] > 0, 'p-value'])),\n '\\n\\t'.join(str(result.loc[result[function.__doc__].abs().idxmax(), :]).split('\\n'))\n ))\n\n human_names = {\n 'percent_mito': 'Percentage of mitochondial genes',\n 'n_UMI': 'Number of UMIs'\n }\n\n alpha = 'ABCDEFG'\n if plot_largest:\n for i, (cell_type, _, var, coeff, _) in enumerate(above_mean.iloc[\n :plot_largest,\n :].itertuples(index=False)):\n datax = data.loc[data.prediction == cell_type, [var, 'pred_score']]\n plot(\n datax[var],\n datax['pred_score'],\n xlabel=human_names.get(var, var),\n ylabel='Prediction probability',\n tag=alpha[i],\n file=os.path.join(CUR_DIR, 'correlation{}.pdf'.format(i + 1)),\n )\n plot(\n datax[var].rank(),\n datax['pred_score'].rank(),\n xlabel=human_names.get(var, var),\n ylabel='Prediction probability',\n file=os.path.join(CUR_DIR, 'correlation{}-rank.pdf'.format(i + 1)),\n )\n\n\n\nif __name__ == '__main__':\n main('SC01', 'SC01v2', spearman, 2)\n #main('SC01', 'SC01v2', pearson)\n" }, { "alpha_fraction": 0.5867903828620911, "alphanum_fraction": 0.6031659245491028, "avg_line_length": 24.80281639099121, "blob_id": "1fb339d3638d6b050fdba364551345232b576efd", "content_id": "0975410a4d2a86ab363f099d1eddb82eadb59440", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1832, "license_type": "no_license", "max_line_length": 86, "num_lines": 71, "path": "/12-catboost-mca/analyse.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import sickle\n\nimport os\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn\n\nimport sankey\nimport utils\n\n\nCUR_DIR, ROOT = sickle.paths(__file__)\n\n\ndef heatmap(predictions, figsize=(16, 20)):\n preds = predictions.copy()\n preds.columns = list(range(len(preds.columns)))\n preds['cluster'] = preds.idxmax(axis=1)\n preds['max_score'] = predictions.max(axis=1)\n preds.sort_values(['cluster', 'max_score'], ascending=[True, False], inplace=True)\n preds = predictions.reindex(preds.index)\n plt.figure(figsize=figsize)\n ax = seaborn.heatmap(preds, yticklabels=[], rasterized=True)\n fig = ax.get_figure()\n fig.tight_layout()\n return fig\n\n\ndef process(exp, reference, query, tag=None):\n exp_clusters = sickle.assignments(query)\n\n clusters = sickle.load_clusters(query)\n\n preds = sickle.load_predictions(\n os.path.join(CUR_DIR, '{}-preds.csv'.format(exp)),\n reference\n )\n\n hmap = heatmap(preds)\n hmap.savefig(os.path.join(CUR_DIR, '{}-heatmap.pdf'.format(exp)))\n\n seaborn.set(font_scale=1)\n mapping = sickle.mapping(query, reference)\n s = sankey.sankey(\n clusters.iloc[:, 0].loc[exp_clusters],\n preds.idxmax(axis=1),\n alpha=.7,\n left_order=sickle.sankey_order(),\n mapping=mapping,\n tag=tag\n )\n s.savefig(os.path.join(CUR_DIR, '{}-sankey.pdf'.format(exp)))\n\n if mapping:\n open(os.path.join(CUR_DIR, '{}-f1.txt'.format(exp)), 'w').write(\n 'F1 score: {:.4f}'.format(\n mapping.f1(clusters.iloc[:, 0].loc[exp_clusters],\n preds.idxmax(axis=1))\n )\n )\n\n\ndef main():\n process('sc01', 'MCA', 'SC01v2', tag='A')\n process('sc02', 'MCA', 'SC02v2', tag='B')\n process('sc03', 'MCA', 'SC03')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6639838814735413, "alphanum_fraction": 0.7887324094772339, "avg_line_length": 31.064516067504883, "blob_id": "b5d2991ee6b207fd40bf9305f34c556aeb520db2", "content_id": "0d199abaac66856a2c16962720130f77512ff584", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 994, "license_type": "no_license", "max_line_length": 81, "num_lines": 31, "path": "/copy-figures.sh", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nrm -rf figs\nmkdir figs\n\n\ncp nested-cv.pdf figs/\n\ncp 01-cluster-sc01-sc02/sc02v2_tsne_final.pdf figs/sc02-tsne.pdf\ncp 01-cluster-sc01-sc02/sc02_cluster10.pdf figs/sc02-cluster10.pdf\n\ncp 04-evaluate-scmap/sc03-cluster-sankey.pdf figs/sc03-to-scmap.pdf\n\ncp 05-catboost-eva/cv3-confusion.pdf figs/\n\ncp 07-catboost-sc02/sc01-sankey.pdf figs/sc01-to-sc02.pdf\ncp 07-catboost-sc02/sc03v2-bcells-heatmap.pdf figs/sc03-bcells.pdf\ncp 07-catboost-sc02/sc03v2-plasma-heatmap.pdf figs/sc03-plasma.pdf\n\ncp 08-unseen-sc02/sc03-it50-oth4-sankey.pdf figs/sc03-to-ensemble.pdf\ncp 08-unseen-sc02/sc03-it50-oth4-plasma-heatmap.pdf figs/sc03-plasma-ensemble.pdf\n\ncp 10-catboost-sc01/sc02-sankey.pdf figs/sc02-to-sc01.pdf\n\ncp 11-catboost-sc03/sc01-jchain.pdf figs/\ncp 11-catboost-sc03/sc02-jchain.pdf figs/\n\ncp 12-catboost-mca/sc01-sankey.pdf figs/sc01-to-mca.pdf\ncp 12-catboost-mca/sc02-sankey.pdf figs/sc02-to-mca.pdf\ncp 12-catboost-mca/correlation1.pdf figs/\ncp 12-catboost-mca/correlation2.pdf figs/\n" }, { "alpha_fraction": 0.6119614243507385, "alphanum_fraction": 0.6405895948410034, "avg_line_length": 33.588233947753906, "blob_id": "a68182f369f1ce215b3ea71d26beede3c15f95d7", "content_id": "8a244e2f5868fdccd6d8d4034b2b382f70e8a5da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3528, "license_type": "no_license", "max_line_length": 106, "num_lines": 102, "path": "/05-catboost-eva/best_model_predict.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport sklearn\nimport catboost\nimport scipy.sparse\nimport matplotlib\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use('Agg')\nimport seaborn\nimport os.path\n\n\nCUR_DIR = os.path.dirname(__file__)\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef path(*args):\n return os.path.join(ROOT, *args)\n\ndef load_mca_lung():\n lung1 = pd.read_csv(path('rmbatch_dge/Lung1_rm.batch_dge.txt'), header=0, sep=' ', quotechar='\"')\n lung2 = pd.read_csv(path('rmbatch_dge/Lung2_rm.batch_dge.txt'), header=0, sep=' ', quotechar='\"')\n lung3 = pd.read_csv(path('rmbatch_dge/Lung3_rm.batch_dge.txt'), header=0, sep=' ', quotechar='\"')\n\n lung1 = lung1.transpose()\n lung2 = lung2.transpose()\n lung3 = lung3.transpose()\n lung = pd.concat([lung1, lung2, lung3])\n\n cell_types = pd.read_csv(path('MCA_assign.csv'), index_col=0)\n cell_types = cell_types[cell_types.Tissue == 'Lung']\n cell_types = cell_types.set_index('Cell.name')\n cell_types = cell_types[['ClusterID', 'Batch']]\n\n lung = lung.join(cell_types)\n lung = lung[~lung.Batch.isna()]\n lung.fillna(0, inplace=True)\n\n X = lung[lung.columns[lung.columns != 'ClusterID']]\n y = lung.ClusterID\n y = y.str.replace('Lung_', '')\n y = y.astype('int')\n y = y - 1\n return X, y\n\ndef load_10x(path, batch_label):\n mtx = pd.read_csv('{}/matrix.mtx'.format(path), skiprows=3, sep=' ', header=None)\n genes = pd.read_table('{}/genes.tsv'.format(path), header=None, index_col=1)\n cells = pd.read_table('{}/barcodes.tsv'.format(path), header=None, index_col=0)\n exp = scipy.sparse.csc_matrix((mtx[2], (mtx[0] - 1, mtx[1] - 1)), shape=(len(genes), len(cells)))\n exp = pd.SparseDataFrame(exp)\n exp.columns = cells.index\n exp = exp.transpose()\n exp.columns = genes.index\n exp = exp.to_dense()\n exp['Batch'] = batch_label\n exp.fillna(0, inplace=True)\n exp = exp.groupby(level=0, axis=1).sum()\n return exp\n\ndef predict(model, input_columns, experiment):\n missing_columns = input_columns[~ input_columns.isin(experiment.columns)]\n experiment = experiment.copy()\n experiment[list(missing_columns)] = pd.DataFrame([[0] * len(missing_columns)], index=experiment.index)\n return pd.DataFrame(model.predict_proba(experiment[input_columns]), index=experiment.index)\n\ndef main():\n X, y = load_mca_lung()\n best_model = catboost.CatBoostClassifier(\n l2_leaf_reg=2,\n learning_rate=0.468,\n depth=10,\n iterations=200,\n random_seed=42,\n logging_level='Silent',\n loss_function='MultiClass',\n eval_metric='TotalF1',\n thread_count=20,\n )\n model_path = os.path.join(CUR_DIR, 'mca-lung-best-model.cbm')\n if os.path.exists(model_path):\n best_model.load_model(model_path)\n else:\n best_model.fit(\n X, y, [X.shape[1] - 1]\n )\n best_model.save_model(model_path)\n\n sc01 = load_10x(path('SC01'), 'SC01')\n sc02 = load_10x(path('SC02'), 'SC02')\n sc03 = load_10x(path('SC03'), 'SC03')\n\n predictions01 = predict(best_model, X.columns, sc01)\n predictions02 = predict(best_model, X.columns, sc02)\n predictions03 = predict(best_model, X.columns, sc03)\n\n pd.DataFrame(predictions01).to_csv(os.path.join(CUR_DIR, 'sc01-best-preds.csv'))\n pd.DataFrame(predictions02).to_csv(os.path.join(CUR_DIR, 'sc02-best-preds.csv'))\n pd.DataFrame(predictions03).to_csv(os.path.join(CUR_DIR, 'sc03-best-preds.csv'))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6165473461151123, "alphanum_fraction": 0.6515513062477112, "avg_line_length": 26.326086044311523, "blob_id": "c7f3ee16a5f254a952406d4cfaab650bd701cf1c", "content_id": "228f7c614fe7046c5f542e4cb710ac3dfe950086", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1257, "license_type": "no_license", "max_line_length": 106, "num_lines": 46, "path": "/07-catboost-sc02/predict_sc01.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\n\nimport pandas as pd\nimport catboost\n\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef path(*args):\n return os.path.join(ROOT, *args)\n\n\ndef predict(model, input_columns, experiment):\n missing_columns = input_columns[~ input_columns.isin(experiment.columns)]\n experiment = experiment.copy()\n experiment[list(missing_columns)] = pd.DataFrame([[0] * len(missing_columns)], index=experiment.index)\n return pd.DataFrame(model.predict_proba(experiment[input_columns]), index=experiment.index)\n\n\ndef main():\n X, _ = utils.load_10x(path('SC02'), 'SC02v2')\n best_model = catboost.CatBoostClassifier(\n l2_leaf_reg=7,\n learning_rate=0.622,\n depth=10,\n iterations=200,\n random_seed=42,\n logging_level='Silent',\n loss_function='MultiClass',\n eval_metric='TotalF1',\n thread_count=20,\n )\n model_path = os.path.join(CUR_DIR, 'sc02v2-best-model.cbm')\n best_model.load_model(model_path)\n\n sc01, _ = utils.load_10x(path('SC01'), 'SC01v2')\n sc01_preds = predict(best_model, X.columns, sc01)\n sc01_preds.to_csv(os.path.join(CUR_DIR, 'sc01-preds.csv'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5570878982543945, "alphanum_fraction": 0.5750480890274048, "avg_line_length": 29.871286392211914, "blob_id": "d5f9934fa0fdee532c9e7e152f1af5f1ade75fdd", "content_id": "50c2dcf36dcf5e9ca5887aa570c2aea57d188e25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3118, "license_type": "no_license", "max_line_length": 90, "num_lines": 101, "path": "/07-catboost-sc02/find_best_params_v2.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\nimport sys\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import ParameterGrid\nimport catboost\nimport sklearn.metrics\n\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef path(*args):\n return os.path.join(ROOT, *args)\n\n\ndef cross_val(X, y, params, cv=5):\n skf = StratifiedKFold(n_splits=cv, shuffle=True)\n\n scores = []\n splits = list(skf.split(X, y))\n for i, (tr_ind, val_ind) in enumerate(splits):\n print('({}/{})'.format(i, len(splits)), file=sys.stderr, end='')\n sys.stderr.flush()\n\n X_train, y_train = X.iloc[tr_ind, :], y.iloc[tr_ind]\n X_valid, y_valid = X.iloc[val_ind, :], y.iloc[val_ind]\n\n clf = catboost.CatBoostClassifier(\n l2_leaf_reg=params['l2_leaf_reg'],\n learning_rate=params['learning_rate'],\n depth=params['depth'],\n iterations=30,\n random_seed=42,\n logging_level='Silent',\n loss_function='MultiClass',\n eval_metric='TotalF1',\n thread_count=20,\n )\n\n clf.fit(\n X_train,\n y_train,\n cat_features=[X.shape[1] - 1],\n )\n\n y_pred = clf.predict(X_valid)\n score = sklearn.metrics.f1_score(y_valid, y_pred, average='weighted')\n scores.append(score)\n print('\\b\\b\\b\\b\\b', file=sys.stderr, end='')\n sys.stderr.flush()\n return np.mean(scores)\n\n\ndef catboost_GridSearchCV(X, y, params_space, cv=5, splits=1, current_split=1):\n max_score = 0\n best_params = None\n all_params = list(ParameterGrid(params_space))\n divider = current_split - 1\n my_params = [all_params[i] for i in range(len(all_params)) if i % splits == divider]\n for i, params in enumerate(my_params):\n print('{:3d}% '.format(i * 100 // len(my_params)), file=sys.stderr, end='')\n sys.stderr.flush()\n score = cross_val(X, y, params, cv=cv)\n if score > max_score:\n max_score = score\n best_params = params\n print('\\r' + ' ' * 20 + '\\r', file=sys.stderr, end='')\n sys.stderr.flush()\n return max_score, best_params\n\n\ndef main(splits, current_split):\n X, y = utils.load_10x(path('SC02'), 'SC02v2')\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.1, stratify=y, random_state=42,\n )\n params_space = {\n 'l2_leaf_reg': [1, 3, 5, 7, 9],\n 'learning_rate': np.linspace(1e-3, 8e-1, num=10),\n 'depth': [6, 8, 10],\n }\n score, best_params = catboost_GridSearchCV(X_train, y_train, params_space, cv=5,\n splits=splits, current_split=current_split)\n print(score)\n print(best_params)\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 3:\n print('Usage: {} <N> <K>'.format(__file__), file=sys.stderr)\n sys.exit(1)\n splits = int(sys.argv[1])\n my_split = int(sys.argv[2])\n main(splits, my_split)\n" }, { "alpha_fraction": 0.575883150100708, "alphanum_fraction": 0.5971975326538086, "avg_line_length": 31.902597427368164, "blob_id": "7e6163a6f1ff166bad9d0c4349158cfa18c07cb1", "content_id": "961ef553ac551b0d30a1e0169848533140f7e258", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5067, "license_type": "no_license", "max_line_length": 115, "num_lines": 154, "path": "/07-catboost-sc02/best_model_analyse_v2.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import sickle\n\nimport os\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn\n\nimport sankey\nimport utils\n\n\nCUR_DIR, ROOT = sickle.paths(__file__)\n\n\ndef heatmap(predictions, label=None, figsize=(20, 8), subfig=None):\n preds = predictions.copy()\n preds.columns = list(range(len(preds.columns)))\n preds['cluster'] = preds.idxmax(axis=1)\n preds['max_score'] = predictions.max(axis=1)\n preds.sort_values(['cluster', 'max_score'], ascending=[True, False], inplace=True)\n preds = predictions.reindex(preds.index)\n plt.figure(figsize=figsize)\n seaborn.set(font_scale=2.2)\n ax = seaborn.heatmap(\n preds.T,\n xticklabels=[],\n cmap=\"Blues\",\n cbar_kws={\n 'ticks': [0, 0.2, 0.4, 0.6, 0.8, 1]\n },\n rasterized=True\n )\n\n if label:\n ax.set_xlabel(label)\n else:\n ax.set_xlabel('')\n ax.set_ylabel('')\n ax.collections[0].set_clim(0, 1)\n\n ax.figure.axes[-1].tick_params(labelsize=10)\n ax.figure.axes[-1].set_ylabel('Prediction probability')\n\n ax.figure.tight_layout()\n ax.figure.subplots_adjust(right=1.04)\n if subfig:\n text_ax = ax.figure.add_axes((0.02, 0.9, 0.05, 0.05), frame_on=False)\n text_ax.set_axis_off()\n plt.text(0, 0, subfig, fontsize=30, transform=text_ax.transAxes, weight='black')\n seaborn.set(font_scale=1)\n return ax.figure\n\n\ndef get_second_maxes(predictions):\n second_choices = pd.DataFrame(index=predictions.columns, columns=predictions.columns)\n second_choices.fillna(0, inplace=True)\n for cell in predictions.index:\n cell_type = predictions.loc[cell, :].idxmax()\n score = predictions.loc[cell, cell_type]\n second_cell_type = predictions.loc[cell, :][predictions.loc[cell, :] < score].idxmax()\n second_choices.loc[cell_type, second_cell_type] += 1\n sums = second_choices.sum(axis=1)\n sums[sums == 0] = 1\n second_choices = second_choices.div(sums, axis='index')\n total = second_choices.sum(axis=0)\n second_choices = second_choices.reindex(columns=sorted(second_choices.columns, key=lambda x: -total[x]))\n return second_choices\n\n\ndef plot_second_maxes(maxes):\n plt.figure(figsize=(14,14))\n sums = maxes.sum(axis=0)\n ax = seaborn.clustermap(maxes,\n xticklabels=[maxes.columns[i] + ' ({:.2f})'.format(sums[i]) for i in range(len(sums))],\n col_cluster=False,\n )\n ax.ax_heatmap.set_ylabel('Main cell type')\n ax.ax_heatmap.set_xlabel('Second cell type')\n return ax\n\n\ndef process(exp, reference, query, tag=None):\n exp_clusters = sickle.assignments(query)\n\n clusters = pd.read_csv('{}/{}_clusters.csv'.format(\n os.path.join(os.path.dirname(CUR_DIR), '00-metadata'),\n query\n ), index_col=0, header=None)\n clusters.index = clusters.index.str.replace('C', '').astype(int)\n\n preds = utils.load_predictions(\n os.path.join(CUR_DIR, '{}-preds.csv'.format(exp)),\n reference\n )\n\n # second_maxes = get_second_maxes(preds)\n # maxes_heatmap = plot_second_maxes(second_maxes)\n # maxes_heatmap.savefig(os.path.join(CUR_DIR, '{}-second-max-heatmap.png'.format(exp)))\n #\n # if query == 'SC03':\n # plasma_second_maxes = get_second_maxes(preds.loc[exp_clusters.index[exp_clusters == 7],:])\n # maxes_heatmap = plot_second_maxes(plasma_second_maxes)\n # plt.suptitle('Second max predictions for Plasma cells')\n # maxes_heatmap.savefig(os.path.join(CUR_DIR, '{}-plasma-second-max-heatmap.png'.format(exp)))\n\n hmap = heatmap(preds)\n hmap.savefig(os.path.join(CUR_DIR, '{}-heatmap.pdf'.format(exp)))\n\n if query == 'SC03':\n hmap = heatmap(\n preds.loc[exp_clusters.index[exp_clusters == 2], :],\n label=r'$\\it{B\\ cells}$ from SC03 dataset',\n figsize=(16, 8),\n subfig='A'\n )\n hmap.savefig(os.path.join(CUR_DIR, '{}-bcells-heatmap.pdf'.format(exp)))\n\n hmap = heatmap(\n preds.loc[exp_clusters.index[exp_clusters == 7], :],\n label=r'$\\it{Plasma\\ cells}$ from SC03 dataset',\n figsize=(16, 8),\n subfig='B'\n )\n hmap.savefig(os.path.join(CUR_DIR, '{}-plasma-heatmap.pdf'.format(exp)))\n\n mapping = sickle.mapping(query, reference)\n s = sankey.sankey(\n clusters.iloc[:, 0].loc[exp_clusters],\n preds.idxmax(axis=1),\n alpha=.7,\n left_order=sickle.sankey_order(),\n mapping=mapping,\n tag=tag\n )\n s.savefig(os.path.join(CUR_DIR, '{}-sankey.pdf'.format(exp)))\n\n if mapping:\n open(os.path.join(CUR_DIR, '{}-f1.txt'.format(exp)), 'w').write(\n 'F1 score: {:.4f}'.format(\n mapping.f1(clusters.iloc[:, 0].loc[exp_clusters],\n preds.idxmax(axis=1))\n )\n )\n\n\ndef main():\n process('sc03v2', 'SC02v2', 'SC03')\n #process('sc03v2-noisy', 'SC02v2', 'SC03')\n process('sc01', 'SC02v2', 'SC01v2', tag='A')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7183364629745483, "alphanum_fraction": 0.760869562625885, "avg_line_length": 54.68421173095703, "blob_id": "47b0b1ed0ec753e948f9ec6a2d8025fd2e3893bd", "content_id": "2c29c2ae1fa6f83ed100819b1a26e9ed6b028c1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1058, "license_type": "no_license", "max_line_length": 357, "num_lines": 19, "path": "/01-cluster-sc01-sc02/README.md", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "## Clustering of SC01, SC02 and SC03 with Seurat\n\n### Code\n\n`main.R`: code to initially cluster SC01, SC02 and SC03. Caches Seurat objects in RDS files, saves PCA elbow plots, tSNE plots and tables with marker genes for each cluster.\n\n`sc01.R`: code to produce final clustering of SC01 (SC01v2).\n\n`sc02.R`: code to produce final clustering of SC02 (SC02v2).\n\n`sc02_b_cells.R`: code to inspect differences between 2 clusters of B cells in the initial clustering of SC02.\n\n`plot_sc02_10.R`: code to plot Figure 2: SC02v2 tSNE + expression of DC subtypes marker genes in cluster #10.\n\n### Cached files\n\n`*_markers_*.csv`: tables of genes, that characterise each cluster in each dataset. This is the output of `FindAllMarkers` function in Seurat. It lists top differentially-expressed genes for all clusters, with their average log-fold change and correspondent p-value. For cluster names see `00-metadata`. For this table for MCA dataset, see `13-cluster-mca`.\n\n`*_assgn.csv`: tables of cell assignments in datasets. Contains cell ids and their cluster number.\n" }, { "alpha_fraction": 0.5996050238609314, "alphanum_fraction": 0.6586028337478638, "avg_line_length": 38.7156867980957, "blob_id": "dcd3ffb4404a743c8d8957eb7e950702e56807e9", "content_id": "f92652452ddb900d8eb3a9da2de9be0fb06f0441", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4051, "license_type": "no_license", "max_line_length": 87, "num_lines": 102, "path": "/04-evaluate-scmap/main.R", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "require(scmap)\nrequire(SingleCellExperiment)\nrequire(SeuratConverter)\nrequire(irr)\n\nCURRENT_DIR <- dirname(sys.frame(1)$ofile)\nCODE_ROOT <- dirname(CURRENT_DIR)\nSCE_CACHE_DIR <- file.path(CODE_ROOT, '01-cluster-sc01-sc02')\nMETADATA_DIR <- file.path(CODE_ROOT, '00-metadata')\n\ngetScmapScore <- function(ref, query) {\n # genes <- head(rownames([email protected]), no_of_genes)\n # rowData(sc01)$scmap_features <- rownames(sc01) %in% genes\n ref <- indexCluster(ref)\n scmap_result <- scmapCluster(projection=query, \n index_list=list(\n ref=metadata(ref)$scmap_cluster_index\n ))\n kappa <- kappa2(data.frame(\n colData(query)$cell_type1,\n scmap_result$combined_labs\n )[scmap_result$combined_labs != \"unassigned\", ])$value\n assigned_frac <- sum(scmap_result$combined_labs != \"unassigned\") / ncol(query)\n return(list(kappa=kappa, assigned_frac=assigned_frac))\n}\n\nmain <- function() {\n sc01.seurat <- readRDS(file.path(SCE_CACHE_DIR, 'SC01.rds'))\n sc01.clusters <- read.csv(file.path(METADATA_DIR, 'SC01_clusters.csv'), header=FALSE)\n sc01.clusters$V1 <- sub(\"C\", \"\", sc01.clusters$V1)\n sc01 <- as(sc01.seurat, \"SingleCellExperiment\")\n counts(sc01) <- as.matrix(assay(sc01, \"raw.data\"))\n logcounts(sc01) <- log2(counts(sc01) + 1)\n rowData(sc01)$feature_symbol <- rownames(sc01)\n colData(sc01)$cell_type1 <- sc01.seurat@ident\n \n rowData(sc01)$scmap_features <- rownames(sc01) %in% rownames(head([email protected], 500))\n res <- getScmapScore(sc01, sc01)\n cat(paste(\"Scmap SC01 on SC01.\ncounts <- raw.data\nlogcounts <- log2(counts + 1)\nSeurat top 500 features\nKappa:\", res$kappa, \", Assigned frac:\", res$assigned_frac),\n file=file.path(CURRENT_DIR, \"sc01-on-sc01.txt\"))\n\n sc01 <- selectFeatures(sc01)\n res <- getScmapScore(sc01, sc01)\n cat(paste(\"\\n\\nScmap SC01 on SC01.\ncounts <- raw.data\nlogcounts <- log2(counts + 1)\nKappa:\", res$kappa, \", Assigned frac:\", res$assigned_frac),\n file=file.path(CURRENT_DIR, \"sc01-on-sc01.txt\"), append=TRUE)\n \n counts(sc01) <- as.matrix(assay(sc01, \"raw.data\"))\n logcounts(sc01) <- as.matrix(assay(sc01, \"data\"))\n sc01 <- selectFeatures(sc01)\n res <- getScmapScore(sc01, sc01)\n cat(paste(\"\\n\\nScmap SC01 on SC01.\ncounts <- raw.data\nlogcounts <- data\nKappa:\", res$kappa, \", Assigned frac:\", res$assigned_frac),\n file=file.path(CURRENT_DIR, \"sc01-on-sc01.txt\"), append=TRUE)\n \n counts(sc01) <- NULL\n logcounts(sc01) <- as.matrix(assay(sc01, \"data\"))\n sc01 <- selectFeatures(sc01)\n res <- getScmapScore(sc01, sc01)\n cat(paste(\"\\n\\nScmap SC01 on SC01.\ncounts <- NULL\nlogcounts <- data\nKappa:\", res$kappa, \", Assigned frac:\", res$assigned_frac),\n file=file.path(CURRENT_DIR, \"sc01-on-sc01.txt\"), append=TRUE)\n \n sc01 <- as(sc01.seurat, \"SingleCellExperiment\")\n counts(sc01) <- as.matrix(assay(sc01, \"raw.data\"))\n logcounts(sc01) <- log2(counts(sc01) + 1)\n rowData(sc01)$feature_symbol <- rownames(sc01)\n colData(sc01)$cell_type1 <- sc01.seurat@ident\n sc01 <- selectFeatures(sc01)\n sc01 <- indexCluster(sc01)\n \n sc03.seurat <- readRDS(file.path(SCE_CACHE_DIR, 'SC03.rds'))\n sc03.clusters <- read.csv(file.path(METADATA_DIR, 'SC03_clusters.csv'), header=FALSE)\n sc03.clusters$V1 <- sub(\"C\", \"\", sc03.clusters$V1)\n sc03 <- as(sc03.seurat, \"SingleCellExperiment\")\n counts(sc03) <- as.matrix(assay(sc03, \"raw.data\"))\n logcounts(sc03) <- log2(counts(sc03) + 1)\n rowData(sc03)$feature_symbol <- rownames(sc03)\n colData(sc03)$cell_type1 <- sc03.seurat@ident\n \n scmap_result <- scmapCluster(projection=sc03, \n index_list=list(\n ref=metadata(sc01)$scmap_cluster_index\n ))\n labels1 <- sc03.clusters$V2[match(colData(sc03)$cell_type1, sc03.clusters$V1)]\n labels2 <- sc01.clusters$V2[match(scmap_result$combined_labs, sc01.clusters$V1)]\n levels(labels2) <- c(levels(labels2), \"Unassigned\")\n labels2[is.na(labels2)] <- \"Unassigned\"\n plot(getSankey(labels1, labels2, plot_width=800, plot_height=800))\n}\n\nmain()\n" }, { "alpha_fraction": 0.5674132704734802, "alphanum_fraction": 0.6130874156951904, "avg_line_length": 30.63888931274414, "blob_id": "639fdd5b8acee03c0b2cee77ffe33501e5478a15", "content_id": "723f8351c18b7438c8489494f9adfab53d1fc576", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2277, "license_type": "no_license", "max_line_length": 96, "num_lines": 72, "path": "/07-catboost-sc02/best_model_map.R", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "require(Seurat)\nrequire(scmap)\n\n\nthisFile <- function() {\n cmdArgs <- commandArgs(trailingOnly = FALSE)\n needle <- \"--file=\"\n match <- grep(needle, cmdArgs)\n if (length(match) > 0) {\n # Rscript\n return(normalizePath(sub(needle, \"\", cmdArgs[match])))\n } else {\n # 'source'd via R console\n return(normalizePath(sys.frames()[[1]]$ofile))\n }\n}\n\nCURRENT_DIR <- dirname(thisFile())\nCODE_ROOT <- dirname(CURRENT_DIR)\nSCE_CACHE_DIR <- file.path(CODE_ROOT, '01-cluster-sc01-sc02')\nMETADATA_DIR <- file.path(CODE_ROOT, '00-metadata')\n\npdfPlot <- function(filename, plot, width=14, height=6) {\n pdf(file=file.path(CURRENT_DIR, filename), width=width, height=height)\n result <- plot()\n dev.off()\n return(result)\n}\n\nprocess <- function(exp) {\n sc03 <- readRDS(file.path(SCE_CACHE_DIR, paste(toupper(exp), 'rds', sep='.')))\n sc03.clusters <- read.csv(file.path(METADATA_DIR, paste0(exp, '_clusters.csv')), header=FALSE)\n sc03.clusters$V1 <- sub(\"C\", \"\", sc03.clusters$V1)\n \n sc02.clusters <- read.csv(file.path(METADATA_DIR, 'SC02_clusters.csv'), header=FALSE)\n sc02.clusters$V1 <- sub(\"C\", \"\", sc02.clusters$V1)\n sc02.clusters$V2 <- paste(sc02.clusters$V2, sc02.clusters$V1)\n \n preds <- read.csv(file.path(CURRENT_DIR, paste0(exp, '-preds.csv')))\n preds$cluster <- apply(preds[,-1], 1, which.max) - 1\n preds$X0 <- sub(\"-1\", \"\", preds$X0)\n preds <- merge([email protected], preds, by.x=\"x\", by.y=\"X0\")\n sc03 <- StashIdent(sc03, save.name = 'orig')\n sc03 <- SetIdent(sc03, \n ident.use = sc02.clusters$V2[match(\n preds$cluster, \n sc02.clusters$V1\n )]\n )\n pdfPlot(paste0(exp, '-tsne.pdf'), function() {\n TSNEPlot(sc03)\n })\n \n labels1 <- sc03.clusters$V2[match([email protected]$orig, sc03.clusters$V1)]\n #labels2 <- mca.clusters$Annotation[match(sc01@ident, mca.clusters$ClusterID)]\n #levels(labels2) <- c(levels(labels2), \"Unassigned\")\n #labels2[is.na(labels2)] <- \"Unassigned\"\n plot(getSankey(labels1, \n sc03@ident, \n plot_width = 800, \n plot_height = 800, \n colors = substr(rainbow(length(unique(labels1))), 1, 7)\n ))\n}\n\nmain <- function() {\n #process('sc01')\n #process('sc02')\n process('sc03')\n}\n\nmain()" }, { "alpha_fraction": 0.6361072063446045, "alphanum_fraction": 0.6483309864997864, "avg_line_length": 35.050846099853516, "blob_id": "a7b9bf4b1ab9ea72298ea99dd65bb56bfd7cabce", "content_id": "9282cf374a15ca752d5a80f32aa5e97e72436b26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2127, "license_type": "no_license", "max_line_length": 105, "num_lines": 59, "path": "/05-catboost-eva/score.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\n\nimport numpy as np\nimport pandas as pd\nimport sklearn.metrics\nfrom sklearn.model_selection import StratifiedKFold\n\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef compute_score(cv, y_test):\n preds = pd.read_csv(os.path.join(CUR_DIR, 'cv{}-predictions.csv'.format(cv)), index_col=0)\n preds.columns = preds.columns.astype(int)\n final_cluster = preds.idxmax(axis=1)\n f1 = sklearn.metrics.f1_score(y_test, final_cluster, average='weighted')\n\n seurat_preds = pd.read_csv(os.path.join(\n CUR_DIR,\n 'cv{}-preds-seurat.csv'.format(cv)\n ), index_col=0)\n seurat_preds.pred = seurat_preds.pred.astype(int)\n seurat_f1 = sklearn.metrics.f1_score(y_test, seurat_preds.pred.loc[y_test.index], average='weighted')\n\n wrong_idx = y_test.index[final_cluster != y_test]\n for index in wrong_idx:\n main_cluster = preds.loc[index, :].idxmax()\n score = preds.loc[index, main_cluster]\n second_cell_type = preds.loc[index, :][preds.loc[index, :] < score].idxmax()\n final_cluster[index] = second_cell_type\n second_f1 = sklearn.metrics.f1_score(y_test, final_cluster, average='weighted')\n\n for index in wrong_idx:\n main_cluster = preds.loc[index, :].idxmax()\n random_cell_type = pd.Series(preds.columns[preds.columns != main_cluster]).sample(1)\n final_cluster[index] = random_cell_type\n random_f1 = sklearn.metrics.f1_score(y_test, final_cluster, average='weighted')\n return f1, seurat_f1, second_f1, random_f1\n\n\ndef main():\n _, y = utils.load_mca_lung()\n skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n splits = list(skf.split(np.zeros(len(y)), y))\n scores = []\n seurat_scores = []\n for i in range(1, 6):\n for tr_idx, test_idx in splits[i - 1:i]:\n y_test = y.iloc[test_idx]\n scores.append(compute_score(i, y_test))\n scores = pd.DataFrame(scores, columns=['f1', 'seurat_f1', 'second_f1', 'random_f1'])\n scores.to_csv(os.path.join(CUR_DIR, 'scores.csv'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5827956795692444, "alphanum_fraction": 0.5956989526748657, "avg_line_length": 28.0625, "blob_id": "c35bd63f4144aacb4e1e38f934acdb8314bdc14c", "content_id": "79e97b33f41bc90124c7091f3245c2e8adbcb207", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1395, "license_type": "no_license", "max_line_length": 108, "num_lines": 48, "path": "/08-unseen-sc02/train.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import catboost\nimport os\nimport timeit\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\ndef get_model(classes=None, iterations=30):\n if len(classes) == 1:\n loss_function = 'Logloss'\n else:\n loss_function = 'MultiClass'\n model = catboost.CatBoostClassifier(\n l2_leaf_reg=7,\n learning_rate=0.622,\n depth=10,\n iterations=iterations,\n random_seed=42,\n logging_level='Silent',\n loss_function=loss_function,\n eval_metric='F1',\n thread_count=10,\n )\n return model\n\n\ndef models(classes, iterations=30, label=None):\n model_dir = os.path.join(CUR_DIR, 'models', label)\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n result = []\n trained = False\n start = timeit.default_timer()\n for cls, X, y in classes:\n model = get_model(classes=cls, iterations=iterations)\n model_path = os.path.join(model_dir, 'cls-{}.cbm'.format('+'.join(map(lambda x: str(int(x)), cls))))\n if os.path.exists(model_path):\n model.load_model(model_path)\n else:\n trained = True\n model.fit(X, y)\n model.save_model(model_path)\n result.append((cls, model))\n if trained:\n train_time = timeit.default_timer() - start\n open(os.path.join(model_dir, 'train_time'), 'w').write(str(train_time))\n return result\n" }, { "alpha_fraction": 0.6597671508789062, "alphanum_fraction": 0.6662354469299316, "avg_line_length": 37.650001525878906, "blob_id": "4e3c530659f2bfed78c7a81bcb690ee531f2e929", "content_id": "2b8252d8143c4b3148bbc0adbaf56c8921142680", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 773, "license_type": "no_license", "max_line_length": 106, "num_lines": 20, "path": "/09-leave-cell-type-out/predict.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import pandas as pd\n\n\ndef base_predict(model, input_columns, experiment):\n missing_columns = input_columns[~ input_columns.isin(experiment.columns)]\n experiment = experiment.copy()\n experiment[list(missing_columns)] = pd.DataFrame([[0] * len(missing_columns)], index=experiment.index)\n return pd.DataFrame(model.predict_proba(experiment[input_columns]), index=experiment.index)\n\n\ndef predict(models, input_columns, X):\n result = pd.DataFrame(index=X.index)\n for i, (classes, model) in enumerate(models):\n predictions = base_predict(model, input_columns, X)\n if len(classes) == 1:\n result[classes[0]] = predictions.iloc[:,0]\n else:\n classes += [-i - 1]\n result[classes] = predictions\n return result\n" }, { "alpha_fraction": 0.5924468636512756, "alphanum_fraction": 0.610542893409729, "avg_line_length": 30.024391174316406, "blob_id": "74d72ccfff54fa7b42805ed30ebc6d980ecbd57f", "content_id": "e0b48720bb0cf53a961c73cc617f711fb8d26159", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1271, "license_type": "no_license", "max_line_length": 95, "num_lines": 41, "path": "/01-cluster-sc01-sc02/sc02_b_cells.R", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "require(ggplot2)\nrequire(gridExtra)\nrequire(grid)\n\n\nthisFile <- function() {\n cmdArgs <- commandArgs(trailingOnly = FALSE)\n needle <- \"--file=\"\n match <- grep(needle, cmdArgs)\n if (length(match) > 0) {\n # Rscript\n return(normalizePath(sub(needle, \"\", cmdArgs[match])))\n } else {\n # 'source'd via R console\n return(normalizePath(sys.frames()[[1]]$ofile))\n }\n}\n\nCURRENT_DIR <- dirname(thisFile())\n\nsce <- readRDS(file.path(CURRENT_DIR, 'SC02.rds'))\nvars <- c('nGene', 'nUMI', 'percent.mito')\nb.cells <- sce@ident %in% c(0, 2)\nb.cells.df <- data.frame([email protected][b.cells, vars], ident=sce@ident[b.cells])\n\nplots <- list()\nfor (var in vars) {\n plots[[var]] <- ggplot(b.cells.df, aes_string(var, fill=\"ident\")) +\n geom_histogram(alpha=0.5, aes(y=..density..), position='identity', bins=50) +\n xlab(var)\n}\n\nml <- arrangeGrob(grobs=plots, \n nrow=3, ncol=1, \n top=textGrob(\"Density of technical variables between two B-Cell clusters\", \n gp=gpar(fontsize=16)))\nggsave(file.path(CURRENT_DIR, \"SC02-b-cells-tech-vars.png\"), ml, width=6, height=6)\n\n\nde.genes <- FindMarkers(sce, 0, 2)\nwrite.csv(de.genes, file=file.path(CURRENT_DIR, \"SC02-b-cells-DE-genes.csv\"))" }, { "alpha_fraction": 0.586004376411438, "alphanum_fraction": 0.616042971611023, "avg_line_length": 33.051429748535156, "blob_id": "f5add60c223d8f983bb37afa11d7e939d8a6d584", "content_id": "c002d522acf11c25d1ab993076dfc393b57b043e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5959, "license_type": "no_license", "max_line_length": 115, "num_lines": 175, "path": "/08-unseen-sc02/analyse.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import sickle\n\nimport os\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn\n\nimport sankey\nimport utils\n\n\nCUR_DIR, ROOT = sickle.paths(__file__)\n\n\ndef load_predictions(path):\n clusters = pd.read_csv('{}/SC02v2_clusters.csv'.format(\n os.path.join(CUR_DIR, '..', '00-metadata'),\n ), index_col=0, header=None)\n clusters.index = clusters.index.str.replace('C', '').astype(int)\n\n preds = pd.read_csv(path, index_col=0)\n preds = preds.reindex(columns=sorted(preds.columns, key=lambda x: (float(x) < 0, float(x))))\n new_columns = list(clusters.iloc[:,0])\n unseen_number = len(preds.columns) - len(clusters)\n if unseen_number:\n unseen_columns = list(preds.columns)[-unseen_number:]\n unseen = preds.loc[:,unseen_columns].min(axis=1)\n preds.drop(columns=unseen_columns, inplace=True)\n preds['Novel cell type'] = unseen\n new_columns += ['Novel cell type']\n #new_columns += unseen_columns\n else:\n unseen = 1 - preds.max(axis=1)\n preds['Novel cell type'] = unseen\n new_columns += ['Novel cell type']\n preds.columns = new_columns\n sums = preds.sum(axis=1)\n return preds.div(sums, axis=0)\n\n\ndef heatmap(predictions, label=None, figsize=(20, 8), threshold=0):\n preds = predictions.copy()\n preds.columns = list(range(len(preds.columns)))\n preds['cluster'] = preds.idxmax(axis=1)\n preds['max_score'] = predictions.max(axis=1)\n preds.sort_values(['cluster', 'max_score'], ascending=[True, False], inplace=True)\n preds = predictions.reindex(preds.index)\n\n plt.figure(figsize=figsize)\n seaborn.set(font_scale=2.2)\n ax = seaborn.heatmap(\n preds.T,\n xticklabels=[],\n cmap=\"Blues\",\n cbar_kws={\n 'ticks': [0, 0.2, 0.4, 0.6, 0.8, 1]\n },\n rasterized=True\n )\n\n if label:\n ax.set_xlabel(label)\n else:\n ax.set_xlabel('')\n ax.set_ylabel('')\n ax.collections[0].set_clim(0, 1)\n\n ax.figure.axes[-1].tick_params(labelsize=10)\n ax.figure.axes[-1].set_ylabel('Prediction probability')\n\n ax.figure.tight_layout()\n ax.figure.subplots_adjust(right=1.04)\n seaborn.set(font_scale=1)\n return ax.figure\n\n\ndef get_second_maxes(predictions):\n second_choices = pd.DataFrame(index=predictions.columns, columns=predictions.columns)\n second_choices.fillna(0, inplace=True)\n for cell in predictions.index:\n cell_type = predictions.loc[cell, :].idxmax()\n score = predictions.loc[cell, cell_type]\n second_cell_type = predictions.loc[cell, :][predictions.loc[cell, :] < score].idxmax()\n second_choices.loc[cell_type, second_cell_type] += 1\n sums = second_choices.sum(axis=1)\n sums[sums == 0] = 1\n second_choices = second_choices.div(sums, axis='index')\n total = second_choices.sum(axis=0)\n second_choices = second_choices.reindex(columns=sorted(second_choices.columns, key=lambda x: -total[x]))\n return second_choices\n\n\ndef plot_second_maxes(maxes):\n plt.figure(figsize=(14,14))\n sums = maxes.sum(axis=0)\n ax = seaborn.clustermap(maxes,\n xticklabels=[maxes.columns[i] + ' ({:.2f})'.format(sums[i]) for i in range(len(sums))],\n col_cluster=False,\n )\n ax.ax_heatmap.set_ylabel('Main cell type')\n ax.ax_heatmap.set_xlabel('Second cell type')\n return ax\n\n\ndef calc_spe_sens(truth, preds, threshold=0):\n PLASMA = 7\n main_columns = list(set(preds.columns) - set(['Novel cell type']))\n predicted = preds.idxmax(axis=1)\n #predicted.loc[preds['Novel cell type'] > threshold] = 'Novel cell type'\n unseen_idx = set(predicted.index[predicted == 'Novel cell type'])\n plasma_idx = set(truth.index[truth == PLASMA])\n not_plasma_idx = set(truth.index[truth != PLASMA])\n sensitivity = len(plasma_idx & unseen_idx) / len(plasma_idx) * 100\n specificity = len(not_plasma_idx - unseen_idx) / len(not_plasma_idx) * 100\n precision = len(plasma_idx & unseen_idx) / len(unseen_idx) * 100\n return specificity, sensitivity, precision\n\n\ndef process(exp, reference, query, tag=None):\n exp_clusters = sickle.assignments(query)\n\n clusters = sickle.load_clusters(query)\n\n preds = load_predictions(os.path.join(CUR_DIR, '{}.csv'.format(exp)))\n\n hmap = heatmap(preds)\n hmap.savefig(os.path.join(CUR_DIR, '{}-heatmap.pdf'.format(exp)))\n\n hmap = heatmap(\n preds.loc[exp_clusters.index[exp_clusters == 7], :],\n label='$\\it{Plasma\\ cells}$ from SC03 dataset',\n figsize=(16, 8)\n )\n hmap.savefig(os.path.join(CUR_DIR, '{}-plasma-heatmap.pdf'.format(exp)))\n\n mapping = sickle.mapping(query, reference)\n s = sankey.sankey(\n clusters.iloc[:, 0].loc[exp_clusters],\n preds.idxmax(axis=1),\n alpha=.7,\n left_order=sickle.sankey_order(),\n mapping=mapping,\n tag=tag\n )\n s.savefig(os.path.join(CUR_DIR, '{}-sankey.pdf'.format(exp)))\n\n if mapping:\n open(os.path.join(CUR_DIR, '{}-f1.txt'.format(exp)), 'w').write(\n 'F1 score: {:.4f}'.format(\n mapping.f1(clusters.iloc[:, 0].loc[exp_clusters],\n preds.idxmax(axis=1))\n )\n )\n\n spe_sens = calc_spe_sens(exp_clusters, preds)\n open(os.path.join(CUR_DIR, '{}-spe-sens.txt'.format(exp)), 'w').write(\n 'Specificity: {:.1f}%\\tSensitivity: {:.1f}%\\tPrecision: {:.1f}%'.format(*spe_sens)\n )\n\n\ndef main():\n process('sc03-it30-oth1', 'SC02v2', 'SC03')\n process('sc03-it50-oth4', 'SC02v2', 'SC03', tag='B')\n #process('sc03-it50-oth4', threshold=0.134)\n process('sc03-it50-oth4-pro', 'SC02v2', 'SC03')\n process('sc03-it100-oth2', 'SC02v2', 'SC03')\n process('sc03-it200-cum2', 'SC02v2', 'SC03')\n process('sc03-it200-cum4', 'SC02v2', 'SC03')\n process('sc03-it200-int2', 'SC02v2', 'SC03')\n process('sc03-it200-int4', 'SC02v2', 'SC03')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6425926089286804, "alphanum_fraction": 0.6603174805641174, "avg_line_length": 34.32710266113281, "blob_id": "260f4d0bdfb8bfe85220b442b6dbd4b1b4861b37", "content_id": "860d4181018fd631caaefaa5f1cdf4410f28e04e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3780, "license_type": "no_license", "max_line_length": 115, "num_lines": 107, "path": "/07-catboost-sc02/best_model_analyse.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport sklearn\nimport catboost\nimport scipy.sparse\nimport matplotlib\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport seaborn\n\nimport os.path\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef load_predictions(path):\n clusters = pd.read_csv('{}/SC02_clusters.csv'.format(\n os.path.join(CUR_DIR, '..', '00-metadata'),\n ), index_col=0, header=None)\n clusters.index = clusters.index.str.replace('C', '').astype(int)\n clusters.iloc[:, 0] = clusters.iloc[:, 0] + ' ' + clusters.index.astype(str)\n preds = pd.read_csv(path, index_col=0)\n preds.columns = clusters.iloc[:, 0]\n return preds\n\n\ndef heatmap(predictions, figsize=(16, 20)):\n preds = predictions.copy()\n preds.columns = list(range(len(preds.columns)))\n preds['cluster'] = preds.idxmax(axis=1)\n preds['max_score'] = predictions.max(axis=1)\n preds.sort_values(['cluster', 'max_score'], ascending=[True, False], inplace=True)\n preds = predictions.reindex(preds.index)\n plt.figure(figsize=figsize)\n ax = seaborn.heatmap(preds, yticklabels=[])\n fig = ax.get_figure()\n fig.tight_layout()\n return fig\n\n\ndef get_second_maxes(predictions):\n second_choices = pd.DataFrame(index=predictions.columns, columns=predictions.columns)\n second_choices.fillna(0, inplace=True)\n for cell in predictions.index:\n cell_type = predictions.loc[cell, :].idxmax()\n score = predictions.loc[cell, cell_type]\n second_cell_type = predictions.loc[cell, :][predictions.loc[cell, :] < score].idxmax()\n second_choices.loc[cell_type, second_cell_type] += 1\n sums = second_choices.sum(axis=1)\n sums[sums == 0] = 1\n second_choices = second_choices.div(sums, axis='index')\n total = second_choices.sum(axis=0)\n second_choices = second_choices.reindex_axis(sorted(second_choices.columns, key=lambda x: -total[x]), axis=1)\n return second_choices\n\n\ndef plot_second_maxes(maxes):\n plt.figure(figsize=(14,14))\n sums = maxes.sum(axis=0)\n ax = seaborn.clustermap(maxes,\n xticklabels=[maxes.columns[i] + ' ({:.2f})'.format(sums[i]) for i in range(len(sums))],\n col_cluster=False,\n )\n ax.ax_heatmap.set_ylabel('Main cell type')\n ax.ax_heatmap.set_xlabel('Second cell type')\n return ax\n\n\ndef process(exp):\n sc03_clusters = pd.read_csv('{}/SC03_assgn.csv'.format(\n os.path.join(CUR_DIR, '..', '01-cluster-sc01-sc02'),\n ), index_col=0)\n sc03_clusters.columns = ['cluster']\n preds = load_predictions(os.path.join(CUR_DIR, '{}-preds.csv'.format(exp)))\n\n second_maxes = get_second_maxes(preds)\n maxes_heatmap = plot_second_maxes(second_maxes)\n maxes_heatmap.savefig(os.path.join(CUR_DIR, '{}-second-max-heatmap.png'.format(exp)))\n\n plasma_second_maxes = get_second_maxes(preds.loc[sc03_clusters.index[sc03_clusters.cluster == 7],:])\n maxes_heatmap = plot_second_maxes(plasma_second_maxes)\n plt.suptitle('Second max predictions for Plasma cells')\n maxes_heatmap.savefig(os.path.join(CUR_DIR, '{}-plasma-second-max-heatmap.png'.format(exp)))\n\n hmap = heatmap(preds)\n hmap.suptitle('Predictions for SC03 dataset')\n hmap.subplots_adjust(top=0.88)\n hmap.savefig(os.path.join(CUR_DIR, '{}-heatmap.png'.format(exp)))\n\n\n hmap = heatmap(preds.loc[sc03_clusters.index[sc03_clusters.cluster == 7],:], figsize=(16, 12))\n hmap.suptitle('Predictions for SC03 Plasma cells')\n hmap.subplots_adjust(top=0.88)\n hmap.savefig(os.path.join(CUR_DIR, '{}-plasma-heatmap.png'.format(exp)))\n\n\n\n\ndef main():\n process('sc03')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6026339530944824, "alphanum_fraction": 0.6049046516418457, "avg_line_length": 36.3220329284668, "blob_id": "f726ce4de9c5fabcac400b15689d6903c6471172", "content_id": "f2f38d56145127ec404d1217cc45006e752af143", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2202, "license_type": "no_license", "max_line_length": 76, "num_lines": 59, "path": "/09-leave-cell-type-out/split.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import math\n\nimport pandas as pd\n\n\ndef split(X, y, other_proportion=1, splits=None, split_order=None):\n result = []\n class_splits = split_y(y, splits=splits, split_order=split_order)\n for classes in class_splits:\n membership = y.isin(classes)\n cls_idx = y[membership].index\n inverse_idx = y[~membership].index\n X_cls = X.loc[cls_idx, :]\n X_other = X.loc[inverse_idx, :]\n y_cls = y.loc[cls_idx]\n y_other = y.loc[inverse_idx]\n\n y_cls = y_cls.replace({x: i for i, x in enumerate(classes)})\n\n to_take = len(y_cls) // len(y_other.unique()) * other_proportion\n other_sample = y_other.groupby(y_other).apply(\n lambda x: x.sample(to_take, replace=len(x) < to_take)\n )\n other_sample.index = other_sample.index.droplevel('cluster')\n other_idx = other_sample.index\n X_cls = pd.concat([X_cls, X_other.loc[other_idx, :]])\n y_cls = pd.concat([y_cls, pd.Series(len(classes), index=other_idx)])\n result.append((classes, X_cls, y_cls))\n return result\n\n\ndef split_y(y, other_proportion=1, splits=None, split_order=None):\n result = []\n unique_classes = sorted(y.unique())\n if splits is None:\n splits = len(unique_classes)\n if splits > len(unique_classes):\n raise ValueError('number of splits too large, max {}'.format(\n len(unique_classes)\n ))\n if split_order not in ('cumsum', 'interleaved'):\n raise ValueError('split_order should be cumsum or interleaved')\n max_classes_in_split = math.ceil(len(unique_classes) / splits)\n max_items_in_split = len(y) / splits\n\n current_split_classes = []\n current_sum = 0\n for cls, count in y.value_counts().sort_index().iteritems():\n current_split_classes.append(cls)\n current_sum += count\n if len(result) + 1 < splits \\\n and (current_sum >= max_items_in_split \\\n or len(current_split_classes) >= max_classes_in_split):\n result.append(current_split_classes)\n current_split_classes = []\n current_sum = 0\n if len(current_split_classes):\n result.append(current_split_classes)\n return result\n" }, { "alpha_fraction": 0.6832844614982605, "alphanum_fraction": 0.7360703945159912, "avg_line_length": 25.230770111083984, "blob_id": "5ae43fa9b0089fb587e7a8ac8abdbfc18272d9cd", "content_id": "aeb1afa0e430c43a8f7053ffab44fe62b476f211", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 341, "license_type": "no_license", "max_line_length": 116, "num_lines": 13, "path": "/04-evaluate-scmap/README.md", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "## Evaluation of scmap\n\n### Code\n\n`main.R`: code to run different setups of scmap for SC01 projection on itself. Code to run SC03 projection onto SC01\n\n`sc02.R`: code to project SC03 onto SC02 for Figure 10A\n\n`analyse.py`: analyse projection from `sc02.R`, quantify and plot Figure 10A\n\n### Cached files\n\n`*-preds.csv`: predictions of scmap\n" }, { "alpha_fraction": 0.6042701005935669, "alphanum_fraction": 0.6171797513961792, "avg_line_length": 32.01639175415039, "blob_id": "fb39cfc7bad6c816e499d125e38ef6837359f31c", "content_id": "cc83f3c1c1ef0522406b0a1a9389aa1ebde6ddaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2014, "license_type": "no_license", "max_line_length": 137, "num_lines": 61, "path": "/09-leave-cell-type-out/find_threshold.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\n\nimport numpy as np\nimport pandas as pd\nimport sklearn.metrics\n\nimport analyse\nimport predict\nimport split\nimport train\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef get_reference():\n global _reference\n if '_reference' not in globals():\n _reference = utils.load_10x(os.path.join(ROOT, 'SC02'), 'SC02v2')\n return _reference\n\n\ndef experiment(**kwargs):\n clusters = pd.read_csv('{}/SC02v2_clusters.csv'.format(\n os.path.join(CUR_DIR, '..', '00-metadata'),\n ), index_col=0, header=None)\n clusters.index = clusters.index.str.replace('C', '').astype(float)\n clusters.columns = ['label']\n\n X, y = get_reference()\n result = []\n for threshold in np.linspace(0.01, 1, 41):\n scores = []\n i = 1\n for cls in sorted(y.unique()):\n result_path = os.path.join(CUR_DIR, 'cv-{}.csv'.format(i))\n preds = analyse.load_predictions(result_path)\n predicted_cluster = pd.Series(index=preds.index)\n predicted_cluster[preds.index[preds.Unseen > threshold]] = 'Unseen'\n main_columns = list(set(preds.columns) - set(['Unseen']))\n predicted_cluster[preds.index[preds.Unseen <= threshold]] = preds.loc[preds.Unseen <= threshold, main_columns].idxmax(axis=1)\n\n true_cluster = y.copy()\n true_cluster = true_cluster[preds.index]\n true_cluster[true_cluster == cls] = 'Unseen'\n true_cluster = true_cluster.replace(\n {idx: val for idx, val in clusters.label.items()}\n )\n scores.append(sklearn.metrics.f1_score(true_cluster, predicted_cluster, average='weighted'))\n\n i += 1\n result.append(pd.DataFrame([[threshold, np.mean(scores)]]))\n result = pd.concat(result)\n result.columns = ['threshold', 'f1_score']\n result.to_csv(os.path.join(CUR_DIR, 'thresholds.csv'))\n\n\nif __name__ == '__main__':\n experiment(catboost_iters=50)\n" }, { "alpha_fraction": 0.6050214171409607, "alphanum_fraction": 0.6344152092933655, "avg_line_length": 27.15517234802246, "blob_id": "d8f6953c91151b6e0f65ff43a525b92466c0d01c", "content_id": "0fc6e9b4ef4f0c1d6b84868e4ce1b234fdecbc40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1633, "license_type": "no_license", "max_line_length": 106, "num_lines": 58, "path": "/07-catboost-sc02/best_model_predict.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import os\n\nimport pandas as pd\nimport catboost\n\nimport utils\n\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(os.path.dirname(CUR_DIR))\n\n\ndef path(*args):\n return os.path.join(ROOT, *args)\n\n\ndef predict(model, input_columns, experiment):\n missing_columns = input_columns[~ input_columns.isin(experiment.columns)]\n experiment = experiment.copy()\n experiment[list(missing_columns)] = pd.DataFrame([[0] * len(missing_columns)], index=experiment.index)\n return pd.DataFrame(model.predict_proba(experiment[input_columns]), index=experiment.index)\n\n\ndef main():\n X, y = utils.load_10x(path('SC02'), 'SC02')\n best_model = catboost.CatBoostClassifier(\n l2_leaf_reg=3,\n learning_rate=0.445,\n depth=10,\n iterations=200,\n random_seed=42,\n logging_level='Silent',\n loss_function='MultiClass',\n eval_metric='TotalF1',\n thread_count=20,\n )\n model_path = os.path.join(CUR_DIR, 'sc02-best-model.cbm')\n if os.path.exists(model_path):\n best_model.load_model(model_path)\n else:\n best_model.fit(\n X, y, [X.shape[1] - 1]\n )\n best_model.save_model(model_path)\n\n sc03, _ = utils.load_10x(path('SC03'), 'SC03')\n sc03_preds = predict(best_model, X.columns, sc03)\n sc03_preds.to_csv(os.path.join(CUR_DIR, 'sc03-preds.csv'))\n\n importances = pd.DataFrame(best_model._feature_importance, X.columns)\n importances[importances[0] > 0].sort_values(\n 0,\n ascending=False\n ).to_csv(os.path.join(CUR_DIR, 'sc02-model-features.csv'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5746410489082336, "alphanum_fraction": 0.5841549634933472, "avg_line_length": 28.798969268798828, "blob_id": "58d07938547766a0e79264c802e3071cb2ff53a7", "content_id": "daafc83aab6e93e984c7e72755822043753baa66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5781, "license_type": "no_license", "max_line_length": 91, "num_lines": 194, "path": "/lib/sickle.py", "repo_name": "mxposed/sickle", "src_encoding": "UTF-8", "text": "import display_settings\n\nimport collections\nimport os\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nimport scanpy.api as sc\nimport sklearn.exceptions\nimport sklearn.metrics\n\n\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nwarnings.filterwarnings(\"ignore\", category=sklearn.exceptions.UndefinedMetricWarning)\n\ndirs = {}\n\ndef paths(path):\n dirs['cur'] = os.path.dirname(os.path.abspath(path))\n dirs['code'] = os.path.dirname(dirs['cur'])\n dirs['root'] = os.path.dirname(dirs['code'])\n return dirs['cur'], dirs['root']\n\n\ndef sankey_order():\n return pd.read_csv(os.path.join(dirs['code'], 'sankey_order.csv')).order\n\n\ndef assignments(dataset):\n exp_clusters = pd.read_csv('{}/{}_assgn.csv'.format(\n os.path.join(dirs['code'], '01-cluster-sc01-sc02'),\n dataset\n ), index_col=0)\n return exp_clusters.iloc[:, 0]\n\n\nclass Mapping:\n def __init__(self, table):\n self.table = table\n self.src_mult = set()\n self.dst_mult = set()\n\n for name, count in collections.Counter(table['from']).items():\n if count > 1:\n self.src_mult.add(name)\n\n for name, count in collections.Counter(table['to']).items():\n if count > 1 and name != 'Novel cell type':\n self.dst_mult.add(name)\n\n self.src_replace = {}\n self.dst_replace = {}\n for idx in table.index:\n src = table.loc[idx, 'from']\n dst = table.loc[idx, 'to']\n if src in self.src_mult:\n if dst in self.dst_replace:\n self.src_replace[src] = self.dst_replace[dst]\n else:\n self.dst_replace[dst] = src\n else:\n self.src_replace[src] = dst\n\n def category(self, source, dest):\n rows_src = self.table[self.table['from'] == source]\n rows = rows_src[rows_src['to'] == dest]\n if len(rows) == 0:\n if len(rows_src) == 1 and rows_src['to'].iloc[0] == 'Novel cell type':\n return 'novel'\n return 'mistake'\n if dest in self.dst_mult:\n return 'decrease'\n if source in self.src_mult:\n return 'increase'\n if dest == 'Novel cell type':\n return 'novel'\n return 'correct'\n\n def f1(self, true, pred):\n true = true.replace(self.src_replace)\n pred = pred.replace(self.dst_replace)\n return sklearn.metrics.f1_score(true, pred, average='weighted')\n\n\ndef mapping(query, reference):\n mapping_file = os.path.join(\n dirs['code'],\n '00-metadata',\n '{}_to_{}.csv'.format(query, reference)\n )\n if os.path.exists(mapping_file):\n return Mapping(pd.read_csv(mapping_file, index_col=None))\n\n\ndef load_mca_assignments(annotation):\n if annotation == 'MCAv2':\n assgn = pd.read_csv(\n os.path.join(dirs['code'], '13-cluster-mca', 'MCAv2_assign.csv'),\n index_col=0\n )\n assgn.columns = ['cluster']\n return assgn.cluster.astype(int) - 1\n raise ValueError('Annotation not known')\n\n\ndef load_mca_raw():\n data = []\n for i in range(1, 4):\n batch = pd.read_csv(\n os.path.join(\n dirs['root'],\n 'rmbatch_dge',\n 'Lung{}_rm.batch_dge.txt'.format(i)\n ),\n header=0,\n sep=' ',\n quotechar='\"'\n )\n data.append(batch.transpose())\n return pd.concat(data)\n\n\ndef load_mca_lung(annotation):\n lung = load_mca_raw().join(load_mca_assignments(annotation))\n lung = lung[~lung.cluster.isna()]\n lung.fillna(0, inplace=True)\n\n X = lung[lung.columns[lung.columns != 'cluster']]\n return X, lung.cluster\n\n\ndef load_sc_scanpy(exp_name, batch_label):\n exp_dir = os.path.join(dirs['root'], exp_name)\n\n data = sc.read(os.path.join(exp_dir, 'matrix.mtx'), cache=True).T\n data.var_names = pd.read_table(\n os.path.join(exp_dir, 'genes.tsv'),\n header=None\n )[1]\n data.obs_names = pd.read_table(\n os.path.join(exp_dir, 'barcodes.tsv'),\n header=None\n )[0]\n data.obs_names = data.obs_names.str.replace('-1', '')\n data.var_names_make_unique()\n sc.pp.filter_cells(data, min_genes=200)\n sc.pp.filter_genes(data, min_cells=3)\n\n data.obs['n_UMI'] = np.sum(data.X, axis=1).A1\n\n mito_genes = data.var_names[data.var_names.str.match(r'^mt-')]\n data.obs['percent_mito'] = np.sum(data[:, mito_genes].X, axis=1).A1 / data.obs['n_UMI']\n\n ribo_genes = data.var_names[data.var_names.str.match(r'^(Rpl|Rps|Mrpl|Mrps)')]\n data.obs['percent_ribo'] = np.sum(data[:, ribo_genes].X, axis=1).A1 / data.obs['n_UMI']\n\n assgn = pd.read_csv(os.path.join(\n dirs['code'],\n '01-cluster-sc01-sc02',\n '{}_assgn.csv'.format(batch_label)\n ), index_col=0)\n assgn.columns = ['cluster']\n\n data.obs['cluster'] = assgn.cluster[data.obs.index]\n return data\n\n\ndef load_sc(batch_label):\n exp_name = batch_label[:4]\n data = load_sc_scanpy(exp_name, batch_label)\n exp = pd.DataFrame(data.X.todense(), index=data.obs_names, columns=data.var_names)\n exp['Batch'] = batch_label\n exp.fillna(0, inplace=True)\n\n exp['cluster'] = data.obs.cluster[exp.index]\n exp = exp[~exp.cluster.isna()]\n return exp[exp.columns[:-1]], exp.cluster\n\n\ndef load_clusters(reference):\n clusters = pd.read_csv(os.path.join(\n dirs['code'],\n '00-metadata',\n '{}_clusters.csv'.format(reference)\n ), index_col=0, header=None)\n clusters.index = clusters.index.str.replace('C', '').astype(int)\n return clusters\n\n\ndef load_predictions(path, reference):\n preds = pd.read_csv(path, index_col=0)\n preds.columns = load_clusters(reference).iloc[:, 0]\n return preds\n" } ]
55
danielma0826/BMI
https://github.com/danielma0826/BMI
80fc8f34544d37b5601eecf1a7880b4268000806
2a44115cf102da01868a533b68f0e116d1c46499
d39eadf6efb69c895146a3dd72b6da1a6761e918
refs/heads/main
2023-01-01T09:17:39.368716
2020-10-27T08:10:34
2020-10-27T08:10:34
307,627,487
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.61654132604599, "alphanum_fraction": 0.646616518497467, "avg_line_length": 25.399999618530273, "blob_id": "6b11fa1dd37dd341e1e3fe88f088e5d138f15ab1", "content_id": "9ce84e33565e0709fb2b62ef26d5bbbe7144d279", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/BMI.py", "repo_name": "danielma0826/BMI", "src_encoding": "UTF-8", "text": "\nheight=eval(input('請輸入身高(cm)='))\nweight=eval(input('請輸入體重(KG)='))\nbmi=weight/((height/100)**2)\nbmi = int(bmi)\nprint('此人的BMI=', bmi)\n" } ]
1
lakshits11/Coursera-Python3_Project_Course_5_My_Work
https://github.com/lakshits11/Coursera-Python3_Project_Course_5_My_Work
cc466dcfbe19401c5a5ec281daf512bbdae0625b
abb41a346d30d0b478bf3f7de73f07a9059c28bf
a7e6fada0e92d9bff7db0c01447ded4d57e026ad
refs/heads/master
2022-11-13T05:33:35.850401
2020-07-07T07:24:52
2020-07-07T07:24:52
277,744,188
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5504322648048401, "alphanum_fraction": 0.5585538148880005, "avg_line_length": 28.293651580810547, "blob_id": "fc2a233b9103f8d0d160afa8b2430e589d476b97", "content_id": "fc1b0d51b324869f38f4bd69fe3913d3c00c7e9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3817, "license_type": "no_license", "max_line_length": 92, "num_lines": 126, "path": "/LakshitSomani_Project_Work.py", "repo_name": "lakshits11/Coursera-Python3_Project_Course_5_My_Work", "src_encoding": "UTF-8", "text": "import zipfile\r\n\r\nfrom PIL import Image\r\nimport pytesseract\r\nimport cv2 as cv\r\nimport numpy as np\r\n\r\n# loading the face detection classifier\r\nface_cascade = cv.CascadeClassifier('readonly/haarcascade_frontalface_default.xml')\r\n\r\n# the rest is up to you!\r\n\r\n# define a function to get (name, image, text) from a zip file\r\ndef zip_images_extraction(name):\r\n \"\"\"\r\n get all the information (name, image, text) from a zip file\r\n\r\n :input: the name of a zip file\r\n :output: a list of dictoionaries. Each dictionary contains the all the information\r\n (name, image, text) of a image object.\r\n\r\n \"\"\"\r\n # zip name\r\n zip_name = 'readonly/' + name\r\n\r\n # output\r\n out = []\r\n\r\n # index out all the information\r\n with zipfile.ZipFile(zip_name) as myzip:\r\n zip_infos = myzip.infolist()\r\n\r\n for ele in zip_infos:\r\n # name\r\n name = ele.filename\r\n # image\r\n img = Image.open(myzip.open(name))\r\n # text\r\n img_strs = pytesseract.image_to_string(img.convert('L'))\r\n\r\n # test if \"Christopher\" or \"Mark\" are in the text\r\n if (\"Christopher\" in img_strs) or (\"Mark\" in img_strs):\r\n # example of dictionary\r\n my_dic = {\"name\":name, \"img\":img, \"text\":img_strs}\r\n out.append(my_dic)\r\n return out\r\n# extract all the information related to small_img.zip and images.zip\r\nsmall_imgs = zip_images_extraction(\"small_img.zip\")\r\n\r\n# big_imgs will be here latter\r\n#big_imgs = zip_images_extraction(\"images.zip\")\r\n# big_imgs will be here latter\r\nbig_imgs = zip_images_extraction(\"images.zip\")\r\n# define a function to extract a list of faces\r\n# create a contact sheet for these faces\r\ndef extract_faces(img, scale_factor):\r\n \"\"\"\r\n gray is in array form\r\n \"\"\"\r\n # extract the retangle of the faces\r\n gray = np.array(img.convert(\"L\"))\r\n faces = face_cascade.detectMultiScale(gray, scale_factor)\r\n\r\n # if no faces are detected\r\n if (len(faces) == 0):\r\n return None\r\n\r\n # extract faces into the list imgs\r\n faces_imgs = []\r\n\r\n for x,y,w,h in faces:\r\n faces_imgs.append(img.crop((x,y,x+w,y+h)))\r\n\r\n # compute nrows and ncols\r\n ncols = 5\r\n nrows = math.ceil(len(faces) / ncols)\r\n\r\n # contact sheet\r\n contact_sheet=Image.new(img.mode, (550, 110*nrows))\r\n x, y = (0, 0)\r\n\r\n for face in faces_imgs:\r\n face.thumbnail((110,110))\r\n contact_sheet.paste(face, (x,y))\r\n\r\n if x+110 == contact_sheet.width:\r\n x = 0\r\n y += 110\r\n else:\r\n x += 110\r\n\r\n return contact_sheet\r\n# define the search function\r\ndef value_search(value, zip_name, scale_factor):\r\n if zip_name == \"small_img.zip\":\r\n ref_imgs = small_imgs\r\n else:\r\n ref_imgs = big_imgs\r\n\r\n for ele in ref_imgs:\r\n # test if value is in the text\r\n if value in ele[\"text\"]:\r\n # print out the name of the figure\r\n print(\"Results found in file {}\".format(ele[\"name\"]))\r\n\r\n # index out the faces\r\n img = ele[\"img\"]\r\n contact_sheet = extract_faces(img, scale_factor)\r\n if contact_sheet is not None:\r\n display(contact_sheet)\r\n else:\r\n print(\"But there were no faces in that file\")\r\n\r\n###########################################################################################\r\n# NEW CELL\r\n# reproduce the search for \"Christopher\"\r\nvalue = \"Christopher\"\r\nzip_name = \"small_img.zip\"\r\nvalue_search(value, zip_name, scale_factor = 1.4)\r\n\r\n############################################################################################\r\n#NEW CELL\r\n# reproduce the search for \"Mark\"\r\nvalue = \"Mark\"\r\nzip_name = \"images.zip\"\r\nvalue_search(value, zip_name, scale_factor = 1.5)\r\n" }, { "alpha_fraction": 0.769784152507782, "alphanum_fraction": 0.798561155796051, "avg_line_length": 68.5, "blob_id": "d04248c8f3c0e9d9b7402b4560bb9da2e46aac32", "content_id": "d5a7ff7c0a596609fb740abb8a96419ca975816d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 139, "license_type": "no_license", "max_line_length": 94, "num_lines": 2, "path": "/README.md", "repo_name": "lakshits11/Coursera-Python3_Project_Course_5_My_Work", "src_encoding": "UTF-8", "text": "# Coursera-Python3_Project_Course_5_My_Work\nThis is Lakshit Somani's work done on Coursera Python 3 Course 5 Pillow-Tesseract-OpenCV Final Project\n" } ]
2
Anika215/Scroll-down-to-an-infinite-page
https://github.com/Anika215/Scroll-down-to-an-infinite-page
889ce8c8e8d580cf4d04091bb05d6138d09b11c0
34de59627395cb43f275cddda66f385431eea43f
8cb90a485828d49288da0857b0ba70136c7a5811
refs/heads/master
2021-07-21T02:35:09.120691
2017-10-30T08:07:26
2017-10-30T08:07:26
108,818,882
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6877551078796387, "alphanum_fraction": 0.6979591846466064, "avg_line_length": 24.37837791442871, "blob_id": "8f1da9163053f29664bde196a578d7fb2e3dff21", "content_id": "73a11ccc6c2eaeeeab610e3892522504fce26138", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 980, "license_type": "no_license", "max_line_length": 76, "num_lines": 37, "path": "/Scrolling.py", "repo_name": "Anika215/Scroll-down-to-an-infinite-page", "src_encoding": "UTF-8", "text": "from selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\nimport time\r\n\r\nusr = \"[email protected]\"\r\npwd = \"password\"\r\n\r\ndriver = webdriver.Chrome()\r\n\r\ndriver.set_window_size(1024, 600)\r\ndriver.maximize_window()\r\n\r\ndriver.get('http://linkedin.com')\r\ndata = driver.find_element_by_id('login-email')\r\ndata.send_keys(usr)\r\ndata = driver.find_element_by_id('login-password')\r\ndata.send_keys(pwd)\r\ndata.send_keys(Keys.RETURN)\r\n\r\nSCROLL_PAUSE_TIME = 3.5\r\n\r\n# Get scroll height\r\nlast_height = driver.execute_script(\"return document.body.scrollHeight\")\r\n\r\nwhile True:\r\n # Scroll down to bottom\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n\r\n # Wait to load page\r\n time.sleep(SCROLL_PAUSE_TIME)\r\n\r\n # Calculate new scroll height and compare with last scroll height\r\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\r\n if new_height == last_height:\r\n break\r\n last_height = new_height\r\n\r\n\r\n" }, { "alpha_fraction": 0.7989690899848938, "alphanum_fraction": 0.7989690899848938, "avg_line_length": 54.14285659790039, "blob_id": "68408db4d1889b0855daf71e102c726c7e669c0c", "content_id": "fbf5ae4b83f9e2c37ca57e6ede5a19bb6d596397", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 388, "license_type": "no_license", "max_line_length": 133, "num_lines": 7, "path": "/README.md", "repo_name": "Anika215/Scroll-down-to-an-infinite-page", "src_encoding": "UTF-8", "text": "# Scroll-down-to-an-infinite-page\nPython script using selenium to login to your linkedin account and scroll down\n\nThis uses selenium to automate web broowsers.I have used the Chrome web browser. To use it you need to download the chrome webdriver.\n\nChange the user id and password with your credentials to use the script. \nYou can also change the scroll pause time according your need. \n\n" } ]
2
MCANYOU/oschena
https://github.com/MCANYOU/oschena
a9dfac545fbab6a54f59533f165ebeeccdf975a9
ed4ea4213c1842a31fcfa28529fdf942d657f4d0
e4bc1b5e0ed158be42868dc4a445d45c0de28c8a
refs/heads/master
2020-03-13T18:28:35.028209
2015-02-02T11:47:13
2015-02-02T11:47:13
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6779661178588867, "alphanum_fraction": 0.7288135886192322, "avg_line_length": 22.600000381469727, "blob_id": "177f33084f72fefaa0760876d5c40bb946d8cbd3", "content_id": "e728ef35ece68f787af43dfee511d27ee4c658f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 118, "license_type": "no_license", "max_line_length": 70, "num_lines": 5, "path": "/getmovielensdata.sh", "repo_name": "MCANYOU/oschena", "src_encoding": "UTF-8", "text": "#!/bin/bash\nrm d.zip\nrm -r ml-100k\ncurl http://files.grouplens.org/datasets/movielens/ml-100k.zip > d.zip\nunzip d.zip\n" }, { "alpha_fraction": 0.559543251991272, "alphanum_fraction": 0.6174551248550415, "avg_line_length": 23.039215087890625, "blob_id": "3fb2f28b80d5eb7337c189c21fbb43a7196a1017", "content_id": "52c384c9ac7c40bcc7227a71ed9d8b633740bda8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1226, "license_type": "no_license", "max_line_length": 83, "num_lines": 51, "path": "/python/pearsonsimilarity.py", "repo_name": "MCANYOU/oschena", "src_encoding": "UTF-8", "text": "from math import sqrt\ndef mean(l):\n return float(sum(l))/len(l)\n\ndef shareditems(ratingspers1, ratingspers2):\n l = []\n for i in ratingspers1.keys():\n if i in ratingspers2.keys():\n l.append(i) \n return l\n\ndef pearsonsimilarity(r, p1, p2, amean, bmean, shareditems):\n l1 = [(r[p1][i] - amean) * (r[p2][i] - bmean) for i in shareditems]\n nominator = sum(l1)\n l2 = [(r[p1][i] - amean)**2 for i in shareditems]\n s1 = sum(l2)\n dominator = sqrt(s1) * sqrt(sum([(r[p2][i] - bmean)**2 for i in shareditems]))\n pearsonsimilarity = nominator / dominator \n return pearsonsimilarity\n\na = [5,3,4,4]\nb = [3,1,2,3,3]\nu2 = [4, 3, 4, 3]\nu3ratings = [1, 5, 5, 2]\n\namean = float(mean(a))\nbmean = float(mean(b))\nu2mean = float(mean(u2))\nu3mean = float(mean(u3ratings))\n\nshareditems = [0,1,2,3]\npers1 = {}\npers2 = {}\nfor i in shareditems:\n idx = i -1\n pers1[i] = a[idx]\n pers2[i] = b[idx]\n\nr = []\np1 = 0\np2 = 1\nu2id = 2\nu3id = 3\nr.append(a)\nr.append(b[:4])\nr.append(u2)\nr.append(u3ratings)\n\np = pearsonsimilarity(r, p1, p2, amean, bmean, shareditems)\npears1 = pearsonsimilarity(r, p1, u2id, amean, u2mean, shareditems)\npears2 = pearsonsimilarity(r, p1, u3id, amean, u3mean, shareditems)\n" }, { "alpha_fraction": 0.5588235259056091, "alphanum_fraction": 0.5882353186607361, "avg_line_length": 19.399999618530273, "blob_id": "e600a43b200c3e7f2dc742f65cc75be0a3c253d4", "content_id": "2524ce55b997c53f2a1855b43068e4fba6e1a659", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "no_license", "max_line_length": 34, "num_lines": 5, "path": "/python/tocsv.py", "repo_name": "MCANYOU/oschena", "src_encoding": "UTF-8", "text": "f = open('../ml-100k/u.data', 'r')\nlines = list(f)\n\ncsvrows = [ x for x in list(f)]\nprint 'converted'\n" }, { "alpha_fraction": 0.7580645084381104, "alphanum_fraction": 0.7903226017951965, "avg_line_length": 30, "blob_id": "64269921334c3d7d92cb520e21875637a62d7b2c", "content_id": "dc3aebde0c0f201904df11d7865635de45b7a4f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 310, "license_type": "no_license", "max_line_length": 84, "num_lines": 10, "path": "/python/computeSingleRecommendation.py", "repo_name": "MCANYOU/oschena", "src_encoding": "UTF-8", "text": "import oschena\n\ntrainingfilepath = '../ml-100k/u1.base'\ntestfilepath = '../ml-100k/u1.test'\nuserid = 1\nitemid = 6\ntrainingset = oschena.loaddata(trainingfilepath)\ntestset = oschena.loaddata(testfilepath)\nrecommendation = oschena.predict(userid, itemid, trainingset, oschena.averagerating)\nprint recommendation\n" }, { "alpha_fraction": 0.4906832277774811, "alphanum_fraction": 0.5155279636383057, "avg_line_length": 13.636363983154297, "blob_id": "6adb411d42088f4496c29b53c0faf8dbc18046d9", "content_id": "dbc739616e9b399d56994874936c4dc19df4dad7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "no_license", "max_line_length": 32, "num_lines": 11, "path": "/python/firstlines.py", "repo_name": "MCANYOU/oschena", "src_encoding": "UTF-8", "text": "s = ''\nf = open('ml-100k/u.data', 'r')\nfor _ in range(5):\n l = f.readline()\n s = s + l\n\n\nfw = open('fivelines.data', 'w')\nfw.write(s)\nf.close()\nfw.close()\n" }, { "alpha_fraction": 0.6140350699424744, "alphanum_fraction": 0.6320288181304932, "avg_line_length": 27.67096710205078, "blob_id": "c10e9ea6848d2101057a543d23ae2126acab9ebf", "content_id": "c40870a7efbb948c37d05822a6e806c6c91010aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4446, "license_type": "no_license", "max_line_length": 135, "num_lines": 155, "path": "/python/evaluation.py", "repo_name": "MCANYOU/oschena", "src_encoding": "UTF-8", "text": "def loaddata(filename):\n stringlines = list(open(filename, 'r'))\n splitlines = [e.split() for e in stringlines]\n return [[int(x) for x in e[:3]] for e in splitlines]\n\ndef averagerating(ratings, user, item):\n return float(sum([r[2] for r in ratings]))/len(ratings)\n\ndef predictions(ratings, useritemlist, predict = averagerating):\n return [[x[0], x[1], predict(ratings, x[0], x[1])] for x in useritemlist]\n \ndef useruser(ratings, user, item):\n useravgrating = useraveragerating(ratings, user)\n l = [sim_distance(ratings, user, u) * (rating(u, item) - useraveragerating(ratings, user)) for s, u in neighborhood(user, ratings)]\n numerator = sum(l)\n denumerator = sum([s for s, u in neighorhood(user, ratings)])\n return numerator / denumerator\n\ndef itemaverage(ratings, user, item):\n itemratings = [r[2] for r in ratings if r[1] == item]\n if len(itemratings) == 0:\n return averagerating(ratings, user, item)\n else:\n return sum(itemratings)/len(itemratings)\n\ndef shareditems(ratingspers1, ratingspers2):\n l = []\n for i in ratingspers1.keys():\n if i in ratingspers2.keys():\n l.append(i) \n return l\n\ndef pearsonsimilarity(r, p1, p2, amean, bmean, shareditems):\n l1 = [(r[p1][i] - amean) * (r[p2][i] - bmean) for i in shareditems]\n nominator = sum(l1)\n l2 = [(r[p1][i] - amean)**2 for i in shareditems]\n s1 = sum(l2)\n dominator = sqrt(s1) * sqrt(sum([(r[p2][i] - bmean)**2 for i in shareditems]))\n pearsonsimilarity = nominator / dominator \n return pearsonsimilarity\n\ndef users(ratings):\n s = []\n for r in ratings:\n if not r[0] in s:\n s.append(r[0])\n return s\n \ndef user_itemratingdict(ratings):\n rdict = {}\n users = users(ratings)\n for u in users:\n udict = {}\n rdict[u] = udict\n\n for r in ratings:\n rdict[r[0]][r[1]] = r[2]\n\ndef distance(a, b):\n return sum([(a[idx] - b[idx])**2 for idx in range(len(a))])\n\ndef userratings(items, userratingsdict):\n return [userratingsdict[i] for i in items]\n\ndef sim_distance(ratings, user1, user2):\n user_itemratingdict = user_itemratingdict(ratings)\n si = shareditems(user_itemratingdict[user1], user_itemratingdict[user2])\n ul1 = userratings(si, user_itemratingdict[user1])\n ul2 = userratings(si, user_itemratingdict[user2])\n return distance(ul1, ul2)\n\ndef sim(u1, u2, R):\n sl = shareditems(R[u1], R[u2])\n\ndef neighborhood(user, ratings, size = 5):\n users = users(ratings)\n l= []\n for u in users(ratings):\n if u != user:\n l.append(( sim_distance(ratings, user, u), u))\n \n l.sort()\n return l[:n]\n\ndef useraveragerating(ratings, user):\n ul = [r[2] for r in ratings if r[0] == user] \n return sum(ul) / len(ul)\n\ndef rating(ratings, user, item):\n for r in ratings:\n if r[0] == user and r[1] == item:\n return r[2]\n else:\n return None\n\ndef mae(predictions, ratings):\n errors = []\n for idx, e in enumerate(predictions):\n actualrating = ratings[idx]\n errors.append(actualrating[2] - e[2])\n\n abserrors = [abs(x) for x in errors]\n return float(sum(abserrors)) / len(abserrors)\n\nuseridcolumn = 0\nitemcolumn = 1\nratingcolumn = 2\ntrainingdata = loaddata('../ml-100k/u1.base')\ntestdata = loaddata('../ml-100k/u1.test')\nratings = [e[ratingcolumn] for e in trainingdata]\n\n\ninputdata = [e[:2] for e in testdata]\n\n#avgmae = mae(predictions, testdata)\n\nitemuserrating = {}\nfor r in trainingdata:\n if r[1] in itemuserrating:\n itemuserrating[r[1]].append(r[2])\n else:\n itemuserrating[r[1]] = [r[2]] \n\nuseritemrating = {}\nfor r in trainingdata:\n if r[0] in useritemrating:\n useritemrating[r[0]].append(r[2])\n else:\n useritemrating[r[0]] = [r[0]]\n\nitems = itemuserrating.keys().sort()\n\nrdict = {}\nfor u in users(trainingdata):\n udict = {}\n rdict[u] = udict\n\nfor r in trainingdata:\n rdict[r[0]][r[1]] = r[2]\n\nR = []\nfor i in range(len(users(trainingdata))):\n R.append(None)\n\nfor u in users(trainingdata):\n ui = []\n for i in itemuserrating.keys():\n ui.append(None)\n R.append(ui)\n\navgpredictions = predictions(trainingdata, inputdata)\navgmae = mae(avgpredictions, testdata)\nitemavgpredictions = predictions(trainingdata, inputdata, itemaverage )\n#itemavgmae = mae(itemavgpredictions, testdata)\n#useruserpredictions = useruserpredict(inputdata, trainingdata)\n\n\n" }, { "alpha_fraction": 0.49424999952316284, "alphanum_fraction": 0.5612499713897705, "avg_line_length": 28.850746154785156, "blob_id": "6887203931ed814fc7986dfafea5128cf55521de", "content_id": "9778dc87d5458a612d15bfbb78860248cfc846c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4000, "license_type": "no_license", "max_line_length": 585, "num_lines": 134, "path": "/python/oschena.py", "repo_name": "MCANYOU/oschena", "src_encoding": "UTF-8", "text": "import sys\ndef loaddata(filename):\n stringlines = list(open(filename, 'r'))\n splitlines = [e.split() for e in stringlines]\n return [[int(x) for x in e[:3]] for e in splitlines]\n\ndef averagerating(user, item, ratings):\n \"\"\"Returns the average of all ratings.\n >>> ratings = [[1,1,1], [1,1,9]]\n >>> averagerating(1,1,ratings)\n 5.0\n \"\"\"\n\n return float(sum([r[2] for r in ratings]))/len(ratings)\n\ndef predict(user, item, trainingset, recommender = averagerating):\n return recommender(user, item, trainingset)\n\ndef distance(a, b):\n \"\"\" Returns squared euclidean distance between u and v\n\n >>> u = [1,2,3]\n >>> v = [2,4,6]\n >>> distance(u,v)\n 14\n \"\"\"\n return sum([(a[idx] - b[idx])**2 for idx in range(len(a))])\n\ndef users(ratings):\n \"\"\"Returns set of user ids\n >>> ratings = [[1, 268, 5], [1, 269, 5], [1, 270, 5], [1, 271, 2], [2, 1, 4], [2, 10, 2], [2, 14, 4], [2, 25, 4], [2, 100, 5], [2, 111, 4], [2, 127, 5], [2, 237, 4], [2, 242, 5], [2, 255, 4], [2, 258, 3], [2, 269, 4], [2, 272, 5], [2, 273, 4], [2, 274, 3], [2, 275, 5], [2, 276, 4], [2, 277, 4], [2, 278, 3], [2, 282, 4], [2, 283, 5], [2, 306, 4], [2, 309, 1], [2, 310, 4], [2, 311, 5], [3, 181, 4], [3, 258, 2], [3, 260, 4], [3, 268, 3], [3, 271, 3], [3, 288, 2], [3, 302, 2], [3, 303, 3], [3, 317, 2], [3, 319, 2], [3, 320, 5], [3, 321, 5], [3, 322, 3], [3, 325, 1], [3, 326, 2]]\n >>> users(ratings)\n [1, 2, 3]\n\n \"\"\"\n \n s = []\n for r in ratings:\n if not r[0] in s:\n s.append(r[0])\n return s\n\ndef neighborhood(user, ratings, user_itemratingdict, size=5):\n ul = users(ratings)\n ul.remove(user)\n\n l = [(sim_distance(ratings, user, x, user_itemratingdict), x) for x in ul]\n\n l.sort()\n print l[:5]\n return l[:50]\n\ndef sim_distance(ratings, user1, user2, user_itemratingdict):\n si = shareditems(user_itemratingdict[user1], user_itemratingdict[user2])\n if len(si) < 5:\n return sys.maxint\n ul1 = userratings(si, user_itemratingdict[user1])\n ul2 = userratings(si, user_itemratingdict[user2])\n d = 1/float(sqrt(distance(ul1, ul2)))\n\n return d\n\ndef create_user_itemratingdict(ratings):\n rdict = {}\n ul = users(ratings)\n for u in ul:\n udict = {}\n rdict[u] = udict\n\n for r in ratings:\n rdict[r[0]][r[1]] = r[2]\n return rdict\n\ndef shareditems(ratingspers1, ratingspers2):\n l = []\n for i in ratingspers1.keys():\n if i in ratingspers2.keys():\n l.append(i) \n return l\n\ndef userratings(items, userratingsdict):\n return [userratingsdict[i] for i in items]\n\ndef useraveragerating(ratings, user):\n ul = [r[2] for r in ratings if r[0] == user] \n return sum(ul) / len(ul)\n \ndef useruser(ratings, user):\n user_itemratingdict = create_user_itemratingdict(ratings)\n useravgrating = useraveragerating(ratings, user)\n itemtotal = {}\n simsum = {}\n for s, u in neighborhood(user, ratings, user_itemratingdict):\n for i in user_itemratingdict[u].keys():\n itemtotal.setdefault(i,0)\n simsum.setdefault(i,0)\n itemtotal[i] += s * user_itemratingdict[u][i]\n simsum[i] += s\n\n rankings = []\n\n for i, total in itemtotal.items():\n s = simsum[i]\n p = total/s\n rankings.append((p,i))\n\n rankings.sort()\n rankings.reverse()\n return rankings\n\ndef useruserp(user, item, uird, ratings, neighborhood):\n avg = useraveragerating(ratings, user)\n hr = haverated(item, neighborhood, uird)\n l = []\n for s, u in hr:\n uavg = useraveragerating(ratings, u)\n p = s * (uird[u][item] - uavg)\n l.append(p)\n\n numerator = sum(l)\n dominator = sum([s for s, u in hr])\n return avg + float(numerator)/dominator\n \n \ndef haverated(item, neighborhood, uird):\n l = []\n for s, u in neighborhood:\n if item in uird[u]:\n l.append((s, u))\n return l\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n" }, { "alpha_fraction": 0.6494464874267578, "alphanum_fraction": 0.6678966879844666, "avg_line_length": 18.285715103149414, "blob_id": "39f2bee3e9a57f1281c7f71fbdcc6768b9baf53f", "content_id": "420e6edb60656dd01729b402c77f034a10ac6875", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 87, "num_lines": 14, "path": "/python/fetchdata.py", "repo_name": "MCANYOU/oschena", "src_encoding": "UTF-8", "text": "import urllib2\nimport zipfile\n\nresponse = urllib2.urlopen('http://files.grouplens.org/datasets/movielens/ml-100k.zip')\n\nwf = open('temp', 'wb')\nwf.write(response.read())\nwf.close()\n\nf = gzip.open('temp', 'rb')\n\nzf = zipfile.ZipFile('temp', 'r')\n\npf = open('u.data','r')\n\n" }, { "alpha_fraction": 0.5891703963279724, "alphanum_fraction": 0.6085444688796997, "avg_line_length": 21.120878219604492, "blob_id": "28449129aba40cd3898dcab00bfc49686b1d3999", "content_id": "0091ac8c5b789ce1b620ea8481cdfed36bf19e5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2013, "license_type": "no_license", "max_line_length": 63, "num_lines": 91, "path": "/python/transform.py", "repo_name": "MCANYOU/oschena", "src_encoding": "UTF-8", "text": "f = open('ml-100k/u.data', 'r')\nfirstline = f.readline()\nfirstlinel = firstline.split()\ncurrentuser = firstlinel[0]\n\nl = list(f)\n\nsplitline = []\nfor line in l:\n splitline.append(line.split())\n\nuserratings = []\nfor line in splitline:\n if(line[0] == currentuser):\n userratings.append(line[1])\n\nuseritemratingdict = {}\nfor r in splitline:\n if r[0] in useritemratingdict:\n useritemratingdict[r[0]].append((r[1], r[2]))\n else:\n useritemratingdict[r[0]] = [(r[1], r[2])]\n\nitemuserrating = {}\nfor r in splitline:\n if r[1] in itemuserrating:\n itemuserrating[r[1]].append((r[0], r[2]))\n else:\n itemuserrating[r[1]] = [(r[0], r[2])] \n\nmostrated = []\nfor k in itemuserrating:\n mostrated.append((len(itemuserrating[k]), k))\n\nl = sorted(mostrated)\nl.reverse()\npopularitems = []\nfor il in l:\n x, y = il\n popularitems.append(y)\n#mostrated = mostrated.sort()\n\nuseritemdict = {}\nfor r in splitline:\n if r[0] in useritemdict:\n useritemdict[r[0]].append(r[1])\n else:\n useritemdict[r[0]] = [r[1]]\n\ncusers = 0\nuserlist = []\nfor k in useritemdict:\n if set(popularitems[:10]).issubset(set(useritemdict[k])):\n userlist.append(k)\n\nitemlist = popularitems[:10]\nuseritemlist = []\nfor u in userlist:\n ratings = []\n for ir in useritemratingdict[u]:\n i, r = ir\n if i in itemlist:\n ratings.append(r)\n useritemlist.append(ratings)\n\nlenlist = []\nfor r in useritemlist:\n lenlist.append(len(r))\n\ncommonratings = {}\nfor line in splitline:\n if line[1] in userratings:\n if line[0] in commonratings:\n commonratings[line[0]] = commonratings[line[0]] + 1\n else:\n commonratings[line[0]] = 1\n\nm = max(commonratings.values())\n\nidenticalratings = []\nfor k in commonratings.keys():\n if(commonratings[k] == 19):\n identicalratings.append(k)\n\nfw = open('fullmatrix.data', 'w')\nfor r in useritemlist:\n s = ' '.join(r) + '\\n'\n fw.write(s)\n\nfw.close() \nf.close()\n" } ]
9
o-ran-sc/smo-app
https://github.com/o-ran-sc/smo-app
abd40cb766208466ada7eac1199ce571c77947a6
ae2c74c28d401b69b8c2aaf2aa3df98088b6f43a
71686c0fd361dd65bf26e069ee2b08fd99bc914c
refs/heads/master
2023-04-05T07:20:26.344007
2020-11-30T21:06:28
2020-12-02T19:26:47
302,153,599
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6365724802017212, "alphanum_fraction": 0.6407075524330139, "avg_line_length": 34.09677505493164, "blob_id": "2e69c12c51bc80f347c00a605e2ecb1563cee6ae", "content_id": "f7c8109abb4fd90ce7a18448f66fc0e9003bc86c", "detected_licenses": [ "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4353, "license_type": "permissive", "max_line_length": 89, "num_lines": 124, "path": "/tools/oran-pkg-validation/csar.py", "repo_name": "o-ran-sc/smo-app", "src_encoding": "UTF-8", "text": "# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\nimport os\nimport tempfile\nimport zipfile\n\nimport requests\nfrom ruamel import yaml\n\nimport toscameta\nimport utils\n\nLOG = logging.getLogger(__name__)\n\nclass _CSARReader(object):\n\n def __init__(self, source, destination, no_verify_cert=True):\n if os.path.isdir(destination) and os.listdir(destination):\n raise ValueError('{0} already exists and is not empty. '\n 'Please specify the location where the CSAR '\n 'should be extracted.'.format(destination))\n downloaded_csar = '://' in source\n if downloaded_csar:\n file_descriptor, download_target = tempfile.mkstemp()\n os.close(file_descriptor)\n self._download(source, download_target)\n source = download_target\n self.source = os.path.expanduser(source)\n self.destination = os.path.expanduser(destination)\n self.metadata = None\n self.manifest = None\n try:\n if not os.path.exists(self.source):\n raise ValueError('{0} does not exists. Please specify a valid CSAR path.'\n .format(self.source))\n if not zipfile.is_zipfile(self.source):\n raise ValueError('{0} is not a valid CSAR.'.format(self.source))\n self._extract()\n self._read_metadata()\n finally:\n if downloaded_csar:\n os.remove(self.source)\n\n @property\n def created_by(self):\n return self.metadata.created_by\n\n @property\n def csar_version(self):\n return self.metadata.csar_version\n\n @property\n def meta_file_version(self):\n return self.metadata.meta_file_version\n\n @property\n def entry_definitions(self):\n return self.metadata.entry_definitions\n\n @property\n def entry_definitions_yaml(self):\n with open(os.path.join(self.destination, self.entry_definitions)) as f:\n return yaml.safe_load(f)\n\n @property\n def entry_manifest_file(self):\n return self.metadata.entry_manifest_file\n\n @property\n def entry_history_file(self):\n return self.metadata.entry_history_file\n\n @property\n def entry_tests_dir(self):\n return self.metadata.entry_tests_dir\n\n @property\n def entry_licenses_dir(self):\n return self.metadata.entry_licenses_dir\n\n @property\n def entry_certificate_file(self):\n return self.metadata.entry_certificate_file\n\n def _extract(self):\n LOG.debug('Extracting CSAR contents')\n if not os.path.exists(self.destination):\n os.mkdir(self.destination)\n with zipfile.ZipFile(self.source) as f:\n f.extractall(self.destination)\n LOG.debug('CSAR contents successfully extracted')\n\n def _read_metadata(self):\n self.metadata = toscameta.create_from_file(self.destination)\n\n def _download(self, url, target):\n response = requests.get(url, stream=True)\n if response.status_code != 200:\n raise ValueError('Server at {0} returned a {1} status code'\n .format(url, response.status_code))\n LOG.info('Downloading {0} to {1}'.format(url, target))\n with open(target, 'wb') as f:\n for chunk in response.iter_content(chunk_size=8192):\n if chunk:\n f.write(chunk)\n\n\ndef read(source, destination, no_verify_cert=False):\n return _CSARReader(source=source,\n destination=destination,\n no_verify_cert=no_verify_cert)\n\n" }, { "alpha_fraction": 0.6154741048812866, "alphanum_fraction": 0.6166375875473022, "avg_line_length": 25.41538429260254, "blob_id": "b5310093899cbeaeaf38f0bf34397095658dd841", "content_id": "7964916909ebb4febb63b62d5db27e40eb7ff7bc", "detected_licenses": [ "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1719, "license_type": "permissive", "max_line_length": 82, "num_lines": 65, "path": "/tools/oran-pkg-validation/main.py", "repo_name": "o-ran-sc/smo-app", "src_encoding": "UTF-8", "text": "\nimport sys\nimport logging\nimport argparse\nimport shutil\nimport tempfile\n\nimport pkg_resources\n\nimport csar\n\nLOG = logging.getLogger(__name__)\n\ndef csar_validate_func(namespace):\n try:\n csar.read(namespace.source,\n namespace.destination,\n namespace.no_verify_cert)\n finally:\n LOG.debug('Calling rmtree: {}'.format(namespace.destination))\n shutil.rmtree(namespace.destination, ignore_errors=True)\n\ndef parse_args(args_list):\n \"\"\"\n Entry point\n \"\"\"\n parser = argparse.ArgumentParser(description='CSAR Validation tool')\n parser.add_argument('-v', '--verbose',\n dest='verbosity',\n action='count',\n default=0,\n help='Set verbosity level (can be passed multiple times)')\n\n subparsers = parser.add_subparsers(help='csar-validate')\n\n csar_open = subparsers.add_parser('csar-validate')\n csar_open.set_defaults(func=csar_validate_func)\n csar_open.add_argument(\n 'source',\n help='CSAR file location')\n csar_open.add_argument(\n '-d', '--destination',\n help='Output directory to extract the CSAR into',\n required=True)\n csar_open.add_argument(\n '--no-verify-cert',\n action='store_true',\n help=\"Do NOT verify the signer's certificate\")\n\n return parser.parse_args(args_list)\n\n\ndef init_logging():\n# verbosity = [logging.WARNING, logging.INFO, logging.DEBUG]\n#\n logging.basicConfig(level=logging.INFO)\n\ndef main():\n args = parse_args(sys.argv[1:])\n# logging.basicConfig(level=logging.DEBUG)\n init_logging()\n return args.func(args)\n\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.6509009003639221, "alphanum_fraction": 0.6659159064292908, "avg_line_length": 34.97297286987305, "blob_id": "4f8f4b7596f1b14ca909f79968ac05edc6ccf80f", "content_id": "e453b3d78ff110a865b0d981e8c2ed12335600cf", "detected_licenses": [ "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1333, "license_type": "permissive", "max_line_length": 103, "num_lines": 37, "path": "/tools/oran-pkg-validation/unit-test/Tosca-error.sh", "repo_name": "o-ran-sc/smo-app", "src_encoding": "UTF-8", "text": "#===================================================================\n#Copyright © 2020 Aarna Networks, Inc.\n#All rights reserved.\n#===================================================================\n#Licensed under the Apache License, Version 2.0 (the \"License\");\n#you may not use this file except in compliance with the License.\n#You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\n#!/bin/sh\n\necho \necho \"Validating TOSCA Version(Tosca-ver-vnf-vsn.csar) Unit test case 1\"\npython3 ../main.py csar-validate -d /tmp/vh2/ --no-verify-cert ../CSAR-dest/Tosca-ver-vnf-vsn.csar\nif [ $? -eq 0 ]\nthen\n\techo \"TOSCA Unit test case 1 Passed\"\nelse\n\techo \"TOSCA Unit test case 1 Failed\"\nfi\necho\necho \"Validating TOSCA CSAR Version(Tosca-csar-ver-vnf-vsn.csar) Unit test case 2\"\necho\npython3 ../main.py csar-validate -d /tmp/vh2/ --no-verify-cert ../CSAR-dest/Tosca-csar-ver-vnf-vsn.csar\nif [ $? -eq 0 ]\nthen\n\techo \"TOSCA Unit test case 2 Passed\"\nelse\n\techo \"TOSCA Unit test case 2 Failed\"\nfi\n\n" }, { "alpha_fraction": 0.8088235259056091, "alphanum_fraction": 0.8529411554336548, "avg_line_length": 21.66666603088379, "blob_id": "1542338345efa823b06a4479b98cf019b1827ead", "content_id": "103f92584e3501aa8bfc4c8aee7f8478f899a45c", "detected_licenses": [ "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 68, "license_type": "permissive", "max_line_length": 24, "num_lines": 3, "path": "/tools/oran-pkg-validation/requirements.txt", "repo_name": "o-ran-sc/smo-app", "src_encoding": "UTF-8", "text": "install python3-pip\npip3 install ruamel.yaml\npip3 install udatetime\n" } ]
4
abhishek-verma/Dino-Run
https://github.com/abhishek-verma/Dino-Run
12d8bbf5f179c6f580d8c4a22f4dc5de57447cc0
1ce28f72066880ff08b6065b09b6a96b623caf5a
0a4748969fdce2ac5040798cba49389575498d38
refs/heads/master
2023-07-21T01:26:32.820361
2019-10-14T06:27:21
2019-10-14T06:27:21
214,892,935
0
0
MIT
2019-10-13T20:58:59
2019-10-14T06:27:23
2022-06-21T23:07:31
Python
[ { "alpha_fraction": 0.4635227620601654, "alphanum_fraction": 0.4719870984554291, "avg_line_length": 26.488889694213867, "blob_id": "50d548ff852db99ca8c76802c52f2e4bbbf7861a", "content_id": "f153c6162e3226bf1bddc36696f0b4181c686cc3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2481, "license_type": "permissive", "max_line_length": 72, "num_lines": 90, "path": "/ai/agent.py", "repo_name": "abhishek-verma/Dino-Run", "src_encoding": "UTF-8", "text": "from .model import Model\nfrom pprint import pprint\nimport random\n\nmodel = Model()\n\nclass Agent:\n\n def __init__(self, dinoJumpAction = None, restartGameAction = None):\n self.dinoJumpAction = dinoJumpAction\n self.restartGameAction = restartGameAction\n self.counter = 5\n self.data = []\n self.lastAction = 0\n\n def updateState(self, cod, coa, speed, isJumping):\n if isJumping :\n return\n\n self.counter = self.counter - 1\n if self.counter <=0 :\n self.counter = 8388608 / pow(speed, 10)\n\n if(self.lastAction == 0) :\n self.reward()\n\n self.lastCod = cod\n self.lastCoa = coa\n self.lastSpeed = speed\n print(\"cod: \", cod, \", coa: \", coa, \", speed: \", speed)\n action = model.predict(cod, coa, speed)\n self.lastAction = action\n if action == 1 and not self.dinoJumpAction == None :\n self.dinoJumpAction()\n\n def reward(self):\n try :\n self.data.append({\n 'cod': self.lastCod,\n 'coa': self.lastCoa,\n 'speed': self.lastSpeed,\n 'action': self.lastAction\n })\n except:\n print(\"\")\n\n def died(self, isJumping, isFalling):\n print(pprint(vars(self)))\n\n if self.lastAction == 0:\n self.data.append({\n 'cod': self.lastCod,\n 'coa': self.lastCoa,\n 'speed': self.lastSpeed,\n 'action': 1\n })\n\n elif isJumping and isFalling:\n self.data.append({\n 'cod': self.lastCod,\n 'coa': self.lastCoa,\n 'speed': self.lastSpeed,\n 'action': 0\n })\n \n elif isJumping and not isFalling:\n self.data.append({\n 'cod': self.lastCod - self.lastSpeed,\n 'coa': self.lastCoa,\n 'speed': self.lastSpeed,\n 'action': 1\n })\n\n else :\n self.data.append({\n 'cod': self.lastCod,\n 'coa': self.lastCoa,\n 'speed': self.lastSpeed,\n 'action': 0\n })\n \n \n\n print(\"trained on data\\n\", self.data)\n model.train(self.data)\n \n self.counter = 8\n\n if not self.restartGameAction == None:\n self.restartGameAction()\n\n \n\n" }, { "alpha_fraction": 0.7643097639083862, "alphanum_fraction": 0.7643097639083862, "avg_line_length": 32, "blob_id": "a54565482d8899be0befb8da8e3b0ea8360d511c", "content_id": "dc45630a2495746f731c6b54afdfd9ff34ba1c97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 297, "license_type": "permissive", "max_line_length": 123, "num_lines": 9, "path": "/README.md", "repo_name": "abhishek-verma/Dino-Run", "src_encoding": "UTF-8", "text": "# Dino Run\n\n![](https://github.com/shivamshekhar/Chrome-T-Rex-Rush/raw/master/screenshot.gif)\n\n### Description:\nAn AI that can learn play the famous Chrome T-Rex \n\n### Refs\nPython implementation of actual game taken and modified for this project https://github.com/shivamshekhar/Chrome-T-Rex-Rush\n" }, { "alpha_fraction": 0.5099901556968689, "alphanum_fraction": 0.5181788206100464, "avg_line_length": 28, "blob_id": "66cb5f511f4ecccc897a4077e530c2381e08c2b9", "content_id": "d61d0e476e521fe9ee04065e5a5cb52797182b58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3053, "license_type": "permissive", "max_line_length": 81, "num_lines": 105, "path": "/ai/model.py", "repo_name": "abhishek-verma/Dino-Run", "src_encoding": "UTF-8", "text": "from sklearn.naive_bayes import GaussianNB\nfrom sklearn import svm\nfrom sklearn.neighbors import KNeighborsClassifier\n\nfrom .naive_bayes import NaiveBayes\n\n\nimport pandas as pd\nimport numpy as np\nfrom scipy.stats import mode\n\nfrom matplotlib import pyplot\nfrom mpl_toolkits.mplot3d import Axes3D\nimport random\n\nnp.seterr(divide='ignore', invalid='ignore')\n\nclassifier = 'our'\nuse_all = True\n\nclass Model:\n\n def __init__(self):\n #Create a Gaussian Classifier\n self.our = NaiveBayes()\n self.gnb = GaussianNB()\n self.knc = KNeighborsClassifier(n_neighbors=3)\n # self.clf = svm.SVC(gamma='scale') # NOT WORKING\n print(\"model initiallized\")\n \n self.gen = 0\n\n def train(self, data):\n df = pd.DataFrame(data)\n\n self.gen = self.gen + 1\n print(\"gen: \", self.gen)\n if(self.gen % 5 == 0):\n self.plot(df)\n\n if(classifier == 'our' or use_all) :\n self.our.fit(df[['cod', 'coa', 'speed']].values, df['action'])\n # if(classifier == 'clf') :\n # self.clf.fit(df[['cod', 'coa', 'speed']], df['action'])\n if(classifier == 'gnb' or use_all) :\n self.gnb.fit(df[['cod', 'coa', 'speed']], df['action'])\n if(classifier == 'knc' or use_all) :\n self.knc.fit(df[['cod', 'coa', 'speed']], df['action'])\n\n print(\"trained for data: \\n\", df[['cod', 'coa', 'speed', 'action']])\n\n def predict(self, cod, coa, speed):\n\n # print('predicting action... ')\n\n try :\n predicted_action = []\n if(classifier == 'our' or use_all) :\n predicted_action.append(self.our.predict([[cod, coa, speed]])[0])\n # if(classifier == 'clf') :\n # predicted_action = self.clf.predict([[cod, coa, speed]])\n if(classifier == 'gnb' or use_all) :\n predicted_action.append(self.gnb.predict([[cod, coa, speed]])[0])\n if(classifier == 'knc' or use_all) :\n predicted_action.append(self.knc.predict([[cod, coa, speed]])[0])\n print('predicted action: ', predicted_action)\n\n action = []\n action.append(0)\n action.append(1)\n\n for a in predicted_action:\n # action[a] = action[a] + 1\n if(a == 1):\n return 1\n\n return 0\n\n # if action[0] > action[1] :\n # return 0\n # else: \n # return 1\n\n except Exception as e: \n # print(e)\n return 0 \n\n def plot(self, df): \n fig = pyplot.figure()\n ax = Axes3D(fig)\n\n cod = df['cod']\n coa = df['coa']\n speed = df['speed']\n action = df['action']\n color= ['red' if a == 0 else 'green' for a in action]\n # plt.scatter(arr1, arr2, color=color)\n # plt.show()\n ax.scatter(cod, speed, coa, color=color)\n\n ax.set_xlabel('COD')\n ax.set_ylabel('SPEED')\n ax.set_zlabel('COA')\n\n pyplot.show()\n " }, { "alpha_fraction": 0.5442504286766052, "alphanum_fraction": 0.5544852614402771, "avg_line_length": 30.961538314819336, "blob_id": "a3f1a44534c7df366fec47fb8748764a6ed82de3", "content_id": "626d22b61e3ce5fca2e8533bb4e78aa98a3d9f7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1661, "license_type": "permissive", "max_line_length": 101, "num_lines": 52, "path": "/ai/naive_bayes.py", "repo_name": "abhishek-verma/Dino-Run", "src_encoding": "UTF-8", "text": "import numpy as np\nimport math\n\nshouldNormalize = True\n\ndef normalize(X, axis=-1, order=2):\n if not shouldNormalize :\n return X\n\n l2 = np.atleast_1d(np.linalg.norm(X, order, axis))\n l2[l2 == 0] = 1\n return X / np.expand_dims(l2, axis)\n\nclass NaiveBayes():\n def fit(self, X, y):\n X = normalize(X)\n # print(X)\n self.X, self.y = X, y\n self.classes = np.unique(y)\n self.parameters = []\n for i, c in enumerate(self.classes):\n X_where_c = X[np.where(y == c)]\n self.parameters.append([])\n for col in X_where_c.T:\n parameters = {\"mean\": col.mean(), \"var\": col.var()}\n self.parameters[i].append(parameters)\n\n def _calculate_likelihood(self, mean, var, x):\n eps = 1e-4\n coeff = 1.0 / math.sqrt(2.0 * math.pi * var + eps)\n exponent = math.exp(-(math.pow(x - mean, 2) / (2 * var + eps)))\n return coeff * exponent\n\n def _calculate_prior(self, c):\n frequency = np.mean(self.y == c)\n return frequency\n\n def _classify(self, sample):\n posteriors = []\n for i, c in enumerate(self.classes):\n posterior = self._calculate_prior(c)\n for feature_value, params in zip(sample, self.parameters[i]):\n likelihood = self._calculate_likelihood(params[\"mean\"], params[\"var\"], feature_value)\n posterior *= likelihood\n posteriors.append(posterior)\n \n return self.classes[np.argmax(posteriors)]\n\n def predict(self, X):\n X = normalize(X)\n y_pred = [self._classify(sample) for sample in X]\n return y_pred" } ]
4
ancastoica/IAR-robot-cleaner-1
https://github.com/ancastoica/IAR-robot-cleaner-1
e74540fb61c614dde6a2fa0058bb9e3331c9385e
8701269080e0e8c3d591bb2467991ae137c7767c
d5387d0bf309c35afc3159f2f8fb66e5627dfdc9
refs/heads/master
2021-07-13T18:50:10.011228
2017-10-16T12:02:14
2017-10-16T12:02:14
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6586978435516357, "alphanum_fraction": 0.6734486222267151, "avg_line_length": 33.49122619628906, "blob_id": "33508538a7ccc6c281821994259f4d91eb74726e", "content_id": "a9120c3e74078aa6b894f13d0ba8554129ae7f92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1968, "license_type": "no_license", "max_line_length": 197, "num_lines": 57, "path": "/README.md", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "Artificial Intelligence Project - Homework 1\n\nTo execute the project :\n\nExecution :\n In the main, you'll be asked to choose one of the 3 algorithms, or all three.\n >>> \"Choose the algorithm to execute (DP; MC; QL; all) : \"\n To get an idea of the computing time :\n - DP : ~ 5h\n - MC : ~ 3 min\n - QL : ~ 3 min\n In order to facilitate the execution, we ran the DP algorithm many times, averaged the results, and when choosing \"all\" algorithm,\n the plot of the DP will be the plot of this value, and not a complete recomputation of the performance.\n\n\n\nProject Structure :\n main.py: Run the algorithms\n emulator.py: The simulator which simulates the environment given a state and an action, which returns a reward, a probability and a next possible state (MC, TD) / a list of possible states (DP)\n robot.py: The actual robot with its position, battery and orientation\n cell.py: The cell with its dirtiness states\n state.py: The state with the map, the robot parameters and the home base position\n policy.py: The policy which can be improved (tuples of states and optimal actions)\n api.py: The api of the project\n dynamic_programming.py: The dynamic programming algorithm\n monte-carlo.py: The monte-carlo algorithm\n qLearning.py: The Q learning algorithm\n\n\nInitial state\n Home base :\n Position x = 0\n Position y = 0\n Robot :\n Position x = 0\n Position y = 0\n Battery = 100\n Orientation = 1\n\n\nStates\n The state is composed of multiple parametres:\n Robot position { x [0, length of map], y [0, height of map] }\n Robot orientation { 0 (N), 1 (E), 2 (S), 3 (O) }\n Robot battery { sufficient, critical (10%), empty}\n Status of each cell { 0 (clean), 1 (dirty) }\n Homebase position { x [0, length of map], y [0, height of map] }\n\nRobot actions\n {\n Vacuum\n Go forward vacuuming\n Go forward no vacuum\n Rotation +90°\n Rotation -90°\n Recharge\n }\n" }, { "alpha_fraction": 0.5414323210716248, "alphanum_fraction": 0.5508061647415161, "avg_line_length": 30.75, "blob_id": "6eac614a63813f0e5df38dba925deb763c76500e", "content_id": "24651f392fb19eb6530a6ad99322b37c8d89f9ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2667, "license_type": "no_license", "max_line_length": 86, "num_lines": 84, "path": "/policy.py", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "class Policy:\n def __init__(self):\n self.matrix = []\n\n \"\"\"\n Get the states and actions from the policy\n \"\"\"\n def get_state_action(self, index):\n if index < len(self.matrix):\n return self.matrix[index][0], self.matrix[index][1], self.matrix[index][2]\n else:\n print(\"Out of bounds when looking for a particular policy\")\n return\n\n \"\"\"\n insert a unique action in the policy\n \"\"\"\n def insert_action(self, index, action, value):\n if index < len(self.matrix):\n policytuple = self.matrix[index]\n policytuple[1] = action\n policytuple[2] = value\n self.matrix[index] = policytuple\n else:\n print(\"Out of bounds when inserting an action in policy\")\n return\n\n \"\"\"\n insert a unique state in the policy \n \"\"\"\n def insert_state(self, index, state, value):\n if index < len(self.matrix):\n policytuple = self.matrix[index]\n policytuple[0] = state\n policytuple[2] = value\n self.matrix[index] = policytuple\n else:\n print(\"Out of bounds when inserting a state in policy\")\n return\n\n \"\"\"\n insert both a state and a action at a same index in the policy\n \"\"\"\n def insert_state_action(self, index, state, action, value):\n if index < len(self.matrix):\n policytuple = self.matrix[index]\n policytuple[0] = state\n policytuple[1] = action\n policytuple[2] = value\n self.matrix[index] = policytuple\n else:\n print(\"Out of bounds when inserting a state and action in policy\")\n return\n\n \"\"\"\n initialize the policy as an array of 3 dimensionnal arrays filled with 0\n \"\"\"\n def init_policy(self, length):\n self.matrix = [[0, 0, 0] for i in range(length)]\n\n def state_exists(self, state):\n index = 0\n while index < len(self.matrix):\n if state == self.matrix[index][0]:\n return index\n index += 1\n return -1\n\n def get_action_given_state(self, state):\n index = self.state_exists(state)\n if index == -1:\n print(\"State not in policy\")\n return None, None\n else:\n return self.matrix[index][1], self.matrix[index][2]\n\n def update_action_for_state(self, state, new_action, new_reward):\n index = self.state_exists(state)\n if index == -1:\n print(\"State not in policy\")\n return\n else:\n self.matrix[index][1] = new_action\n self.matrix[index][2] = new_reward\n" }, { "alpha_fraction": 0.5421221852302551, "alphanum_fraction": 0.5736334323883057, "avg_line_length": 27.796297073364258, "blob_id": "8571f50be2c9fe7f1da557ffb4834de75362c212", "content_id": "1e90fd1e237f511374d206da7b076b2a53022df9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3110, "license_type": "no_license", "max_line_length": 182, "num_lines": 108, "path": "/api.py", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "from state import State\nfrom robot import Robot\nfrom random import randrange\nfrom cell import Cell\n\nMAPSIZE = 3 # The size of the map knowing that it is a square\nACTIONS = [\"go_forward_vacuuming\", \"go_forward_no_vacuuming\", \"rotate_left\", \"rotate_right\", \"vacuum\", \"recharge\"] # List of possible actions\nDISCOUNTED_FACTOR = 0.9 # The factor used to make the series converge\nINITIAL_MAP = [[Cell(0, 0, 0, 1), Cell(0, 1, 1, 0), Cell(0, 2, 0, 0)], [Cell(1, 0, 1, 0), Cell(1, 1, 0, 0), Cell(1, 2, 1, 0)], [Cell(2, 0, 0, 0), Cell(2, 1, 1, 0), Cell(2, 2, 0, 0)]]\n# Initial map\n# hxo\n# xox\n# oxo\nINITIAL_STATE = State(Robot(0, 0, MAPSIZE, MAPSIZE, 1, 100), INITIAL_MAP, (0, 0))\n\n\n\"\"\"\nPrint a terminal version of the map\n\"\"\"\ndef printmap(mapp):\n for i in range(len(mapp)):\n line = \"\"\n for j in range(len(mapp[i])):\n if mapp[i][j].home == 1:\n line += \"h\"\n elif mapp[i][j].dirty == 1:\n line += \"x\"\n elif mapp[i][j].dirty == 0:\n line += \"o\"\n print(line)\n\n\n\"\"\"\nPrint a readable state\n\"\"\"\ndef printstate(state):\n print(\"Robot coordinates : (\", state.robot.x, \", \", state.robot.y, \")\")\n print(\"Robot battery : \", state.robot.battery)\n print(\"Robot orientation (0 for N, 1 fro E, 2 for S, 3 for W): \", state.robot.orientation)\n print(\"Home base coordinates: (\", state.base[0], \", \", state.base[1], \")\")\n printmap(state.mapp)\n\n\ndef initmap(base_x=0, base_y=0):\n mapp = [[Cell(0, 0, 0, 0) for j in range(MAPSIZE)] for i in range(MAPSIZE)]\n mapp[base_x][base_y] = Cell(base_x, base_y, 0, 1)\n\n return mapp\n\n\n\"\"\"\nCreates a random map given the position of the homebase\n\"\"\"\ndef randommap(basex, basey):\n mapp = [[Cell(0, 0) for j in range(MAPSIZE)] for i in range(MAPSIZE)]\n\n for i in range(MAPSIZE):\n for j in range(MAPSIZE):\n if i == basex and j == basey:\n mapp[i][j] = Cell(i, j, randrange(2), 1)\n else:\n mapp[i][j] = Cell(i, j, randrange(2))\n return mapp\n\n\ndef resetvector(vector):\n return [0.0 for i in range(len(vector))]\n\n\"\"\"\nCreates a random states with random robot and map\n\"\"\"\ndef randomstate():\n base = (randrange(0, MAPSIZE), randrange(0, MAPSIZE))\n robot = Robot(randrange(0, MAPSIZE), randrange(0, MAPSIZE), MAPSIZE, MAPSIZE, randrange(0, 4), randrange(0, 100))\n\n rstate = State(\n robot,\n randommap(base[0], base[1]),\n base\n )\n\n return rstate\n\n\ndef get_state(text):\n index = 0\n robot = Robot(0, 0, MAPSIZE, MAPSIZE, 0, 0)\n mapp = [[Cell(0, 0) for j in range(MAPSIZE)] for i in range(MAPSIZE)]\n for i in range(len(mapp)):\n for j in range(len(mapp[i])):\n mapp[i][j].set(i, j, int(text[index]), int(text[index+1]))\n index += 2\n index += 1\n base = (int(text[index-1]), int(text[index]))\n\n index += 1\n robot.x = int(text[index])\n\n index += 1\n robot.y = int(text[index])\n\n index += 1\n robot.orientation = int(text[index])\n\n index += 1\n robot.battery = int(text[index:])\n\n return State(robot, mapp, base)\n" }, { "alpha_fraction": 0.5668920278549194, "alphanum_fraction": 0.5771358609199524, "avg_line_length": 36.5461540222168, "blob_id": "fa2c195354e79f4a6c1ca823c47a1dca36f4c46d", "content_id": "2e743bd862f05e22fa965cedaea8e54f3e03ff4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4881, "license_type": "no_license", "max_line_length": 165, "num_lines": 130, "path": "/dynamic_programming.py", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "from emulator import Emulator\nfrom state import State\nfrom robot import Robot\nfrom copy import deepcopy\nfrom cell import Cell\nimport numpy as np\nimport itertools\nimport api\n\n\nclass DP:\n\n def __init__(self):\n self.states = [] # all possible states\n self.values = []\n self.threshold = 0.01 # The threshold used to stop the interations\n\n \"\"\"\n generate all the possible states\n \"\"\"\n\n def generate_all_states(self):\n for battery in range(0, 3):\n for robot_x in range(api.MAPSIZE):\n for robot_y in range(api.MAPSIZE):\n for robot_orientation in range(0, 4):\n self.generate_all_map(battery, robot_x, robot_y, robot_orientation, 0, 0)\n\n \"\"\"\n Generate a map using the given parameters\n \"\"\"\n\n def generate_all_map(self, battery, robot_x, robot_y, robot_orientation, base_x, base_y):\n mapp = api.initmap(base_x, base_y)\n all_maps = [np.reshape(np.array(i), (api.MAPSIZE, api.MAPSIZE)) for i in itertools.product([0, 1], repeat=api.MAPSIZE * api.MAPSIZE)]\n abs_battery = 100\n\n if battery == 0:\n abs_battery = 0\n elif battery == 1:\n abs_battery = 10\n elif battery == 2:\n abs_battery = 100\n\n robot = Robot(robot_x, robot_y, api.MAPSIZE, api.MAPSIZE, robot_orientation, abs_battery)\n\n for maps_ind in range(len(all_maps)):\n if all_maps[maps_ind][base_x][base_y] == 0:\n for x in range(api.MAPSIZE):\n for y in range(api.MAPSIZE):\n if x == base_x and y == base_y:\n mapp[x][y] = Cell(x, y, 0, 1)\n else:\n mapp[x][y] = Cell(x, y, all_maps[maps_ind][x][y], 0)\n self.states.append(State(robot, mapp, (base_x, base_y)).to_string())\n\n\n\n \"\"\"\n Get the infinite norm of the difference of two vectors\n \"\"\"\n\n def get_infinite_norme(self, values, values_prime):\n maxvalue = 0.0\n for i in range(len(values)):\n temp = abs(values[i] - values_prime[i])\n if temp > maxvalue:\n maxvalue = temp\n return maxvalue\n\n\n \"\"\"\n Return the value function of a given state\n \"\"\"\n\n def get_value_function(self, emulator, state_ind):\n rewards = [0.0 for i in range(len(api.ACTIONS))]\n newstates = [[0.0, 0.0] for i in range(len(api.ACTIONS))]\n probabilities = [0.0 for i in range(len(api.ACTIONS))]\n q_values = [0.0 for i in range(len(api.ACTIONS))]\n\n # Try each and every one of the possible actions\n for action_ind in range(len(api.ACTIONS)):\n # Get the rewards, states, probabilities as lists\n rewards[action_ind], newstates[action_ind], probabilities[action_ind] = emulator.simulate(api.get_state(self.states[state_ind]), api.ACTIONS[action_ind])\n # Compute Q value\n q_values[action_ind] = rewards[action_ind]\n\n if type(newstates[action_ind]) == list:\n for possible_action in range(len(newstates[action_ind])):\n possible_ind = self.state_exists(newstates[action_ind][possible_action])\n q_values[action_ind] += api.DISCOUNTED_FACTOR * probabilities[action_ind] * self.values[possible_ind]\n else:\n q_values[action_ind] += api.DISCOUNTED_FACTOR * probabilities[action_ind] * self.values[self.state_exists(newstates[action_ind])]\n\n return max(q_values)\n\n def state_exists(self, state):\n index = 0\n while index < len(self.states):\n if state == self.states[index]:\n return index\n index += 1\n return -1\n\n def run(self):\n # Initialization of the simulation\n self.generate_all_states()\n self.values = [0.0 for i in range(len(self.states))]\n\n emulator = Emulator(\"DP\")\n\n while True:\n # Update the values at t-1 according to the values at t\n values_prime = deepcopy(self.values[:])\n # Go through all the states\n for state_ind in range(len(self.states)):\n\n # Update the new maximum value\n self.values[state_ind] = self.get_value_function(emulator, state_ind)\n # If the threshold is bigger than the difference between Vs and their predecessors\n # then we consider the algorithm as successful\n if self.get_infinite_norme(self.values, values_prime) < self.threshold:\n break\n\n s0_index = self.state_exists(api.INITIAL_STATE.to_string())\n # print(\"s0 index:\", self.state_exists(api.INITIAL_STATE.to_string()))\n # print(\"s0 id:\", self.state_exists(api.INITIAL_STATE.to_string()))\n # print(\"Value: \", self.values[s0_index])\n return self.values[s0_index]\n" }, { "alpha_fraction": 0.492233008146286, "alphanum_fraction": 0.49708738923072815, "avg_line_length": 28.428571701049805, "blob_id": "1a05db70830883dc243ce034f8963ad32f0430d6", "content_id": "99d04a630f3de7e18e775fe6693387aa18e06b9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 73, "num_lines": 35, "path": "/state.py", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "import api\n\n\nclass State:\n def __init__(self, robot, mapp, base):\n self.robot = robot\n self.mapp = mapp\n self.base = base\n\n def is_final_state(self):\n # Check if all map is clean\n for i in range(api.MAPSIZE):\n for j in range(api.MAPSIZE):\n if self.mapp[i][j].dirty == 1:\n return False\n # Check if robot at base\n if self.robot.x == self.base[0] and self.robot.y == self.base[1]:\n return True\n else:\n return False\n\n def to_string(self):\n text = \"\"\n for i in range(len(self.mapp)):\n for j in range(len(self.mapp[i])):\n cell = self.mapp[i][j]\n text += str(cell.dirty)\n text += str(cell.home)\n text += str(self.base[0])\n text += str(self.base[1])\n text += str(self.robot.x)\n text += str(self.robot.y)\n text += str(self.robot.orientation)\n text += str(self.robot.battery)\n return text\n" }, { "alpha_fraction": 0.46047431230545044, "alphanum_fraction": 0.46640315651893616, "avg_line_length": 21, "blob_id": "488270b49320de58445b3b8adb52b23bfba28887", "content_id": "be771c62135bba6e3730484388f07696c3ef1478", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 506, "license_type": "no_license", "max_line_length": 46, "num_lines": 23, "path": "/cell.py", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "class Cell:\n def __init__(self, x, y, dirty=0, home=0):\n self.x = x\n self.y = y\n self.dirty = dirty\n self.home = home\n\n def set(self, x, y, dirty, home):\n self.x = x\n self.y = y\n self.dirty = dirty\n self.home = home\n\n def clean(self):\n self.dirty = 0\n\n def to_string(self):\n text = \"\"\n text += str(self.x)\n text += str(self.y)\n text += str(self.dirty)\n text += str(self.home)\n return text\n" }, { "alpha_fraction": 0.4102359712123871, "alphanum_fraction": 0.4395101070404053, "avg_line_length": 47.269229888916016, "blob_id": "ef5c41ee64b23825a47608913d961cd12c1d0d39", "content_id": "a8b74d1e99b1111e03bfa720555f991abae72f97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10043, "license_type": "no_license", "max_line_length": 112, "num_lines": 208, "path": "/emulator.py", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "from random import randrange\nfrom copy import deepcopy\nimport api\n\n\nclass Emulator:\n def __init__(self, algorithm):\n self.algorithm = algorithm\n\n # rewards and transition model under the idea of ((action reward + time reward), probability of success)\n self.empty_battery = {\"go_forward_vacuuming\": ((-100 + -1), 0.0),\n \"go_forward_no_vacuuming\": ((-100 + -1), 0.0),\n \"rotate_left\": ((-100 + -1), 0.0),\n \"rotate_right\": ((-100 + -1), 0.0),\n \"vacuum\": ((-100 + -1), 0.0),\n \"recharge\": (0, 1.0)}\n self.critical_battery = {\"go_forward_vacuuming\": ((-3 + -1), 1.0),\n \"go_forward_no_vacuuming\": ((0 + -1), 1.0),\n \"rotate_left\": ((0 + -1), 1.0),\n \"rotate_right\": ((0 + -1), 1.0),\n \"vacuum\": ((-5 + -1), 1.0),\n \"recharge\": (0, 1.0)}\n self.sufficient_battery = {\"go_forward_vacuuming\": ((0 + -1), 1.0),\n \"go_forward_no_vacuuming\": ((0 + -1), 1.0),\n \"rotate_left\": ((0 + -1), 1.0),\n \"rotate_right\": ((0 + -1), 1.0),\n \"vacuum\": ((0 + -1), 1.0),\n \"recharge\": (0, 1.0)}\n self.front_wall = {\"go_forward_vacuuming\": (-10, 0.0),\n \"go_forward_no_vacuuming\": (-10, 0.0),\n \"rotate_left\": (10, 1.0),\n \"rotate_right\": (10, 1.0),\n \"vacuum\": (0, 1.0),\n \"recharge\": (0, 1.0)}\n self.right_wall = {\"go_forward_vacuuming\": (0, 1.0),\n \"go_forward_no_vacuuming\": (0, 1.0),\n \"rotate_left\": (0, 1.0),\n \"rotate_right\": (-10, 1.0),\n \"vacuum\": (0, 1.0),\n \"recharge\": (0, 1.0)}\n self.left_wall = {\"go_forward_vacuuming\": (0, 1.0),\n \"go_forward_no_vacuuming\": (0, 1.0),\n \"rotate_left\": (-10, 1.0),\n \"rotate_right\": (0, 1.0),\n \"vacuum\": (0, 1.0),\n \"recharge\": (0, 1.0)}\n self.dirty_cell = {\"go_forward_vacuuming\": (40, 0.9),\n \"go_forward_no_vacuuming\": (-40, 0.8),\n \"rotate_left\": (0, 1.0),\n \"rotate_right\": (0, 1.0),\n \"vacuum\": (40, 1.0),\n \"recharge\": (0, 1.0)}\n self.clean_cell = {\"go_forward_vacuuming\": (-10, 0.9),\n \"go_forward_no_vacuuming\": (5, 0.9),\n \"rotate_left\": (0, 1.0),\n \"rotate_right\": (0, 1.0),\n \"vacuum\": (-10, 1.0),\n \"recharge\": (0, 1.0)}\n\n \"\"\"\n Simulate the model according to the algorithm we're using\n \"\"\"\n\n def simulate(self, state, action):\n reward = 0\n probability = 1.0\n newstate = deepcopy(state)\n\n # Checks that the action exists\n api.ACTIONS.index(action)\n\n if state.robot is not None and state.mapp is not None:\n\n if state.is_final_state():\n reward += 100\n return reward, newstate, probability\n\n # Battery check\n if state.robot.battery == 0:\n reward += self.empty_battery.get(action)[0]\n probability *= self.empty_battery.get(action)[1]\n elif state.robot.battery <= 10:\n reward += self.critical_battery.get(action)[0]\n probability *= self.critical_battery.get(action)[1]\n elif state.robot.battery >= 10:\n reward += self.sufficient_battery.get(action)[0]\n probability *= self.sufficient_battery.get(action)[1]\n\n # Position check\n if state.robot.orientation == 0:\n if state.robot.x == 0:\n reward += self.left_wall.get(action)[0]\n probability *= self.left_wall.get(action)[1]\n if state.robot.y == 0:\n reward += self.front_wall.get(action)[0]\n probability *= self.front_wall.get(action)[1]\n if state.robot.x == api.MAPSIZE - 1:\n reward += self.right_wall.get(action)[0]\n probability *= self.right_wall.get(action)[1]\n\n elif state.robot.orientation == 1:\n if state.robot.y == 0:\n reward += self.left_wall.get(action)[0]\n probability *= self.left_wall.get(action)[1]\n if state.robot.x == api.MAPSIZE - 1:\n reward += self.front_wall.get(action)[0]\n probability *= self.front_wall.get(action)[1]\n if state.robot.y == api.MAPSIZE - 1:\n reward += self.right_wall.get(action)[0]\n probability *= self.right_wall.get(action)[1]\n\n elif state.robot.orientation == 2:\n if state.robot.x == api.MAPSIZE - 1:\n reward += self.left_wall.get(action)[0]\n probability *= self.left_wall.get(action)[1]\n if state.robot.y == api.MAPSIZE - 1:\n reward += self.front_wall.get(action)[0]\n probability *= self.front_wall.get(action)[1]\n if state.robot.x == 0:\n reward += self.right_wall.get(action)[0]\n probability *= self.right_wall.get(action)[1]\n\n elif state.robot.orientation == 3:\n if state.robot.y == api.MAPSIZE - 1:\n reward += self.left_wall.get(action)[0]\n probability *= self.left_wall.get(action)[1]\n if state.robot.x == 0:\n reward += self.front_wall.get(action)[0]\n probability *= self.front_wall.get(action)[1]\n if state.robot.y == 0:\n reward += self.right_wall.get(action)[0]\n probability *= self.right_wall.get(action)[1]\n\n # Dirtiness check\n if newstate.mapp[state.robot.x][state.robot.y].dirty == 0:\n reward += self.clean_cell.get(action)[0]\n probability *= self.clean_cell.get(action)[1]\n elif newstate.mapp[state.robot.x][state.robot.y].dirty == 1:\n reward += self.dirty_cell.get(action)[0]\n probability *= self.dirty_cell.get(action)[1]\n\n if self.algorithm == \"DP\":\n newstate2 = deepcopy(state)\n # Probability computation and robot parameters update\n if action == \"recharge\":\n if state.robot.x == state.base[0] and state.robot.y == state.base[1]:\n if state.robot.battery == 100:\n reward = reward - 20\n else:\n newstate.robot.battery = 100\n newstate2.robot.battery = 100\n reward += 20\n else:\n reward = reward - 20\n elif action == \"go_forward_vacuuming\":\n newstate.robot.go_forward()\n newstate.mapp[state.robot.x][state.robot.y].clean()\n newstate2.mapp[state.robot.x][state.robot.y].clean()\n newstate.robot.lower_battery()\n newstate2.robot.lower_battery()\n elif action == \"go_forward_no_vacuuming\":\n newstate.robot.go_forward()\n newstate.robot.lower_battery()\n newstate2.robot.lower_battery()\n elif action == \"rotate_right\":\n newstate.robot.rotate_right()\n elif action == \"rotate_left\":\n newstate.robot.rotate_left()\n elif action == \"vacuum\":\n newstate.mapp[state.robot.x][state.robot.y].clean()\n newstate.robot.lower_battery()\n\n return reward, [newstate, newstate2], probability\n\n elif self.algorithm == \"MC\":\n\n # Probability computation and robot parameters update\n if action == \"recharge\":\n if state.robot.x == state.base[0] and state.robot.y == state.base[1]:\n if state.robot.battery == 100:\n reward = reward - 20\n else:\n newstate.robot.battery = 100\n reward += 20\n else:\n reward = reward - 20\n elif action == \"go_forward_vacuuming\":\n dice = randrange(1, 100)\n if dice <= probability * 100:\n newstate.robot.go_forward()\n newstate.mapp[state.robot.x][state.robot.y].clean()\n newstate.robot.lower_battery()\n elif action == \"go_forward_no_vacuuming\":\n dice = randrange(1, 100)\n if dice <= probability * 100:\n newstate.robot.go_forward()\n elif action == \"rotate_right\":\n newstate.robot.rotate_right()\n elif action == \"rotate_left\":\n newstate.robot.rotate_left()\n elif action == \"vacuum\":\n newstate.mapp[state.robot.x][state.robot.y].clean()\n newstate.robot.lower_battery()\n\n return reward, newstate, probability\n else:\n print(\"Unrecognized state in function simulate\")\n return\n\n\n\n" }, { "alpha_fraction": 0.5420833230018616, "alphanum_fraction": 0.5529166460037231, "avg_line_length": 19.3389835357666, "blob_id": "f3da9b0619e1a1a867dd4730764cde732248816f", "content_id": "dd6e26e41c440fa847140e0771d6fc57a6f477f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2400, "license_type": "no_license", "max_line_length": 206, "num_lines": 118, "path": "/main.py", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "from dynamic_programming import DP\nfrom monte_carlo import MC\nfrom q_learning import QL\nimport matplotlib.pyplot as plt\n\nEPISODE = 50\nplt.xlabel(\"Number of episodes\")\nplt.ylabel(\"Performance\")\n\nalgorithm_choice = \"\"\nwhile algorithm_choice != \"DP\" and algorithm_choice != \"MC\" and algorithm_choice != \"QL\" and algorithm_choice != \"dp\" and algorithm_choice != \"mc\" and algorithm_choice != \"ql\" and algorithm_choice != \"all\":\n algorithm_choice = str(input(\"Choose the algorithm to execute (DP; MC; QL; all) : \"))\n\nif algorithm_choice == \"DP\" or algorithm_choice == \"dp\":\n \"\"\"\n Dynamic Programming\n \"\"\"\n # Initialization\n DP = DP()\n v_s0 = DP.run()\n\n plt.plot([v_s0 for i in range(100)])\n plt.title(\"Dynamic Programing\")\n plt.show()\n print(\"The performance of Dynamic Programming is : \", v_s0)\n\n\nelif algorithm_choice == \"MC\" or algorithm_choice == \"mc\":\n \"\"\"\n Monte Carlo\n \"\"\"\n MC = MC()\n q = []\n\n for t in range(0, EPISODE):\n v = MC.run(100, t)\n q.append(v)\n\n plt.plot(q)\n plt.title(\"Monte Carlo\")\n plt.show()\n\nelif algorithm_choice == \"QL\" or algorithm_choice == \"ql\":\n \"\"\"\n Q-Learning\n \"\"\"\n QL = QL()\n ql = []\n\n i = 0\n while i < EPISODE:\n v = QL.run(i)\n ql.append(v)\n i += 1\n\n plt.plot(ql)\n plt.title(\"Q Learning\")\n plt.show()\n\nelif algorithm_choice == \"all\":\n \"\"\"\n Dynamic Programming\n \"\"\"\n plt.plot([4.72 for i in range(EPISODE)], label='DP')\n\n \"\"\"\n Monte Carlo\n \"\"\"\n MC = MC()\n q = []\n\n for t in range(0, EPISODE):\n v = MC.run(EPISODE, t)\n q.append(v)\n\n plt.plot(q, label='MC')\n\n \"\"\"\n Q-Learning\n \"\"\"\n QL = QL()\n ql = []\n\n i = 0\n while i < EPISODE:\n v = QL.run(i)\n ql.append(v)\n i += 1\n\n plt.plot(ql, label='QL')\n plt.title(\"All algorithms\")\n plt.ylim([0, 50])\n\n \"\"\"\n Dynamic Programming\n \"\"\"\n plt.figure()\n plt.plot([4.72 for i in range(EPISODE)], label='DP')\n plt.title(\"Dynamic Programing\")\n\n \"\"\"\n Monte-Carlo\n \"\"\"\n plt.figure()\n plt.plot(q, label='MC')\n plt.title(\"Monte Carlo\")\n plt.xlabel(\"Number of episodes\")\n plt.ylabel(\"Performance\")\n\n \"\"\"\n Q-Learning\n \"\"\"\n plt.figure()\n plt.plot(ql, label='QL')\n plt.title(\"Q Learning\")\n plt.xlabel(\"Number of episodes\")\n plt.ylabel(\"Performance\")\n plt.show()\n" }, { "alpha_fraction": 0.6610169410705566, "alphanum_fraction": 0.6610169410705566, "avg_line_length": 11, "blob_id": "9eab58c01a27cef1524ec78a879e2ede8aee4fbc", "content_id": "0129074de8f1e6440bf59d3b93d438c714714d3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 59, "license_type": "no_license", "max_line_length": 26, "num_lines": 5, "path": "/Makefile", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "make:\n pip install matplotlib\n\nrun:\n python ./main.py" }, { "alpha_fraction": 0.5024301409721375, "alphanum_fraction": 0.5185297727584839, "avg_line_length": 31.27450942993164, "blob_id": "71f68c32ca9a30e7e018e8edb5a95d25c29e2aca", "content_id": "2427110848f03ca9efd89eb2d30a1b9a6a42ea3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3292, "license_type": "no_license", "max_line_length": 189, "num_lines": 102, "path": "/monte_carlo.py", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "import copy\nfrom emulator import Emulator\nfrom state import State\nfrom robot import Robot\nimport random\nimport api\n\n\nclass MC:\n emulator = Emulator(\"MC\")\n epsilon = 0.1\n alpha = 0.001\n gamma = 0.9\n Q_function = {}\n\n def argmax_q_function(self, state):\n \"\"\"\n Calculate argmax(a) of Q(s, a)\n :return: a ( the action that maximizez Q(s,a) ), max_q (the maximal value)\n \"\"\"\n a = api.ACTIONS[random.randrange(len(api.ACTIONS))]\n if (state, a) not in self.Q_function.keys():\n self.Q_function[(state, a)] = 0\n max_q = self.Q_function[(state, a)]\n for action in api.ACTIONS:\n if (state, action) not in self.Q_function.keys():\n self.Q_function[(state, action)] = 0\n if self.Q_function[(state, action)] > max_q:\n max_q = self.Q_function[(state, action)]\n a = action\n return a, max_q\n\n def generate_episode(self, length):\n \"\"\"\n Generate an episode\n :param length: number of (s, a, r) sequences\n :return: list of (s, a, r) sequences\n \"\"\"\n\n episode = []\n index_episode = 0\n\n # (s0, a0, r0) generation\n\n s = State(Robot(0, 0, api.MAPSIZE, api.MAPSIZE, 1, 100), api.INITIAL_MAP, (0, 0))\n id_s = s.to_string()\n\n # epsilon-greedy choice of a0\n\n dice = random.uniform(0, 1)\n if dice > self.epsilon:\n a = self.argmax_q_function(id_s)[0]\n else:\n a = copy.copy(api.ACTIONS[random.randrange(len(api.ACTIONS))])\n\n r = self.emulator.simulate(s, a)[0]\n\n episode.append([id_s, a, r])\n\n # Generation of the nex length-1 sequences\n\n while index_episode < length and s.robot.battery >= 0 and not s.is_final_state():\n index_episode += 1\n s = self.emulator.simulate(s, a)[1]\n id_s = s.to_string()\n\n # epsilon-greedy choice of a0\n\n dice = random.uniform(0, 1)\n if dice > self.epsilon:\n a = self.argmax_q_function(id_s)[0]\n else:\n a = copy.copy(api.ACTIONS[random.randrange(len(api.ACTIONS))])\n\n r = self.emulator.simulate(s, a)[0]\n\n episode.append([id_s, a, r])\n return episode\n\n def run(self, limit, T):\n \"\"\"\n Run Monte Carlo algorithm\n :param limit: when to stop algorithm ( limit -> infinity)\n :param T: episodes length\n :return: max Q(s0, a)\n \"\"\"\n i = 0\n G = {}\n\n while i < limit:\n i += 1\n episode = self.generate_episode(T)\n ep_length = len(episode)\n for t in range(0, ep_length):\n G[t] = 0\n for k in range(t, ep_length):\n G[t] += episode[k][2] * (self.gamma ** k)\n if (episode[t][0], episode[t][1]) in self.Q_function.keys():\n self.Q_function[(episode[t][0], episode[t][1])] = self.Q_function[(episode[t][0], episode[t][1])] + self.alpha * (G[t] - self.Q_function[(episode[t][0], episode[t][1])])\n else:\n self.Q_function[(episode[t][0], episode[t][1])] = self.alpha * G[t]\n return self.argmax_q_function(api.INITIAL_STATE.to_string())[1]\n" }, { "alpha_fraction": 0.505150556564331, "alphanum_fraction": 0.5150554776191711, "avg_line_length": 32.21052551269531, "blob_id": "8df9a97352110e8394111e46210f3b656e8421e6", "content_id": "100ee0f4834e8cb27dafd322b3b4135b8649c89c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2524, "license_type": "no_license", "max_line_length": 84, "num_lines": 76, "path": "/q_learning.py", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "from emulator import Emulator\nimport random\nimport api\nimport copy\n\n\nclass QL:\n emulator = Emulator(\"MC\")\n epsilon = 0.2\n alpha = 0.1\n gamma = 0.99\n Q_function = {}\n\n def argmax_q_function(self, state):\n \"\"\"\n Calculate argmax(a) of Q(s, a)\n :return: a ( the action that maximizez Q(s,a) ), max_q (the maximal value)\n \"\"\"\n a = api.ACTIONS[random.randrange(len(api.ACTIONS))]\n if (state, a) not in self.Q_function.keys():\n self.Q_function[(state, a)] = 0\n max_q = self.Q_function[(state, a)]\n for action in api.ACTIONS:\n if (state, action) not in self.Q_function.keys():\n self.Q_function[(state, action)] = 0\n if self.Q_function[(state, action)] > max_q:\n max_q = self.Q_function[(state, action)]\n a = action\n return a, max_q\n\n def run(self, limit):\n \"\"\"\n Run Q-Learning algorithm\n :param limit: when to stop algorithm / episode length\n :return: max Q(s0, a)\n \"\"\"\n i = 0\n\n s = copy.deepcopy(api.INITIAL_STATE)\n id_s = s.to_string()\n\n # epsilon-greedy choice of a0\n dice = random.uniform(0, 1)\n if dice > self.epsilon:\n a = self.argmax_q_function(id_s)[0]\n else:\n a = api.ACTIONS[random.randrange(len(api.ACTIONS))]\n\n while i < limit:\n i += 1\n if s.robot.battery <= 0 or s.is_final_state():\n break\n r = self.emulator.simulate(s, a)[0]\n s_prime = copy.deepcopy(self.emulator.simulate(s, a)[1])\n\n # epsilon-greedy choice of a_prime\n dice = random.uniform(0, 1)\n if dice > self.epsilon:\n (a_prime, maxQ) = self.argmax_q_function(s_prime)\n else:\n a_prime = api.ACTIONS[random.randrange(len(api.ACTIONS))]\n if (id_s, a_prime) in self.Q_function.keys():\n maxQ = self.argmax_q_function(s_prime)[1]\n else:\n maxQ = 0\n\n if (id_s, a) not in self.Q_function.keys():\n self.Q_function[(id_s, a)] = 0\n\n delta = r + self.gamma * maxQ - self.Q_function[id_s, a]\n self.Q_function[id_s, a] = self.Q_function[id_s, a] + self.alpha * delta\n\n a = copy.deepcopy(a_prime)\n s = copy.deepcopy(s_prime)\n id_s = s.to_string()\n return self.argmax_q_function(api.INITIAL_STATE.to_string())[1]\n" }, { "alpha_fraction": 0.45873016119003296, "alphanum_fraction": 0.48253968358039856, "avg_line_length": 29, "blob_id": "aa43f0d1d183aeac5d5af738e2b1551f3cac8aaa", "content_id": "a3421460b39241cf4fe98efa6413777a2f351567", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1890, "license_type": "no_license", "max_line_length": 94, "num_lines": 63, "path": "/robot.py", "repo_name": "ancastoica/IAR-robot-cleaner-1", "src_encoding": "UTF-8", "text": "class Robot:\n def __init__(self, x, y, X, Y, orientation=1, battery=100):\n \"\"\"\n Robot's position x, y\n Boundaries of the map - number of lines Y and number of columns X\n Orientation between 0 and 4:\n 0\n 3 | | 1\n 2\n \"\"\"\n self.x = x\n self.y = y\n self.X = X\n self.Y = Y\n self.orientation = orientation\n self.battery = battery\n\n def set_position(self, x, y):\n if 0 <= x < self.X:\n self.x = x\n if 0 <= y < self.Y:\n self.y = y\n\n def rotate_right(self):\n \"\"\"\n Right rotation => orientation 2 becomes 3, 3 becomes 0 etc.\n \"\"\"\n if self.battery > 0:\n self.orientation = (self.orientation + 1) % 4\n self.battery = self.battery - 1\n\n def rotate_left(self):\n \"\"\"\n Left rotation => orientation 3 becomes 2, 0 becomes 3 etc.\n \"\"\"\n if self.battery > 0:\n self.orientation = (self.orientation - 1) % 4\n self.battery = self.battery - 1\n\n def go_forward(self):\n \"\"\"\n Go forward 1 cell according to the orientation - only if possible (between boundaries)\n \"\"\"\n if self.battery > 0:\n self.battery = self.battery - 1\n\n if self.orientation == 0 and self.x != 0:\n self.x = self.x - 1\n elif self.orientation == 1 and self.y != self.Y - 1:\n self.y = self.y + 1\n elif self.orientation == 2 and self.x != self.X - 1:\n self.x = self.x + 1\n elif self.orientation == 3 and self.y != 0:\n self.y = self.y - 1\n\n def lower_battery(self, n=1):\n \"\"\"\n Lower robot's battery by n units\n \"\"\"\n if self.battery >= n:\n self.battery = self.battery - n\n else:\n self.battery = 0\n" } ]
12
memazouni/blockchainSimulator
https://github.com/memazouni/blockchainSimulator
b2f0b6a33eba719fd46db627af28abc7740c871d
5f101f4771e7a6152c1ca7e0ed9f997a1d2b4fc7
c235c5a556a9ca4a3580879a56b0e3d1df8cc4d5
refs/heads/master
2020-07-06T21:19:03.784585
2019-05-16T21:41:18
2019-05-16T21:41:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7678571343421936, "alphanum_fraction": 0.8035714030265808, "avg_line_length": 52, "blob_id": "ce0cc6ace41ed1b70b9efa9e4867bf62861f4885", "content_id": "872b55b1fca6bb18a2b9c835e851a86e4d3ccba5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 56, "license_type": "no_license", "max_line_length": 52, "num_lines": 1, "path": "/sm1thbr3nblock.py", "repo_name": "memazouni/blockchainSimulator", "src_encoding": "UTF-8", "text": "\nhttps://github.com/sm1thbr3n/blockchainSimulator.git\n \n" } ]
1
leemin-woo/driving-car
https://github.com/leemin-woo/driving-car
7b5ef437a945bd83c2677130f4a293be1ef937e1
09945f1eddcc6a5a51f878ab2b00df430e198dd6
0c5d4154aeadd42b6544eb975a2b54eed1377b24
refs/heads/master
2022-11-09T00:33:35.733049
2020-06-18T07:44:58
2020-06-18T07:44:58
273,002,678
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5508486032485962, "alphanum_fraction": 0.5747249126434326, "avg_line_length": 32.656673431396484, "blob_id": "656d1c3f39af293b446d3198b6c96329eedb109a", "content_id": "09e96a3b2748a74e38b01f6b62e5d01ed54879d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22458, "license_type": "no_license", "max_line_length": 121, "num_lines": 667, "path": "/main (copy).py", "repo_name": "leemin-woo/driving-car", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport rospkg\nimport rospy\nimport sys\nimport os\nfrom sensor_msgs.msg import CompressedImage\n\ntry:\n os.chdir(os.path.dirname(__file__))\n os.system('clear')\n print(\"\\nWait for initial setup, please don't connect anything yet...\\n\")\n sys.path.remove('/opt/ros/lunar/lib/python2.7/dist-packages')\nexcept:\n pass\n\nfrom std_msgs.msg import Float32\nimport cv2\nimport numpy as np\nfrom ctypes import *\nimport math\nimport random\nimport time\n\n\nclass BOX(Structure):\n _fields_ = [(\"x\", c_float),\n (\"y\", c_float),\n (\"w\", c_float),\n (\"h\", c_float)]\n\n\nclass DETECTION(Structure):\n _fields_ = [(\"bbox\", BOX),\n (\"classes\", c_int),\n (\"prob\", POINTER(c_float)),\n (\"mask\", POINTER(c_float)),\n (\"objectness\", c_float),\n (\"sort_class\", c_int)]\n\n\nclass IMAGE(Structure):\n _fields_ = [(\"w\", c_int),\n (\"h\", c_int),\n (\"c\", c_int),\n (\"data\", POINTER(c_float))]\n\n\nclass METADATA(Structure):\n _fields_ = [(\"classes\", c_int),\n (\"names\", POINTER(c_char_p))]\n\n\nrospack = rospkg.RosPack()\npath = rospack.get_path('ithutech')\nos.chdir(path)\n\nhasGPU = True\nlib = CDLL(\n \"./model/darknet.so\", RTLD_GLOBAL)\nlib.network_width.argtypes = [c_void_p]\nlib.network_width.restype = c_int\nlib.network_height.argtypes = [c_void_p]\nlib.network_height.restype = c_int\n\npredict = lib.network_predict\npredict.argtypes = [c_void_p, POINTER(c_float)]\npredict.restype = POINTER(c_float)\n\nif hasGPU:\n set_gpu = lib.cuda_set_device\n set_gpu.argtypes = [c_int]\n\nmake_image = lib.make_image\nmake_image.argtypes = [c_int, c_int, c_int]\nmake_image.restype = IMAGE\n\nget_network_boxes = lib.get_network_boxes\nget_network_boxes.argtypes = [c_void_p, c_int, c_int, c_float, c_float, POINTER(\n c_int), c_int, POINTER(c_int), c_int]\nget_network_boxes.restype = POINTER(DETECTION)\n\nmake_network_boxes = lib.make_network_boxes\nmake_network_boxes.argtypes = [c_void_p]\nmake_network_boxes.restype = POINTER(DETECTION)\n\nfree_detections = lib.free_detections\nfree_detections.argtypes = [POINTER(DETECTION), c_int]\n\nfree_ptrs = lib.free_ptrs\nfree_ptrs.argtypes = [POINTER(c_void_p), c_int]\n\nnetwork_predict = lib.network_predict\nnetwork_predict.argtypes = [c_void_p, POINTER(c_float)]\n\nreset_rnn = lib.reset_rnn\nreset_rnn.argtypes = [c_void_p]\n\nload_net = lib.load_network\nload_net.argtypes = [c_char_p, c_char_p, c_int]\nload_net.restype = c_void_p\n\nload_net_custom = lib.load_network_custom\nload_net_custom.argtypes = [c_char_p, c_char_p, c_int, c_int]\nload_net_custom.restype = c_void_p\n\ndo_nms_obj = lib.do_nms_obj\ndo_nms_obj.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\ndo_nms_sort = lib.do_nms_sort\ndo_nms_sort.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\nfree_image = lib.free_image\nfree_image.argtypes = [IMAGE]\n\nletterbox_image = lib.letterbox_image\nletterbox_image.argtypes = [IMAGE, c_int, c_int]\nletterbox_image.restype = IMAGE\n\nload_meta = lib.get_metadata\nlib.get_metadata.argtypes = [c_char_p]\nlib.get_metadata.restype = METADATA\n\nload_image = lib.load_image_color\nload_image.argtypes = [c_char_p, c_int, c_int]\nload_image.restype = IMAGE\n\nrgbgr_image = lib.rgbgr_image\nrgbgr_image.argtypes = [IMAGE]\n\npredict_image = lib.network_predict_image\npredict_image.argtypes = [c_void_p, IMAGE]\npredict_image.restype = POINTER(c_float)\n\n\naltNames = ['turn_left_sign', 'turn_right_sign',\n 'rock', 'small_box', 'big_box']\nconfigPath = \"./model/yolov3-tiny_obj.cfg\"\nmetaPath = \"./model/obj.data\"\nweightPath = \"./model/yolov3-tiny_obj_last.weights\"\nnetMain = load_net_custom(configPath.encode(\n \"ascii\"), weightPath.encode(\"ascii\"), 0, 1)\nmetaMain = load_meta(metaPath.encode(\"ascii\"))\n\n\ndef array_to_image(arr):\n # need to return old values to avoid python freeing memory\n arr = arr.transpose(2, 0, 1)\n c = arr.shape[0]\n h = arr.shape[1]\n w = arr.shape[2]\n arr = np.ascontiguousarray(arr.flat, dtype=np.float32) / 255.0\n data = arr.ctypes.data_as(POINTER(c_float))\n im = IMAGE(w, h, c, data)\n return im, arr\n\n\ndef detect(image, net=netMain, meta=metaMain, thresh=.5, hier_thresh=.5, nms=.45):\n \"\"\"\n Performs the meat of the detection\n \"\"\"\n im, _ = array_to_image(image)\n num = c_int(0)\n pnum = pointer(num)\n predict_image(net, im)\n dets = get_network_boxes(net, im.w, im.h, thresh,\n hier_thresh, None, 0, pnum, 0)\n num = pnum[0]\n if nms:\n do_nms_sort(dets, num, meta.classes, nms)\n res = []\n for j in range(num):\n for i in range(meta.classes):\n if dets[j].prob[i] > 0:\n b = dets[j].bbox\n if altNames is None:\n nameTag = meta.names[i]\n else:\n nameTag = altNames[i]\n res.append((nameTag, dets[j].prob[i], (b.x, b.y, b.w, b.h)))\n res = sorted(res, key=lambda x: -x[1])\n # free_image(im)\n # free_detections(dets, num)\n return res\n\n\ndef to_hls(img):\n \"\"\"\n Returns the same image in HLS format\n The input image must be in RGB format\n \"\"\"\n return cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n\n\ndef to_lab(img):\n \"\"\"\n Returns the same image in LAB format\n Th input image must be in RGB format\n \"\"\"\n return cv2.cvtColor(img, cv2.COLOR_RGB2LAB)\n\n\ndef draw_lines(img, lines, color=[255, 0, 0], thickness=10):\n \"\"\"\n NOTE: this is the function you might want to use as a starting point once you want to \n average/extrapolate the line segments you detect to map out the full\n extent of the lane (going from the result shown in raw-lines-example.mp4\n to that shown in P1_example.mp4). \n Think about things like separating line segments by their \n slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left\n line vs. the right line. Then, you can average the position of each of \n the lines and extrapolate to the top and bottom of the lane.\n This function draws `lines` with `color` and `thickness`. \n Lines are drawn on the image inplace (mutates the image).\n If you want to make the lines semi-transparent, think about combining\n this function with the weighted_img() function below\n \"\"\"\n global x_des, y_des, angle, turn_left, turn_right, turning_left, turning_right, rock, rocking, lost_lane\n\n # In case of error, don't draw the line\n draw_right = True\n draw_left = True\n\n # Find slopes of all lines\n # But only care about lines where abs(slope) > slope_threshold\n slope_threshold = 0.5\n slopes = []\n new_lines = []\n for line in lines:\n x1, y1, x2, y2 = line[0] # line = [[x1, y1, x2, y2]]\n\n # Calculate slope\n if x2 - x1 == 0.: # corner case, avoiding division by 0\n slope = 999. # practically infinite slope\n else:\n slope = (y2 - y1) / (x2 - x1)\n\n # Filter lines based on slope\n if abs(slope) > slope_threshold:\n slopes.append(slope)\n new_lines.append(line)\n\n lines = new_lines\n\n # Split lines into right_lines and left_lines, representing the right and left lane lines\n # Right/left lane lines must have positive/negative slope, and be on the right/left half of the image\n right_lines = []\n left_lines = []\n for i, line in enumerate(lines):\n x1, y1, x2, y2 = line[0]\n img_x_center = img.shape[1] / 2 # x coordinate of center of image\n if slopes[i] > 0 and x1 > img_x_center and x2 > img_x_center:\n right_lines.append(line)\n elif slopes[i] < 0 and x1 < img_x_center and x2 < img_x_center:\n left_lines.append(line)\n\n # Run linear regression to find best fit line for right and left lane lines\n # Right lane lines\n right_lines_x = []\n right_lines_y = []\n\n for line in right_lines:\n x1, y1, x2, y2 = line[0]\n\n right_lines_x.append(x1)\n right_lines_x.append(x2)\n\n right_lines_y.append(y1)\n right_lines_y.append(y2)\n\n if len(right_lines_x) > 0:\n right_m, right_b = np.polyfit(\n right_lines_x, right_lines_y, 1) # y = m*x + b\n else:\n right_m, right_b = 1, 1\n draw_right = False\n\n # Left lane lines\n left_lines_x = []\n left_lines_y = []\n\n for line in left_lines:\n x1, y1, x2, y2 = line[0]\n\n left_lines_x.append(x1)\n left_lines_x.append(x2)\n\n left_lines_y.append(y1)\n left_lines_y.append(y2)\n\n if len(left_lines_x) > 0:\n left_m, left_b = np.polyfit(\n left_lines_x, left_lines_y, 1) # y = m*x + b\n else:\n left_m, left_b = 1, 1\n draw_left = False\n\n # Find 2 end points for right and left lines, used for drawing the line\n # y = m*x + b --> x = (y - b)/m\n y1 = img.shape[0]\n y2 = img.shape[0] * (1 - trap_height)\n\n right_x1 = (y1 - right_b) / right_m\n right_x2 = (y2 - right_b) / right_m\n\n left_x1 = (y1 - left_b) / left_m\n left_x2 = (y2 - left_b) / left_m\n\n # Convert calculated end points from float to int\n y1 = int(y1)\n y2 = int(y2)\n right_x1 = int(right_x1)\n right_x2 = int(right_x2)\n left_x1 = int(left_x1)\n left_x2 = int(left_x2)\n\n # print('Left:')\n # print('(', left_x1, ',', y1, '), (', left_x2, ',', y2, ')')\n # print('Right:')\n # print('(', right_x1, ',', y1, '), (', right_x2, ',', y2, ')')\n\n # Draw the right and left lines on image\n if draw_right:\n cv2.line(img, (right_x1, y1), (right_x2, y2), color, thickness)\n if draw_left:\n cv2.line(img, (left_x1, y1), (left_x2, y2), color, thickness)\n if draw_left and draw_right:\n x_des = int((left_x1 + right_x1)/2)\n y_des = int(y1-50)\n\n # print('Center:')\n # print('(', x_des, ',', y_des, ')')\n\n dx = x_des - car_pos_x\n dy = car_pos_y - y_des\n\n if dx < 0:\n angle = -np.arctan(-dx/dy) * 180/math.pi\n elif dx == 0:\n angle = 0\n else:\n angle = np.arctan(dx/dy) * 180/math.pi\n\n # size of rock bigger than 4700 (rock is very close)\n if rock >= 4700 and not draw_left and not draw_right:\n turn_left = 0\n turn_right = 0\n angle = 80\n else:\n if turning_left != 0 or turning_right != 0:\n if turning_left > 0 and turning_left < turn_step_left:\n for _ in range(20):\n car_control(angle=-90, speed=50)\n print(\n '------------------------------------Turn leftingg-------------------------------')\n turning_left += 1\n if turning_left == turn_step_left:\n for _ in range(10):\n car_control(angle=90, speed=20)\n print(\n '------------------------------------Correcting-------------------------------')\n for _ in range(30):\n car_control(angle=-5, speed=50)\n print(\n '------------------------------------Correcting-------------------------------')\n turning_left = 0\n turn_left = 0\n turn_right = 0\n\n if turning_right > 0 and turning_right < turn_step_right:\n car_control(angle=90, speed=20)\n print(\n '------------------------------------Turn rightingg-------------------------------')\n turning_right += 1\n if turning_right == turn_step_right:\n for _ in range(5):\n car_control(angle=-90, speed=20)\n print(\n '------------------------------------Correcting-------------------------------')\n for _ in range(5):\n car_control(angle=0, speed=20)\n print(\n '------------------------------------Correcting-------------------------------')\n turning_right = 0\n turn_right = 0\n turn_left = 0\n else:\n if not draw_left and not draw_right:\n lost_lane += 1\n if lost_lane > lost_lane_thresh:\n if turn_left >= 2 or turn_right >= 5:\n lost_lane = 0\n for _ in range(1):\n car_control(angle=0, speed=0)\n if turn_left - turn_right >= -3:\n car_control(angle=-90, speed=20)\n turning_left += 1\n print(\n '------------------------------------Turn left-------------------------------')\n elif turn_right - turn_left >= 5:\n car_control(angle=90, speed=20)\n turning_right += 1\n print(\n '------------------------------------Turn right------------------------------')\n else:\n car_control(angle=angle, speed=35)\n else:\n if draw_left and not draw_right:\n car_control(angle=25, speed=25)\n elif draw_right and not draw_left:\n car_control(angle=-25, speed=25)\n else:\n car_control(angle=angle, speed=45)\n\n img[y_des-5:y_des+5, x_des-5:x_des+5] = (0, 0, 255)\n\n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n \"\"\"\n `img` should be the output of a Canny transform.\n Returns an image with hough lines drawn.\n \"\"\"\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array(\n []), minLineLength=min_line_len, maxLineGap=max_line_gap)\n # line_img = np.zeros(img.shape, dtype=np.uint8) # this produces single-channel (grayscale) image\n line_img = np.zeros((*img.shape, 3), dtype=np.uint8) # 3-channel RGB image\n draw_lines(line_img, lines)\n #draw_lines_debug2(line_img, lines)\n return line_img\n\n# Python 3 has support for cool math symbols.\n\n\ndef weighted_img(img, initial_img, α=0.8, β=1., λ=0.):\n \"\"\"\n `img` is the output of the hough_lines(), An image with lines drawn on it.\n Should be a blank image (all black) with lines drawn on it.\n `initial_img` should be the image before any processing.\n The result image is computed as follows:\n initial_img * α + img * β + λ\n NOTE: initial_img and img must be the same shape!\n \"\"\"\n return cv2.addWeighted(initial_img, α, img, β, λ)\n\n\ndef abs_sobel(gray_img, x_dir=True, kernel_size=3, thres=(0, 255)):\n \"\"\"\n Applies the sobel operator to a grayscale-like (i.e. single channel) image in either horizontal or vertical direction\n The function also computes the asbolute value of the resulting matrix and applies a binary threshold\n \"\"\"\n sobel = cv2.Sobel(gray_img, cv2.CV_64F, 1, 0, ksize=kernel_size) if x_dir else cv2.Sobel(\n gray_img, cv2.CV_64F, 0, 1, ksize=kernel_size)\n sobel_abs = np.absolute(sobel)\n sobel_scaled = np.uint8(255 * sobel / np.max(sobel_abs))\n\n gradient_mask = np.zeros_like(sobel_scaled)\n gradient_mask[(thres[0] <= sobel_scaled) & (sobel_scaled <= thres[1])] = 1\n return gradient_mask\n\n\ndef mag_sobel(gray_img, kernel_size=3, thres=(0, 255)):\n \"\"\"\n Computes sobel matrix in both x and y directions, merges them by computing the magnitude in both directions\n and applies a threshold value to only set pixels within the specified range\n \"\"\"\n sx = cv2.Sobel(gray_img, cv2.CV_64F, 1, 0, ksize=kernel_size)\n sy = cv2.Sobel(gray_img, cv2.CV_64F, 0, 1, ksize=kernel_size)\n\n sxy = np.sqrt(np.square(sx) + np.square(sy))\n scaled_sxy = np.uint8(255 * sxy / np.max(sxy))\n\n sxy_binary = np.zeros_like(scaled_sxy)\n sxy_binary[(scaled_sxy >= thres[0]) & (scaled_sxy <= thres[1])] = 1\n\n return sxy_binary\n\n\ndef combined_sobels(sx_binary, sy_binary, sxy_magnitude_binary, gray_img, kernel_size=3, angle_thres=(0, np.pi/2)):\n sxy_direction_binary = dir_sobel(\n gray_img, kernel_size=kernel_size, thres=angle_thres)\n\n combined = np.zeros_like(sxy_direction_binary)\n # Sobel X returned the best output so we keep all of its results. We perform a binary and on all the other sobels\n combined[(sx_binary == 1) | ((sy_binary == 1) & (\n sxy_magnitude_binary == 1) & (sxy_direction_binary == 1))] = 1\n\n return combined\n\n\ndef compute_hls_white_binary(rgb_img):\n \"\"\"\n Returns a binary thresholded image produced retaining only white and yellow elements on the picture\n The provided image should be in RGB format\n \"\"\"\n hls_img = to_hls(rgb_img)\n\n # Compute a binary thresholded image where white is isolated from HLS components\n img_hls_white_bin = np.zeros_like(hls_img[:, :, 0])\n img_hls_white_bin[((hls_img[:, :, 0] >= 0) & (hls_img[:, :, 0] <= 255))\n & ((hls_img[:, :, 1] >= 220) & (hls_img[:, :, 1] <= 255))\n & ((hls_img[:, :, 2] >= 0) & (hls_img[:, :, 2] <= 255))\n ] = 1\n\n return img_hls_white_bin\n\n\ndef get_combined_binary_thresholded_img(undist_img):\n \"\"\"\n Applies a combination of binary Sobel and color thresholding to an undistorted image\n Those binary images are then combined to produce the returned binary image\n \"\"\"\n undist_img_gray = to_lab(undist_img)[:, :, 0]\n sx = abs_sobel(undist_img_gray, kernel_size=15, thres=(20, 120))\n sy = abs_sobel(undist_img_gray, x_dir=False,\n kernel_size=15, thres=(20, 120))\n sxy = mag_sobel(undist_img_gray, kernel_size=15, thres=(80, 200))\n sxy_combined_dir = combined_sobels(\n sx, sy, sxy, undist_img_gray, kernel_size=15, angle_thres=(np.pi/4, np.pi/2))\n\n hls_w_y_thres = compute_hls_white_binary(undist_img)\n\n combined_binary = np.zeros_like(hls_w_y_thres)\n combined_binary[(sxy_combined_dir == 1) | (hls_w_y_thres == 1)] = 1\n\n return combined_binary\n\n\ndef dir_sobel(gray_img, kernel_size=3, thres=(0, np.pi/2)):\n \"\"\"\n Computes sobel matrix in both x and y directions, gets their absolute values to find the direction of the gradient\n and applies a threshold value to only set pixels within the specified range\n \"\"\"\n sx_abs = np.absolute(\n cv2.Sobel(gray_img, cv2.CV_64F, 1, 0, ksize=kernel_size))\n sy_abs = np.absolute(\n cv2.Sobel(gray_img, cv2.CV_64F, 0, 1, ksize=kernel_size))\n\n dir_sxy = np.arctan2(sx_abs, sy_abs)\n\n binary_output = np.zeros_like(dir_sxy)\n binary_output[(dir_sxy >= thres[0]) & (dir_sxy <= thres[1])] = 1\n\n return binary_output\n\n\n'''\nPARAM WORLD\n'''\n# Region-of-interest vertices\n# We want a trapezoid shape, with bottom edge at the bottom of the image\n# width of bottom edge of trapezoid, expressed as percentage of image width\ntrap_bottom_width = 1\ntrap_top_width = 1 # ditto for top edge of trapezoid\ntrap_height = 1 # height of the trapezoid expressed as percentage of image height\nsky_line = 75\n\n# Hough Transform\nrho = 2 # distance resolution in pixels of the Hough grid\ntheta = 1 * np.pi/180 # angular resolution in radians of the Hough grid\n# minimum number of votes (intersections in Hough grid cell)\nthreshold = 170\nmin_line_length = 5 # minimum number of pixels making up a line\nmax_line_gap = 15 # maximum gap in pixels between connectable line segments\n\n# Dillation\nkernel = np.ones((10, 10), np.uint8)\niterations = 1\n\nx_des = 320/2\ny_des = 160\ncar_pos_x = 120\ncar_pos_y = 300\nangle = 0\n\n# Turn param\nlost_lane = 0\nlost_lane_thresh = 2\nturn_left = 0\nturn_right = 0\nturning_left = 0\nturning_right = 0\nturn_step_left = 40\nturn_step_right = 20\n\n# Hardcode roadblock\nrock = 0\n\n# fourcc = cv2.VideoWriter_fourcc(*'XVID')\n# video_out_name = 'output_{}.avi'.format(time.time())\n# video_out = cv2.VideoWriter(video_out_name, fourcc, 20, (320, 240))\n\n'''\nPARAM WORLD\n'''\n\n\ndef car_control(angle=angle, speed=50):\n pub_speed = rospy.Publisher('/ithutech_speed', Float32, queue_size=10)\n pub_speed.publish(speed)\n # rate = rospy.Rate(100)\n pub_angle = rospy.Publisher('/ithutech_steerAngle', Float32, queue_size=10)\n # if angle>0:\n # angle += 3\n # if angle<0:\n # angle -= 3\n pub_angle.publish(angle)\n print('Angle:', angle, 'Speed:', speed)\n # rate = rospy.Rate(100)\n\n\ndef image_callback(data):\n global turn_left, turn_right, rock\n start_time = time.time()\n temp = np.fromstring(data.data, np.uint8)\n img = cv2.imdecode(temp, cv2.IMREAD_COLOR)\n frame = img\n\n # Lane detect\n frame = frame[sky_line:, :]\n frame = cv2.dilate(frame, kernel, iterations=iterations)\n combined = get_combined_binary_thresholded_img(\n cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) * 255\n line_image = hough_lines(combined, rho, theta,\n threshold, min_line_length, max_line_gap)\n test_img = cv2.cvtColor(combined, cv2.COLOR_GRAY2RGB)\n annotated_image = cv2.cvtColor(weighted_img(\n line_image, test_img), cv2.COLOR_RGB2BGR)\n cv2.imshow('ithutech_lane_detection', annotated_image)\n\n # Object detect\n detections = detect(image=img, thresh=0.25)\n if detections:\n for each_detection in detections:\n print('{}: {}%'.format(each_detection[0], each_detection[1]*100))\n if each_detection[0] == 'turn_left_sign':\n turn_left += 1\n if each_detection[0] == 'turn_right_sign':\n turn_right += 1\n x_center = each_detection[-1][0]\n y_center = each_detection[-1][1]\n width = each_detection[-1][2]\n height = each_detection[-1][3]\n x_top = int(x_center - width/2)\n y_top = int(y_center - height/2)\n x_bot = int(x_top + width)\n y_bot = int(y_top + height)\n if each_detection[0] == 'rock':\n rock = width * height\n print('Size: ', rock)\n cv2.rectangle(img, (x_top, y_top), (x_bot, y_bot), (0, 255, 0), 2)\n\n # video_out.write(annotated_image)\n cv2.imshow('ithutech_object_detector', img)\n cv2.waitKey(1)\n print('FPS:', 1/(time.time() - start_time))\n\n\ndef main():\n rospy.init_node('ithutech_node', anonymous=True)\n rospy.Subscriber(\"/ithutech_image/compressed\", CompressedImage,\n image_callback, queue_size=1, buff_size=2**24)\n rospy.spin()\n # video_out.release()\n # print('Saved', video_out_name)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5812747478485107, "alphanum_fraction": 0.5901538729667664, "avg_line_length": 29.417112350463867, "blob_id": "a7d6cf42292afbc331eff379c068cfe32ef2ca30", "content_id": "13799056a7d1c6b8796c6bc7a129a3075e05a424", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11375, "license_type": "no_license", "max_line_length": 132, "num_lines": 374, "path": "/detect_lane.py", "repo_name": "leemin-woo/driving-car", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport argparse\nimport os.path as ops\nimport glog as log\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom config import global_config\nfrom lanenet_model import lanenet\nfrom lanenet_model import lanenet_postprocess\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom sensor_msgs.msg import Image\nimport scipy.misc\nimport time\nimport random\nimport math\nfrom ctypes import *\nimport numpy as np\nimport cv2\nfrom std_msgs.msg import Float32\nimport rospkg\nimport rospy\nimport sys\nimport os\nfrom sensor_msgs.msg import CompressedImage\nfrom skimage import io, draw\n# import gi\n# gi.require_version('Gtk', '2.0')\ntry:\n os.chdir(os.path.dirname(__file__))\n os.system('clear')\n print(\"\\nWait for initial setup, please don't connect anything yet...\\n\")\n sys.path.remove('/opt/ros/melodic/lib/python2.7/dist-packages')\nexcept:\n pass\nCFG = global_config.cfg\n\nspeed = 20\nangle = 0\ncar_x = 160\nskyLine = 80\nsrcPath = '/home/luong/luong_ws/py_digitalrace_2019/src/ithutech/src/'\nweights_path = srcPath + 'model/tusimple_lanenet_vgg.ckpt'\nimage_path = '/home/luong/test.jpg'\nconfigPath = \"./model/yolov3-tiny_obj.cfg\"\nmetaPath = \"./model/obj.data\"\nweightPath = \"./model/yolov3-tiny_obj_332000.weights\"\nmodelPath = \"./model/darknet.so\"\naltNames = None\nif altNames is None:\n # In Python 3, the metafile default access craps out on Windows (but not Linux)\n # Read the names file and create a list to feed to detect\n try:\n with open(metaPath) as metaFH:\n metaContents = metaFH.read()\n import re\n match = re.search(\"names *= *(.*)$\", metaContents,\n re.IGNORECASE | re.MULTILINE)\n if match:\n result = match.group(1)\n else:\n result = None\n try:\n if os.path.exists(result):\n with open(result) as namesFH:\n namesList = namesFH.read().strip().split(\"\\n\")\n altNames = [x.strip() for x in namesList]\n except TypeError:\n pass\n except Exception:\n pass\n\n\ndef sample(probs):\n s = sum(probs)\n probs = [a/s for a in probs]\n r = random.uniform(0, 1)\n for i in range(len(probs)):\n r = r - probs[i]\n if r <= 0:\n return i\n return len(probs)-1\n\n\ndef c_array(ctype, values):\n arr = (ctype*len(values))()\n arr[:] = values\n return arr\n\n\nclass BOX(Structure):\n _fields_ = [(\"x\", c_float),\n (\"y\", c_float),\n (\"w\", c_float),\n (\"h\", c_float)]\n\n\nclass DETECTION(Structure):\n _fields_ = [(\"bbox\", BOX),\n (\"classes\", c_int),\n (\"prob\", POINTER(c_float)),\n (\"mask\", POINTER(c_float)),\n (\"objectness\", c_float),\n (\"sort_class\", c_int),\n (\"uc\", POINTER(c_float)),\n (\"points\", c_int)]\n\n\nclass IMAGE(Structure):\n _fields_ = [(\"w\", c_int),\n (\"h\", c_int),\n (\"c\", c_int),\n (\"data\", POINTER(c_float))]\n\n\nclass METADATA(Structure):\n _fields_ = [(\"classes\", c_int),\n (\"names\", POINTER(c_char_p))]\n\n\nrospack = rospkg.RosPack()\npath = rospack.get_path('ithutech')\nos.chdir(path)\n\nhasGPU = True\nlib = CDLL(modelPath, RTLD_GLOBAL)\nlib.network_width.argtypes = [c_void_p]\nlib.network_width.restype = c_int\nlib.network_height.argtypes = [c_void_p]\nlib.network_height.restype = c_int\n\ncopy_image_from_bytes = lib.copy_image_from_bytes\ncopy_image_from_bytes.argtypes = [IMAGE, c_char_p]\n\n\ndef network_width(net):\n return lib.network_width(net)\n\n\ndef network_height(net):\n return lib.network_height(net)\n\n\npredict = lib.network_predict_ptr\npredict.argtypes = [c_void_p, POINTER(c_float)]\npredict.restype = POINTER(c_float)\n\nif hasGPU:\n set_gpu = lib.cuda_set_device\n set_gpu.argtypes = [c_int]\n\ninit_cpu = lib.init_cpu\n\nmake_image = lib.make_image\nmake_image.argtypes = [c_int, c_int, c_int]\nmake_image.restype = IMAGE\n\nget_network_boxes = lib.get_network_boxes\nget_network_boxes.argtypes = [c_void_p, c_int, c_int, c_float, c_float, POINTER(\n c_int), c_int, POINTER(c_int), c_int]\nget_network_boxes.restype = POINTER(DETECTION)\n\nmake_network_boxes = lib.make_network_boxes\nmake_network_boxes.argtypes = [c_void_p]\nmake_network_boxes.restype = POINTER(DETECTION)\n\nfree_detections = lib.free_detections\nfree_detections.argtypes = [POINTER(DETECTION), c_int]\n\nfree_ptrs = lib.free_ptrs\nfree_ptrs.argtypes = [POINTER(c_void_p), c_int]\n\nnetwork_predict = lib.network_predict_ptr\nnetwork_predict.argtypes = [c_void_p, POINTER(c_float)]\n\nreset_rnn = lib.reset_rnn\nreset_rnn.argtypes = [c_void_p]\n\nload_net = lib.load_network\nload_net.argtypes = [c_char_p, c_char_p, c_int]\nload_net.restype = c_void_p\n\nload_net_custom = lib.load_network_custom\nload_net_custom.argtypes = [c_char_p, c_char_p, c_int, c_int]\nload_net_custom.restype = c_void_p\n\ndo_nms_obj = lib.do_nms_obj\ndo_nms_obj.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\ndo_nms_sort = lib.do_nms_sort\ndo_nms_sort.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\nfree_image = lib.free_image\nfree_image.argtypes = [IMAGE]\n\nletterbox_image = lib.letterbox_image\nletterbox_image.argtypes = [IMAGE, c_int, c_int]\nletterbox_image.restype = IMAGE\n\nload_meta = lib.get_metadata\nlib.get_metadata.argtypes = [c_char_p]\nlib.get_metadata.restype = METADATA\n\nload_image = lib.load_image_color\nload_image.argtypes = [c_char_p, c_int, c_int]\nload_image.restype = IMAGE\n\nrgbgr_image = lib.rgbgr_image\nrgbgr_image.argtypes = [IMAGE]\n\npredict_image = lib.network_predict_image\npredict_image.argtypes = [c_void_p, IMAGE]\npredict_image.restype = POINTER(c_float)\n\npredict_image_letterbox = lib.network_predict_image_letterbox\npredict_image_letterbox.argtypes = [c_void_p, IMAGE]\npredict_image_letterbox.restype = POINTER(c_float)\n\nnetMain = load_net_custom(configPath.encode(\n \"ascii\"), weightPath.encode(\"ascii\"), 0, 1)\nmetaMain = load_meta(metaPath.encode(\"ascii\"))\n\nwith open(metaPath) as metaFH:\n metaContents = metaFH.read()\n import re\n match = re.search(\"names *= *(.*)$\", metaContents,\n re.IGNORECASE | re.MULTILINE)\n if match:\n result = match.group(1)\n else:\n result = None\n try:\n if os.path.exists(result):\n with open(result) as namesFH:\n namesList = namesFH.read().strip().split(\"\\n\")\n altNames = [x.strip() for x in namesList]\n except TypeError:\n pass\n\n\ndef array_to_image(arr):\n # need to return old values to avoid python freeing memory\n arr = arr.transpose(2, 0, 1)\n c = arr.shape[0]\n h = arr.shape[1]\n w = arr.shape[2]\n arr = np.ascontiguousarray(arr.flat, dtype=np.float32) / 255.0\n data = arr.ctypes.data_as(POINTER(c_float))\n im = IMAGE(w, h, c, data)\n return im, arr\n\n\ndef classify(net, meta, im):\n out = predict_image(net, im)\n res = []\n for i in range(meta.classes):\n if altNames is None:\n nameTag = meta.names[i]\n else:\n nameTag = altNames[i]\n res.append((nameTag, out[i]))\n res = sorted(res, key=lambda x: -x[1])\n return res\n\n\ndef detect_image(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45, debug=False):\n custom_image_bgr = image # use: detect(,,imagePath,)\n custom_image = cv2.cvtColor(custom_image_bgr, cv2.COLOR_BGR2RGB)\n custom_image = cv2.resize(custom_image, (lib.network_width(\n net), lib.network_height(net)), interpolation=cv2.INTER_LINEAR)\n # import scipy.misc\n # custom_image = scipy.misc.imread(image)\n # you should comment line below: free_image(im)\n im, arr = array_to_image(custom_image)\n\n num = c_int(0)\n if debug:\n print(\"Assigned num\")\n pnum = pointer(num)\n if debug:\n print(\"Assigned pnum\")\n predict_image(net, im)\n letter_box = 0\n if debug:\n print(\"did prediction\")\n dets = get_network_boxes(\n net, custom_image_bgr.shape[1], custom_image_bgr.shape[0], thresh, hier_thresh, None, 0, pnum, letter_box) # OpenCV\n\n # dets = get_network_boxes(net, im.w, im.h, thresh,\n # hier_thresh, None, 0, pnum, letter_box)\n if debug:\n print(\"Got dets\")\n num = pnum[0]\n if debug:\n print(\"got zeroth index of pnum\")\n if nms:\n do_nms_sort(dets, num, meta.classes, nms)\n if debug:\n print(\"did sort\")\n res = []\n if debug:\n print(\"about to range\")\n for j in range(num):\n if debug:\n print(\"Ranging on \"+str(j)+\" of \"+str(num))\n if debug:\n print(\"Classes: \"+str(meta), meta.classes, meta.names)\n for i in range(meta.classes):\n if debug:\n print(\"Class-ranging on \"+str(i)+\" of \" +\n str(meta.classes)+\"= \"+str(dets[j].prob[i]))\n if dets[j].prob[i] > 0:\n b = dets[j].bbox\n if altNames is None:\n nameTag = meta.names[i]\n else:\n nameTag = altNames[i]\n if debug:\n print(\"Got bbox\", b)\n print(nameTag)\n print(dets[j].prob[i])\n print((b.x, b.y, b.w, b.h))\n res.append((nameTag, dets[j].prob[i], (b.x, b.y, b.w, b.h)))\n if debug:\n print(\"did range\")\n res = sorted(res, key=lambda x: -x[1])\n if debug:\n print(\"did sort\")\n free_detections(dets, num)\n if debug:\n print(\"freed detections\")\n return res\n\n\ndef performDetect(image,\n thresh=0.25,\n configPath=configPath,\n weightPath=weightPath,\n metaPath=metaPath,\n showImage=True):\n # Import the global variables. This lets us instance Darknet once, then just call performDetect() again without instancing again\n global metaMain, netMain, altNames # pylint: disable=W0603\n assert 0 < thresh < 1, \"Threshold should be a float between zero and one (non-inclusive)\"\n import cv2\n # if is used cv2.imread(image)\n detections = detect_image(netMain, metaMain, image, thresh)\n # detections = detect(netMain, metaMain, imagePath.encode(\"ascii\"), thresh)\n if showImage:\n try:\n imcaption = []\n for detection in detections:\n img = image\n x_center = detection[-1][0]\n y_center = detection[-1][1]\n width = detection[-1][2]\n height = detection[-1][3]\n x_top = int(x_center - width/2)\n y_top = int(y_center - height/2)\n x_bot = int(x_top + width)\n y_bot = int(y_top + height)\n cv2.rectangle(img, (x_top, y_top),\n (x_bot, y_bot), (0, 255, 0), 2)\n label = detection[0]\n confidence = detection[1]\n pstring = label+\": \"+str(np.rint(100 * confidence))+\"%\"\n imcaption.append(pstring)\n print(pstring)\n # detections = {\n # \"detections\": detections,\n # \"image\": image,\n # \"caption\": \"\\n<br/>\".join(imcaption)\n # }\n except Exception as e:\n print(\"Unable to show image: \"+str(e))\n return detections" }, { "alpha_fraction": 0.5421872138977051, "alphanum_fraction": 0.5621387362480164, "avg_line_length": 30.686853408813477, "blob_id": "06a3f3242a6094f8d3b1dc3a09eaece09299012c", "content_id": "6968cab34afe3563dfd621c15a9b5c2c9aa0e166", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21452, "license_type": "no_license", "max_line_length": 132, "num_lines": 677, "path": "/main.py", "repo_name": "leemin-woo/driving-car", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport argparse\nimport os.path as ops\nimport glog as log\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom config import global_config\nfrom lanenet_model import lanenet\nfrom lanenet_model import lanenet_postprocess\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom sensor_msgs.msg import Image\nimport scipy.misc\nimport time\nimport random\nimport math\nfrom ctypes import *\nimport numpy as np\nimport cv2\nfrom std_msgs.msg import Float32\nimport rospkg\nimport rospy\nimport sys\nimport os\nfrom sensor_msgs.msg import CompressedImage\nfrom skimage import io, draw\nimport threading\nimport time\n# import gi\n# gi.require_version('Gtk', '2.0')\ntry:\n os.chdir(os.path.dirname(__file__))\n os.system('clear')\n print(\"\\nWait for initial setup, please don't connect anything yet...\\n\")\n sys.path.remove('/opt/ros/melodic/lib/python2.7/dist-packages')\nexcept:\n pass\nCFG = global_config.cfg\n\nturn_right = turn_left = False\nlane_detect = True\nframe = 0\nimage_0 = None\nimage_object = None\nspeed = 50\nangle = 0\ncar_x = 160\nskyLine = 80\nwait_to_turn = False\nt_start = None\nhave_data = False\ndetect_object_alive = False\ndetect_lane_alive = False\navoid_object = False\nbr = False\n\n\nsrcPath = '/home/ntl/Downloads/py_digitalrace_2019-master/src/chickenteam/src/'\nweights_path = srcPath + 'model/tusimple_lanenet_vgg.ckpt'\nimage_path = '/home/ntl/test.jpg'\nconfigPath = \"./model/yolov3-tiny_obj.cfg\"\nmetaPath = \"./model/obj.data\"\nweightPath = \"./model/yolov3-tiny_obj_332000.weights\"\nmodelPath = \"./model/darknet.so\"\naltNames = None\nif altNames is None:\n # In Python 3, the metafile default access craps out on Windows (but not Linux)\n # Read the names file and create a list to feed to detect\n try:\n with open(metaPath) as metaFH:\n metaContents = metaFH.read()\n import re\n match = re.search(\"names *= *(.*)$\", metaContents,\n re.IGNORECASE | re.MULTILINE)\n if match:\n result = match.group(1)\n else:\n result = None\n try:\n if os.path.exists(result):\n with open(result) as namesFH:\n namesList = namesFH.read().strip().split(\"\\n\")\n altNames = [x.strip() for x in namesList]\n except TypeError:\n pass\n except Exception:\n pass\n\n\ndef sample(probs):\n s = sum(probs)\n probs = [a/s for a in probs]\n r = random.uniform(0, 1)\n for i in range(len(probs)):\n r = r - probs[i]\n if r <= 0:\n return i\n return len(probs)-1\n\n\ndef c_array(ctype, values):\n arr = (ctype*len(values))()\n arr[:] = values\n return arr\n\n\nclass BOX(Structure):\n _fields_ = [(\"x\", c_float),\n (\"y\", c_float),\n (\"w\", c_float),\n (\"h\", c_float)]\n\n\nclass DETECTION(Structure):\n _fields_ = [(\"bbox\", BOX),\n (\"classes\", c_int),\n (\"prob\", POINTER(c_float)),\n (\"mask\", POINTER(c_float)),\n (\"objectness\", c_float),\n (\"sort_class\", c_int),\n (\"uc\", POINTER(c_float)),\n (\"points\", c_int)]\n\n\nclass IMAGE(Structure):\n _fields_ = [(\"w\", c_int),\n (\"h\", c_int),\n (\"c\", c_int),\n (\"data\", POINTER(c_float))]\n\n\nclass METADATA(Structure):\n _fields_ = [(\"classes\", c_int),\n (\"names\", POINTER(c_char_p))]\n\n\nrospack = rospkg.RosPack()\npath = rospack.get_path('ithutech')\nos.chdir(path)\n\nhasGPU = True\nlib = CDLL(modelPath, RTLD_GLOBAL)\nlib.network_width.argtypes = [c_void_p]\nlib.network_width.restype = c_int\nlib.network_height.argtypes = [c_void_p]\nlib.network_height.restype = c_int\n\ncopy_image_from_bytes = lib.copy_image_from_bytes\ncopy_image_from_bytes.argtypes = [IMAGE, c_char_p]\n\n\ndef network_width(net):\n return lib.network_width(net)\n\n\ndef network_height(net):\n return lib.network_height(net)\n\n\npredict = lib.network_predict_ptr\npredict.argtypes = [c_void_p, POINTER(c_float)]\npredict.restype = POINTER(c_float)\n\nif hasGPU:\n set_gpu = lib.cuda_set_device\n set_gpu.argtypes = [c_int]\n\ninit_cpu = lib.init_cpu\n\nmake_image = lib.make_image\nmake_image.argtypes = [c_int, c_int, c_int]\nmake_image.restype = IMAGE\n\nget_network_boxes = lib.get_network_boxes\nget_network_boxes.argtypes = [c_void_p, c_int, c_int, c_float, c_float, POINTER(\n c_int), c_int, POINTER(c_int), c_int]\nget_network_boxes.restype = POINTER(DETECTION)\n\nmake_network_boxes = lib.make_network_boxes\nmake_network_boxes.argtypes = [c_void_p]\nmake_network_boxes.restype = POINTER(DETECTION)\n\nfree_detections = lib.free_detections\nfree_detections.argtypes = [POINTER(DETECTION), c_int]\n\nfree_ptrs = lib.free_ptrs\nfree_ptrs.argtypes = [POINTER(c_void_p), c_int]\n\nnetwork_predict = lib.network_predict_ptr\nnetwork_predict.argtypes = [c_void_p, POINTER(c_float)]\n\nreset_rnn = lib.reset_rnn\nreset_rnn.argtypes = [c_void_p]\n\nload_net = lib.load_network\nload_net.argtypes = [c_char_p, c_char_p, c_int]\nload_net.restype = c_void_p\n\nload_net_custom = lib.load_network_custom\nload_net_custom.argtypes = [c_char_p, c_char_p, c_int, c_int]\nload_net_custom.restype = c_void_p\n\ndo_nms_obj = lib.do_nms_obj\ndo_nms_obj.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\ndo_nms_sort = lib.do_nms_sort\ndo_nms_sort.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\nfree_image = lib.free_image\nfree_image.argtypes = [IMAGE]\n\nletterbox_image = lib.letterbox_image\nletterbox_image.argtypes = [IMAGE, c_int, c_int]\nletterbox_image.restype = IMAGE\n\nload_meta = lib.get_metadata\nlib.get_metadata.argtypes = [c_char_p]\nlib.get_metadata.restype = METADATA\n\nload_image = lib.load_image_color\nload_image.argtypes = [c_char_p, c_int, c_int]\nload_image.restype = IMAGE\n\nrgbgr_image = lib.rgbgr_image\nrgbgr_image.argtypes = [IMAGE]\n\npredict_image = lib.network_predict_image\npredict_image.argtypes = [c_void_p, IMAGE]\npredict_image.restype = POINTER(c_float)\n\npredict_image_letterbox = lib.network_predict_image_letterbox\npredict_image_letterbox.argtypes = [c_void_p, IMAGE]\npredict_image_letterbox.restype = POINTER(c_float)\n\nnetMain = load_net_custom(configPath.encode(\n \"ascii\"), weightPath.encode(\"ascii\"), 0, 1)\nmetaMain = load_meta(metaPath.encode(\"ascii\"))\n\nwith open(metaPath) as metaFH:\n metaContents = metaFH.read()\n import re\n match = re.search(\"names *= *(.*)$\", metaContents,\n re.IGNORECASE | re.MULTILINE)\n if match:\n result = match.group(1)\n else:\n result = None\n try:\n if os.path.exists(result):\n with open(result) as namesFH:\n namesList = namesFH.read().strip().split(\"\\n\")\n altNames = [x.strip() for x in namesList]\n except TypeError:\n pass\n\n\ndef array_to_image(arr):\n # need to return old values to avoid python freeing memory\n arr = arr.transpose(2, 0, 1)\n c = arr.shape[0]\n h = arr.shape[1]\n w = arr.shape[2]\n arr = np.ascontiguousarray(arr.flat, dtype=np.float32) / 255.0\n data = arr.ctypes.data_as(POINTER(c_float))\n im = IMAGE(w, h, c, data)\n return im, arr\n\n\ndef classify(net, meta, im):\n out = predict_image(net, im)\n res = []\n for i in range(meta.classes):\n if altNames is None:\n nameTag = meta.names[i]\n else:\n nameTag = altNames[i]\n res.append((nameTag, out[i]))\n res = sorted(res, key=lambda x: -x[1])\n return res\n\n\ndef detect_image(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45, debug=False):\n custom_image_bgr = image # use: detect(,,imagePath,)\n custom_image = cv2.cvtColor(custom_image_bgr, cv2.COLOR_BGR2RGB)\n custom_image = cv2.resize(custom_image, (lib.network_width(\n net), lib.network_height(net)), interpolation=cv2.INTER_LINEAR)\n # import scipy.misc\n # custom_image = scipy.misc.imread(image)\n # you should comment line below: free_image(im)\n im, arr = array_to_image(custom_image)\n\n num = c_int(0)\n if debug:\n print(\"Assigned num\")\n pnum = pointer(num)\n if debug:\n print(\"Assigned pnum\")\n predict_image(net, im)\n letter_box = 0\n if debug:\n print(\"did prediction\")\n dets = get_network_boxes(\n net, custom_image_bgr.shape[1], custom_image_bgr.shape[0], thresh, hier_thresh, None, 0, pnum, letter_box) # OpenCV\n\n # dets = get_network_boxes(net, im.w, im.h, thresh,\n # hier_thresh, None, 0, pnum, letter_box)\n if debug:\n print(\"Got dets\")\n num = pnum[0]\n if debug:\n print(\"got zeroth index of pnum\")\n if nms:\n do_nms_sort(dets, num, meta.classes, nms)\n if debug:\n print(\"did sort\")\n res = []\n if debug:\n print(\"about to range\")\n for j in range(num):\n if debug:\n print(\"Ranging on \"+str(j)+\" of \"+str(num))\n if debug:\n print(\"Classes: \"+str(meta), meta.classes, meta.names)\n for i in range(meta.classes):\n if debug:\n print(\"Class-ranging on \"+str(i)+\" of \" +\n str(meta.classes)+\"= \"+str(dets[j].prob[i]))\n if dets[j].prob[i] > 0:\n b = dets[j].bbox\n if altNames is None:\n nameTag = meta.names[i]\n else:\n nameTag = altNames[i]\n if debug:\n print(\"Got bbox\", b)\n print(nameTag)\n print(dets[j].prob[i])\n print((b.x, b.y, b.w, b.h))\n res.append((nameTag, dets[j].prob[i], (b.x, b.y, b.w, b.h)))\n if debug:\n print(\"did range\")\n res = sorted(res, key=lambda x: -x[1])\n if debug:\n print(\"did sort\")\n free_detections(dets, num)\n if debug:\n print(\"freed detections\")\n return res\n\n\n\ndef performDetect(thresh=0.25,\n configPath=configPath,\n weightPath=weightPath,\n metaPath=metaPath,\n showImage=True):\n # Import the global variables. This lets us instance Darknet once, then just call performDetect() again without instancing again\n assert 0 < thresh < 1, \"Threshold should be a float between zero and one (non-inclusive)\"\n # if is used cv2.imread(image)\n detect_object_alive = True\n # print('detect_object_alive is', detect_object_alive )\n detections = detect_image(netMain, metaMain, image_0, thresh)\n # detections = detect(netMain, metaMain, imagePath.encode(\"ascii\"), thresh)\n if showImage:\n try:\n imcaption = []\n for detection in detections:\n img = image_0\n if detection[0] == 'turn_left_traffic':\n turn_left = True\n elif detection[0] == 'turn_right_traffic':\n turn_right = True\n x_center = detection[-1][0]\n y_center = detection[-1][1]\n width = detection[-1][2]\n height = detection[-1][3]\n x_top = int(x_center - width/2)\n y_top = int(y_center - height/2)\n x_bot = int(x_top + width)\n y_bot = int(y_top + height)\n cv2.rectangle(img, (x_top, y_top),\n (x_bot, y_bot), (255, 255, 255), 2)\n label = detection[0]\n confidence = detection[1]\n pstring = label+\": \"+str(np.rint(100 * confidence))+\"%\"\n imcaption.append(pstring)\n print(pstring)\n cv2.imshow('object', img)\n except Exception as e:\n print(\"Unable to show image: \"+str(e))\n cv2.waitKey(1) \n detect_object_alive = False\n\n\n\n\"\"\"\n:param image_path:\n:param weights_path:\n:return:\n\"\"\"\ninput_tensor = tf.placeholder(dtype=tf.float32, shape=[\n 1, 256, 512, 3], name='input_tensor')\n\nnet = lanenet.LaneNet(phase='test', net_flag='vgg')\nbinary_seg_ret, instance_seg_ret = net.inference(\n input_tensor=input_tensor, name='lanenet_model')\nsaver = tf.train.Saver()\n# Set sess configuration\nsess_config = tf.ConfigProto()\nsess_config.gpu_options.per_process_gpu_memory_fraction = CFG.TEST.GPU_MEMORY_FRACTION\nsess_config.gpu_options.allow_growth = CFG.TRAIN.TF_ALLOW_GROWTH\nsess_config.gpu_options.allocator_type = 'BFC'\nsess = tf.Session(config=sess_config)\nsaver.restore(sess=sess, save_path=weights_path)\n\ndef inference_net():\n global detect_lane_alive,image_0\n detect_lane_alive = True\n # preprocess\n image = image_0\n crop_img = image[skyLine:, 0:]\n h = crop_img.shape[0] # 240\n w = crop_img.shape[1] # 320\n\n # resize for lanenet image required\n image = cv2.resize(crop_img, (512, 256), interpolation=cv2.INTER_LINEAR)\n image = image / 127.5 - 1.0\n\n # get image with lane\n binary_seg_image, instance_seg_image = sess.run(\n [binary_seg_ret, instance_seg_ret],\n feed_dict={input_tensor: [image]}\n )\n # reed image\n embedding_image = np.array(instance_seg_image[0], np.uint8)\n # resize to crop image size\n embedding_image = cv2.resize(\n embedding_image, (w, h), interpolation=cv2.INTER_LINEAR)\n # embedding_image = cv2.resize(embedding_image, (512, 256), interpolation=cv2.INTER_LINEAR)\n\n # make equal with src image\n top = skyLine\n bottom = left = right = 0\n embedding_image = cv2.copyMakeBorder(\n embedding_image, top, bottom, left, right, cv2.BORDER_CONSTANT)\n # print(embedding_image.shape)\n # draw lines\n h = embedding_image.shape[0]\n w = embedding_image.shape[1]\n left_lane = []\n right_lane = []\n\n # get line coordinates\n\n max_y = 120\n dx = car_x\n zero_image = np.zeros((h, w, 3))\n lanes = []\n for y in range(100, 240, 1):\n x = 5\n lane_number = 0\n while x < 315:\n if(embedding_image[y, x].any() > 0):\n # zero_image[y][x] = [0, 255, 0]\n # print('lane point begin', lane_number)\n # find new lane\n if len(lanes) <= lane_number + 1:\n lanes.append([])\n # print('create new lane:', lane_number,\n # 'with coordinates:', 'x:', x, '- y:', y)\n if len(lanes[lane_number]) == 0:\n lanes[lane_number].append([x, y])\n # print('find lane:', lane_number,\n # 'with coordinates:', x, y,\n # '\\nlanes append:', lanes[lane_number][0])\n lane_number += 1\n # when x in the old lane\n elif abs(x - lanes[lane_number][-1][0]) < 10:\n if y - lanes[lane_number][-1][1] < 10:\n # print(abs(x - lanes[lane_number][-1][0]))\n lanes[lane_number].append([x, y])\n # print('find lane:', lane_number,\n # 'with coordinates:', x, y)\n lane_number += 1\n #x in the next lane\n elif abs(x - lanes[lane_number][-1][0]) > 50:\n lane_number += 1\n # print('x in the next lane:', lane_number,\n # 'with coordinates:', x, y)\n lanes[lane_number].append([x, y])\n lane_number += 1\n # print('lane point end', lane_number)\n # # print image found\n # print('end loop')\n zero_image[y][x] = [255, 0, 0]\n\n x += 40\n else:\n x += 1\n # y_left_end = y_right_end = 80\n # x_left_end = 0\n # x_right_end = 320\n\n y_left_top= y_right_top= 180\n x_left_top= 0\n x_right_top= 320\n for lane in lanes:\n if len(lane) > 20:\n # print(lane[-1])\n # find coord end\n # if lane[-1][0] < car_x - 30 and y_left_end < lane[-1][1]:\n # y_left_end = lane[-1][1]\n # x_left_end = lane[-1][0]\n # elif lane[-1][0] > car_x + 30 and y_right_end < lane[-1][1]:\n # y_right_end = lane[-1][1]\n # x_right_end = lane[-1][0]\n # print(lane[0])\n # find coord top\n if lane[-1][0] < car_x - 30 and y_left_top > lane[0][1]:\n y_left_top= lane[0][1]\n x_left_top= lane[0][0]\n elif lane[-1][0] > car_x + 30 and y_right_top> lane[0][1]:\n y_right_top= lane[0][1]\n x_right_top= lane[0][0]\n print(len(lanes))\n # print('find end', 'left', x_left_end, y_left_end,\n # 'right', y_right_end, x_right_end)\n # print('find top', 'left', y_left_top, x_left_top,\n # 'right', y_right_top, x_right_top)\n # In case of error, don't draw the line\n\n # if draw_left:\n # cv2.line(zero_image, (x_left_top,y_left_top),\n # (x_left_end, y_left_end), [0, 0, 255], 5)\n # if draw_right:\n # cv2.line(zero_image, (x_right_top, y_right_top),\n # (x_right_end, y_right_end), [255, 0, 0], 5)\n dx = int((x_left_top + x_right_top)/2)\n drive_follow_lane(dx)\n # cv2.imwrite(\n # '/home/luong/luong_ws/py_digitalrace_2019/src/ithutech/test.jpg', zero_image)\n cv2.imshow('test', zero_image)\n cv2.imshow('test2',embedding_image)\n cv2.waitKey(1)\n detect_lane_alive = False\n\n\n\n\n# def get_lane_begin_end(lanes):\n# global y_left_end,y_right_end,x_left_end,x_right_end,y_left_top,y_right_top,x_left_top,x_right_top\n# for lane in lanes:\n# if len(lane) < 10:\n# lanes.pop(lanes.index(lane))\n# # print(lane[-1])\n# # find coord end\n# if lane[-1][0] < car_x - 30 and y_left_end < lane[-1][1]:\n# y_left_end = lane[-1][1]\n# x_left_end = lane[-1][0]\n# elif lane[-1][0] > car_x + 30 and y_right_end < lane[-1][1]:\n# y_right_end = lane[-1][1]\n# x_right_end = lane[-1][0]\n# # print(lane[0])\n# # find coord top\n# if lane[0][0] < car_x - 30 and y_left_top> lane[0][1]:\n# y_left_top= lane[0][1]\n# x_left_top= lane[0][0]\n# elif lane[0][0] > car_x + 30 and y_right_top> lane[0][1]:\n# y_right_top= lane[0][1]\n# x_right_top= lane[0][0]\n\n # zero_image[y_left_end][x_left_end] = [0, 255, 0]\n # zero_image[y_right_end][x_right_end] = [0, 255, 0]\n # zero_image[y_left_top][x_left_top] = [0, 0, 255]\n # zero_image[y_right_top][x_right_top] = [0, 0, 255]\n # zero_image = np.zeros((240, 320, 3))\n\n\n\n\n# def draw_lines(img, color=[0, 0, 255], thickness=5):\n# global angle\n\n # # In case of error, don't draw the line\n # draw_right = True\n # draw_left = True\n\n # if draw_left:\n # cv2.line(img, (x_left_top,y_left_top),\n # (x_left_end, y_left_end), color, thickness)\n # if draw_right:\n # cv2.line(img, (x_right_top, y_right_top),\n # (x_right_end, y_right_end), color, thickness)\n # if draw_left and draw_right:\n # x_des = int((x_left_end + x_right_end)/2)\n # # y_des = int((y_left_end + y_right_end)/2)\n # drive_follow_lane(x_des)\n # dx = x_des - car_x\n # dy = car_x - y_des\n # if dx < 0:\n # angle = -np.arctan(-dx/dy) * 180/math.pi\n # elif dx == 0:\n # angle = 0\n # else:\n # angle = np.arctan(dx/dy) * 180/math.pi\n # print('angle is:', angle)\n\n\ndef drive_follow_lane(dx):\n global speed, angle\n l = dx - 10\n r = dx + 10\n if(car_x < l):\n # print(\"Drive to the right\")\n if angle < 0:\n angle = 0\n angle += 1\n elif(car_x > r):\n # print(\"Drive to the left\")\n if angle > 0:\n angle = 0\n angle -= 1\n else:\n angle = 0\n # print(\"go ahead\")\n # print(dx, car_x)\n # print('Angle:', angle)\n\ndef car_control(angle, speed):\n pub_speed = rospy.Publisher(\n '/bridge05/ithutech/set_speed', Float32, queue_size=10)\n pub_angle = rospy.Publisher(\n '/bridge05/ithutech/set_angle', Float32, queue_size=10)\n pub_speed.publish(speed)\n pub_angle.publish(angle)\n # print('Angle:', angle, 'Speed:', speed)\n\n\ndef image_callback(data):\n global frame, image_0, image_object, have_data, \\\n detect_object_alive, detect_lane_alive\n car_control(angle, speed)\n temp = np.fromstring(data.data, np.uint8)\n image_0 = cv2.imdecode(temp, cv2.IMREAD_COLOR)\n frame += 1\n if frame > 5:\n print('found data, check: ', detect_object_alive, detect_lane_alive)\n if not detect_object_alive:\n print('detect object')\n threading.Thread(target=performDetect())\n else:\n print('detect_object is running')\n frame = 0\n if not detect_lane_alive:\n print('detect lane')\n threading.Thread(target=inference_net())\n else:\n print('lane thread is running')\n \n cv2.imshow('object', image_0)\n # cv2.imshow('detect_objetct',img)\n\n\navoid_object = False\nbr = False\n\n\ndef main():\n rospy.init_node('ithutech_node', anonymous=True)\n # rospy.Subscriber(\"/ithutech_image/compressed\", CompressedImage,\n # image_callback, queue_size=1, buff_size=2**24)\n rospy.Subscriber(\"/bridge05/ithutech/camera/rgb/compressed\", CompressedImage,\n image_callback, queue_size=1, buff_size=2**24)\n rospy.spin()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4885476231575012, "alphanum_fraction": 0.5650702714920044, "avg_line_length": 27.67910385131836, "blob_id": "98507e6b4777769ce1c2708939fcec5d757cb49b", "content_id": "70d801b02d4aa4ba779664833bff3bc64a5ad56f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3842, "license_type": "no_license", "max_line_length": 109, "num_lines": 134, "path": "/crop.py", "repo_name": "leemin-woo/driving-car", "src_encoding": "UTF-8", "text": "# import the necessary packages\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# load the image and show it\n# img = cv2.imread(\"/home/luong/luong_ws/py_digitalrace_2019/src/ithutech/src/020219_0.000000_67.000000.jpg\")\n# cv2.imshow(\"original\", image)\n# cv2.waitKey(0)\n# img = cv2.imread(\"/home/luong/luong_ws/py_digitalrace_2019/src/ithutech/src/020219_0.000000_67.000000.jpg\")\n# skyLine = 90\n# crop_img = img[skyLine:, 0:]\n# top=0\n# bottom=0\n# left=60\n# right=60\n# image = cv2.copyMakeBorder( img, top, bottom, left, right, cv2.BORDER_CONSTANT)\n\n\nclass coordinate:\n def __init__(self, x, y):\n self.x = x\n# self.y = y\n\n\n# image = cv2.imread(\n# '/home/luong/luong_ws/py_digitalrace_2019/src/ithutech/test.jpg', 1)\n# print(image.shape)\n# h = image.shape[0]\n# w = image.shape[1]\n# left_lane = []\n# right_lane = []\n# zero_image_left_lane = np.zeros((240, 320, 3))\n# zero_image_right_lane = np.zeros((240, 320, 3))\n# y = 100\n# while(y < 140):\n# y += 1\n# for x in range(w):\n# lane_coord = coordinate(x,y)\n# if(image[y, x, 2] > 0):\n# zero_image_left_lane[y, x] = [0, 255, 0]\n# left_lane.append(lane_coord)\n# elif(image[y, x, 1] > 0):\n# zero_image_right_lane[y, x] = [255, 0, 0]\n# right_lane.append(lane_coord)\n\n\n# zero_image = np.zeros((240, 320, 3))\n# lane_follow = []\n# # for y in range(100,120,1):\n# for l in left_lane:\n# if(100 < l.y < 120 and l.x > 70):\n# for r in right_lane:\n# if(r.y == l.y and r.y < 250):\n# lf = coordinate(int((l.x+r.x)/2), r.y)\n# lane_follow.append(lf)\n# zero_image[lf.y, lf.x] = [255, 255, 255]\n# zero_image[r.y, r.x] = [255, 0, 0]\n# zero_image[l.y, l.x] = [0, 255, 0]\n\n\n# cv2.imshow('image', zero_image)\n# cv2.imshow('image2', image)\n\n# cv2.imshow('left', zero_image_left_lane)\n# cv2.imshow('right',zero_image_right_lane)\n# cv2.waitKey()\n# print(x)\n# return mask_image\n# for i in range(256):\n# for j in range(512):\n# y = []\n# if(embedding_image[i, j, 0] > 0 or embedding_image[i, j, 1] > 0 or embedding_image[i, j, 2] > 0):\n# image_vis[i][j] = [255, 0, 255]\n# # print(i,j)\n# y.append(i)\n# y.append(j)\n# x.append(y)\n\n# lanes = []\n# for i in range(5):\n# lane_number = 0\n# x = 0\n# while x < 10:\n# if len(lanes) < lane_number + 1:\n# lanes.append([])\n# lanes[lane_number].append([1, 2])\n# print(lane_number, lanes[0])\n# lane_number += 1\n# x += 1\n# elif lane_number == 4:\n# print('haha')\n# else:\n# x += 1\n# # lanes[lane_number].append([1,2])\n# # lane_number +=1\n# img = cv2.imread('/home/luong/luong_ws/py_digitalrace_2019/src/ithutech/test.jpg')\n# rows,cols,ch = img.shape\n\n# pts1 = np.float32([[0,40],[320,40],[0,400],[320,400]])\n# pts2 = np.float32([[0,0],[320,0],[100,400],[200,400]])\n\n# M = cv2.getPerspectiveTransform(pts1,pts2)\n\n# dst = cv2.warpPerspective(img,M,(300,300))\n\n# plt.subplot(121),plt.imshow(img),plt.title('Input')\n# plt.subplot(122),plt.imshow(dst),plt.title('Output')\n# plt.show()\n\nzero = np.zeros((250,250,3))\n \n# Window name in which image is displayed \nwindow_name = 'Image'\n \n# Start coordinate, here (0, 0) \n# represents the top left corner of image \nstart_point = (0, 0) \n \n# End coordinate, here (250, 250) \n# represents the bottom right corner of image \nend_point = (100, 250) \n \n# Green color in BGR \ncolor = (0, 255, 0) \n \n# Line thickness of 9 px \nthickness = 9\n \n# Using cv2.line() method \n# Draw a diagonal green line with thickness of 9 px \nimage = cv2.line(zero, start_point, end_point, color, thickness)\ncv2.imshow(window_name,zero)\ncv2.waitKey()" }, { "alpha_fraction": 0.4661017060279846, "alphanum_fraction": 0.4825211763381958, "avg_line_length": 20.953489303588867, "blob_id": "586ff9fa792644bb78cc0804b615067f86808131", "content_id": "be8c7ba1796d3e9cfbdb4f685414eb5d5ba7e2c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1888, "license_type": "no_license", "max_line_length": 45, "num_lines": 86, "path": "/car_conntrol_demo.py", "repo_name": "leemin-woo/driving-car", "src_encoding": "UTF-8", "text": "from ctypes import *\nfrom math import *\n\ncarPos = POS(120, 300)\nturn_left = False\nturn_right = False\ngo_ahead = False\nangle = 0\nspeed = 0\nobject_detected = 0\n\n\nclass POS:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\nclass BOX(Structure):\n _fields_ = [(\"x\", c_float),\n (\"y\", c_float),\n (\"w\", c_float),\n (\"h\", c_float)]\n\n\nclass DETECTION(Structure):\n _fields_ = [(\"bbox\", BOX),\n (\"classes\", c_int),\n (\"prob\", POINTER(c_float)),\n (\"mask\", POINTER(c_float)),\n (\"objectness\", c_float),\n (\"sort_class\", c_int),\n (\"uc\", POINTER(c_float)),\n (\"points\", c_int)]\n\n\ndef get_lane(img):\n lx = 1\n ly = 2\n rx = 1\n ry = 2\n left_lane_pos = POS(lx, ly)\n right_lane_pos = POS(rx, ry)\n left_lane = []\n right_lane = []\n left_lane.append(left_lane)\n right_lane.append(right_lane_pos)\n return left_lane, right_lane\n\n\ndef detect_object(img):\n global object_detected\n detections = []\n object_pos = POS(1, 2)\n for detection in detections:\n if(object_pos.y >= 100):\n if(object_pos.x > carPos.x):\n object_detected = 1\n else:\n object_detected = -1\n return detection\n object_detected = 0\n\n\ndef drive_car(img):\n global angle\n left_lane, right_lane = get_lane(img)\n\n dy = carPos.y\n for i in left_lane:\n for j in right_lane:\n if(i.y == j.y):\n xmax = (i.x + j.x)/2 + 20\n xmin = (i.x + j.x)/2 - 20\n if(object_detected == 0):\n if(carPos.x > xmax):\n angle -= 1\n elif(carPos.x < xmin):\n angle += 1\n else:\n angle = 0\n\n\n# run(image):\n# left_lane, right_lane = get_lane(image)\n# go_ahead(left_lane,right_lane)\n" } ]
5
mtnesbitt/BlockedTrafficVisualization
https://github.com/mtnesbitt/BlockedTrafficVisualization
f921974ddc5fd4354f39f33616f3709e12266611
1630a1df10a9df694ceb4c21f635065fdb1cbbc1
8f76ad95c42f50a93310a873ebbc44391109c6c8
refs/heads/master
2021-01-25T04:27:24.360503
2017-08-03T14:41:55
2017-08-03T14:41:55
93,443,587
0
0
null
2017-06-05T20:24:57
2017-06-05T19:53:30
2017-06-05T19:53:25
null
[ { "alpha_fraction": 0.5740281343460083, "alphanum_fraction": 0.5971877574920654, "avg_line_length": 38.868133544921875, "blob_id": "2b6e284a79da73ffb0e2c212b23f02bdcb818686", "content_id": "50713224b9a1d564b25bc21888ce7d37b050b6ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3627, "license_type": "no_license", "max_line_length": 118, "num_lines": 91, "path": "/wx_plotter.py", "repo_name": "mtnesbitt/BlockedTrafficVisualization", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport datetime\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nfrom attack_info_manager import AttackInfoManager\nfrom mpl_toolkits.basemap import Basemap\nfrom wx import *\nimport wx\nclass TrafficMap(Frame):\n def __init__(self):\n Frame.__init__(self, None, -1,\n 'Moravian Traffic Project', size=(600, 600), pos=(10,10))\n\n self.SetBackgroundColour(\"white\")\n\n panel = Panel(self, size=(1000, 1000), pos=(650, 0))\n\n text = StaticText(panel, -1, style=ALIGN_RIGHT, pos=(10, 10))\n\n text.SetLabel(\"Everyday, thousands of users attempt to get past the Moravian firewall and fail \"\n \"to do so.\"\n \"Interested in the tendencies of where these attacks take place,\"\n \"we decided to develop a program that takes the IP address\"\n \"of each attempt, converts it to longitude/latitude coordinates and plots it on a basemap. \"\n \"The color of the dots corresponds to the type of protocol that is being used. \"\n \"Red is for tcp, blue is udp, green is icmp, and cyan is gre\")\n text.Wrap(600)\n font = wx.Font('70')\n text.SetFont(font)\n\n text.SetBackgroundColour(\"WHITE\")\n\n image_panel = Panel(self, pos=(150, 475), size=(1000, 240))\n image_panel.SetBackgroundColour('white')\n\n img1 = Image(\"diagram.png\", BITMAP_TYPE_ANY)\n w = img1.GetWidth()\n h = img1.GetHeight()\n\n img2 = img1.Scale(w / 1.7, h / 2)\n sb2 = StaticBitmap(image_panel, -1, BitmapFromImage(img2), pos=(0, 0))\n\n self.figure = Figure()\n self.canvas = FigureCanvas(self, -1, self.figure)\n\n self.sizer = FlexGridSizer(cols=2, hgap=10, vgap=10)\n self.sizer = BoxSizer()\n self.sizer.Add(self.canvas)\n self.sizer.Add(panel)\n self.SetSizer(self.sizer)\n\n self.Fit()\n\n self.Maximize()\n self.plot_map()\n self.timer = Timer(self)\n self.Bind(EVT_TIMER, self.callback, self.timer)\n self.timer.Start(milliseconds=50, oneShot=False)\n\n def plot_map(self):\n self.data = AttackInfoManager(100, 10)\n self.ax = self.figure.add_subplot(111)\n self.m = Basemap(projection='cyl', resolution=\"c\", lat_0=0, lon_0=0, ax=self.ax)\n self.m.drawcoastlines()\n xx, yy = self.m(self.data.get_lons(), self.data.get_lats())\n self.scatter = self.m.scatter(xx, yy, s=self.data.get_sizes(), c=self.data.get_colors())\n self.figure.canvas.draw()\n\n def callback(self, event):\n if(len(self.data.get_attack_times()) == 0):\n timestamp = datetime.datetime.strftime(datetime.datetime.now() - datetime.timedelta(seconds=2),\n '%Y/%m/%d%H:%M:%S')\n else:\n timestamp = self.data.get_attack_times()[-1]\n self.data.get_attacks_since(timestamp)\n self.data.update()\n xx, yy = self.m(self.data.get_lons(), self.data.get_lats())\n # values need to be a 2D array, and zip makes a generator of tuples\n self.scatter.set_offsets([list(a) for a in zip(xx, yy)])\n self.scatter.set_color(self.data.get_colors())\n self.scatter.set_sizes(self.data.get_sizes())\n self.figure.canvas.draw()\n\nclass App(App):\n def OnInit(self):\n 'Create the main window and insert the custom frame'\n frame = TrafficMap()\n frame.Show(True)\n return True\napp = App(0)\napp.MainLoop()" }, { "alpha_fraction": 0.8488371968269348, "alphanum_fraction": 0.8488371968269348, "avg_line_length": 85, "blob_id": "9455d324cdb94f9a68b6c7d10ec50480d6f973d1", "content_id": "a5fb670146c74acfc742615759b1b15d1242679e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 86, "license_type": "no_license", "max_line_length": 85, "num_lines": 1, "path": "/README.md", "repo_name": "mtnesbitt/BlockedTrafficVisualization", "src_encoding": "UTF-8", "text": "An application to visualize network traffic blocked by the Moravian College firewall.\n" } ]
2
jiajingchen113322/Jiajing
https://github.com/jiajingchen113322/Jiajing
167bafc18651365b9f9045a58be40dd89b228409
e9956ec7c50838071d2a75614d3a581f54f83dc3
57bf00b2ed9abf220fd8fa9ec72695b0fa0f96f0
refs/heads/master
2020-05-20T00:35:12.324527
2019-11-17T00:07:08
2019-11-17T00:07:08
185,290,488
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6195752024650574, "alphanum_fraction": 0.6464806199073792, "avg_line_length": 26.84375, "blob_id": "bbc85a70404c4e11176d3aa709fc1fdccf155670", "content_id": "84780a0d4b5730588978cd13de648c46745eee19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12027, "license_type": "no_license", "max_line_length": 117, "num_lines": 416, "path": "/ConNTM.py", "repo_name": "jiajingchen113322/Jiajing", "src_encoding": "UTF-8", "text": "import numpy as np\r\nfrom torchvision import datasets,transforms\r\nimport torch\r\nimport torch.nn as nn\r\n# import cv2\r\nimport matplotlib.pyplot as plt\r\nimport torch.nn.functional as F\r\nimport torch.utils.data as Data\r\nfrom torch.autograd import Variable\r\ntorch.manual_seed(0)\r\n\r\ntrain_data=datasets.MNIST(root='./mnist/',train=True\\\r\n\t,transform=transforms.ToTensor(),download=True)\r\n\r\ntest_data=datasets.MNIST(root='./mnist/',train=False\\\r\n\t,transform=transforms.ToTensor(),download=True)\r\n#here we want to define a function which give the stardand input and output\r\n\r\ndef get_st_in_out(alldata,batch_size,sort_num):\r\n\ttrain_input_img=(alldata.data.float())/256\r\n\ttrain_input_img=train_input_img[0:sort_num*batch_size]\r\n\t#the following code could help me to show the image as a try\r\n\t# img=train_input_img[3].numpy()\r\n\t# plt.imshow(img,cmap='gray')\r\n\t# plt.show_img_label()\r\n\r\n\ttrain_output_img_label=(alldata.targets)[0:sort_num*batch_size].reshape(batch_size,sort_num)\r\n\tlabel=torch.sort(train_output_img_label,1)[0]\r\n\r\n\t#make the real input whose size is (1000,sort_num,1,28,28)\r\n\tnet_train_input=np.empty((batch_size,sort_num,1,28,28))\r\n\tfor indice, img in enumerate(train_input_img):\r\n\t\tbatch_num=indice//sort_num #find out which batch the img belongs\r\n\t\tele_num=indice%sort_num # find out wihch position the img should belong within sort_num position for each batch\r\n\t\tnet_train_input[batch_num,ele_num,0]=img\r\n\r\n\r\n\t#the net_train_input size is [1000,sort_num,28,28]\r\n\t#the net_train_ouput size is [1000,sort_num,sort_num]\r\n\t#the position of input and output are corresponding to each other\r\n\tnet_train_input=torch.tensor(net_train_input).float()\r\n\tnet_train_label=train_output_img_label.reshape((batch_size,sort_num))\r\n\t#doing sort\r\n\tnet_train_label=torch.sort(net_train_label,1)[0]\r\n\toutput_eye=torch.eye(10,10)\r\n\r\n\t# we make the net_train_out,whose size is (1000,sort_num,sort_num), is the one-hot of sort\r\n\tnet_train_out=torch.empty((net_train_label.size()[0],sort_num,10))\r\n\tfor i in range(net_train_label.size()[0]):\r\n\t\treal_num_set=list(net_train_label[i])\r\n\t\tnet_train_out[i]=torch.cat([output_eye[j] for j in real_num_set]).reshape(sort_num,10)\r\n\r\n\t#net_train_input size is (batch*sort_num,1,28,28)\r\n\t#net_train_out size is (batch,sort_num,sort_num)\r\n\treturn net_train_input,label\r\n\r\n\r\n\r\n\r\n\r\n# input of CNN is (N,C,H,W)\r\n\r\nclass CNN(nn.Module):\r\n\tdef __init__(self):\r\n\t\tsuper(CNN,self).__init__()\r\n\t\tself.Conv1=nn.Sequential(\r\n\t\t\tnn.Conv2d(1,16,5,1,2),\r\n\t\t\tnn.ReLU(),\r\n\t\t\tnn.MaxPool2d(2))\r\n\t\tself.Conv2=nn.Sequential(\r\n\t\t\tnn.Conv2d(16,32,5,1,2),\r\n\t\t\tnn.ReLU(),\r\n\t\t\tnn.MaxPool2d(2))\r\n\t\tself.out=nn.Linear(32*7*7,10)\r\n\r\n\tdef forward(self,x):\r\n\t\tx=x.reshape(-1,1,28,28)\r\n\t\tx=self.Conv1(x)\r\n\t\tx=self.Conv2(x)\r\n\t\tx=x.view(x.size(0),-1)\r\n\t\toutput=self.out(x)\r\n\t\toutput=torch.softmax(output,1)\r\n\t\treturn output\r\n\r\n# img=net_train_input[0]\r\n# print(img.shape)\r\n# cnn=CNN()\r\n# out=cnn(img)\r\n# out shape is (4,10)\r\n\r\n\r\n#Here we define the controller\r\nclass LSTMController(nn.Module):\r\n\tdef __init__(self):\r\n\t\tsuper(LSTMController,self).__init__()\r\n\t\tself.controller=nn.LSTM(input_size=10,\r\n\t\t\t\t\t\t\t\thidden_size=64,\r\n\t\t\t\t\t\t\t\tnum_layers=1,\r\n\t\t\t\t\t\t\t\tbatch_first=True,\r\n\t\t\t\t\t\t\t\tbidirectional=True)\r\n\tdef forward(self,x):\r\n\t\t# input size is (batch,time_step,inpt_size)\r\n\t\tout,state=self.controller(x,None)\r\n\t\treturn out\r\n\r\n# cnn=CNN()\r\n# out=cnn(net_train_input[0])\r\n# out=out.view(1,4,10)\r\n# controller=LSTMController()\r\n# controller_out=controller(out,None)\r\n# print(controller_out.shape)\r\n# controller_out shape is [1,4,64]\r\n\r\ndef convolve(w, s):\r\n \"\"\"Circular convolution implementation.\"\"\"\r\n assert s.size(0) == 3\r\n t = torch.cat([w[-1:], w, w[:1]])\r\n c = F.conv1d(t.view(1, 1, -1), s.view(1, 1, -1)).view(-1)\r\n return c\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass Memory(nn.Module):\r\n\tdef __init__(self,n,m):\r\n\t\tsuper(Memory,self).__init__()\r\n\t\tself.N=n\r\n\t\tself.M=m\r\n\t\tself.register_buffer('mem_bias', torch.Tensor(self.N, self.M))\r\n\t\tstdev = 1 / (np.sqrt(self.N + self.M))\r\n\t\tnn.init.uniform_(self.mem_bias, -stdev, stdev)\r\n\t\tself.memory=self.mem_bias\r\n\t\t# self.memory=torch.empty((self.N,self.M)).fill_(0.1)\r\n\t\r\n\tdef rest_memory(self):\r\n\t\t# nn.init.uniform_(self.mem_bias,-stdev,stdev)\r\n\t\tself.memory=self.mem_bias\r\n\t\t# self.memory=torch.empty((self.N,self.M)).fill_(0.1)\r\n\r\n\tdef size(self):\r\n\t\treturn self.N,self.M\r\n\r\n\tdef read(self,w):\r\n\t\tw=w.reshape(1,self.N)\r\n\t\tr=torch.matmul(w,self.memory).squeeze()\r\n\t\treturn r\r\n\r\n\tdef write(self,w,e,a):\r\n\t\t# e,a shape is (self.M)\r\n\t\tself.prev=self.memory\r\n\t\tera=torch.matmul(w.reshape(self.N,1),e.reshape(1,self.M))\r\n\t\tadd=torch.matmul(w.reshape(self.N,1),a.reshape(1,self.M))\r\n\t\tself.memory=self.prev*(1-era)+add\r\n\r\n\tdef similarity(self,k,b):\r\n\t\t# k's shape is self.M, b's shape is 1\r\n\t\t# wc=F.softmax(b * F.cosine_similarity(self.memory + 1e-16, k.reshape(1,self.M) + 1e-16, dim=-1), dim=0)\r\n\t\ta=F.cosine_similarity(self.memory + 1e-16, k.reshape(1,self.M) + 1e-16, dim=-1)\r\n\t\twc=F.softmax(a,0)\r\n\t\treturn wc\r\n\tdef interpolate(self,w_pre,wc,g):\r\n\t\twg=g * wc + (1 - g) * w_pre\r\n\t\treturn wg\r\n\r\n\tdef shift(self,wg,s):\r\n\t\ts=s.reshape(-1)\r\n\t\twg=wg.reshape(-1)\r\n\t\twt_pie=convolve(wg,s)\r\n\t\treturn wt_pie\r\n\r\n\tdef sharpen(self,w_pie,y):\r\n\t\tw=(w_pie)**torch.trunc(y)\r\n\t\tw = torch.div(w,torch.sum(w)+1e-16)\r\n\t\treturn w\r\n\t\r\n\tdef address(self, k, b, g, s, y, w_pre):\r\n\t\twc=self.similarity(k,b)\r\n\t\twg=self.interpolate(w_pre,wc,g)\r\n\t\tw_pie=self.shift(wg,s)\r\n\t\tw=self.sharpen(w_pie,y)\r\n\t\treturn w\r\n\t\t\"\"\"NTM Addressing (according to section 3.3).\r\n\r\n Returns a softmax weighting over the rows of the memory matrix.\r\n\r\n :param k: The key vector.\r\n :param β: The key strength (focus).\r\n :param g: Scalar interpolation gate (with previous weighting).\r\n :param s: Shift weighting.\r\n :param γ: Sharpen weighting scalar.\r\n :param w_prev: The weighting produced in the previous time step.\r\n \"\"\"\r\n # Content focus\r\n\r\ndef _split_cols(mat, lengths):\r\n\tassert mat.size()[1] == sum(lengths)\r\n\tl = np.cumsum([0] + lengths)\r\n\tresults = []\r\n\tfor s, e in zip(l[:-1], l[1:]):\r\n\t results += [mat[:, s:e]]\r\n\treturn results\r\n\r\n\r\nclass read_head(nn.Module):\r\n\tdef __init__(self,memory,controller_size):\r\n\t\tsuper(read_head,self).__init__()\r\n\t\tself.memory=memory\r\n\t\tself.controller_size=controller_size\r\n\t\tself.N, self.M=memory.size()\r\n\t\t# Corresponding to k, β, g, s, γ sizes from the paper\r\n\t\tself.read_lengths=[self.M, 1, 1, 3, 1]\r\n\t\tself.fc_read = nn.Linear(controller_size, sum(self.read_lengths))\r\n\r\n\tdef address_memory(self, k, β, g, s, γ, w_prev):\r\n\t\tk = k.clone()\r\n\t\tβ = F.softplus(β)\r\n\t\tg = torch.sigmoid(g)\r\n\t\ts = F.softmax(s, dim=1)\r\n\t\tγ = 1 + F.softplus(γ)\r\n\r\n\t\tw = self.memory.address(k, β, g, s, γ, w_prev)\r\n\r\n\t\treturn w\r\n\r\n\tdef forward(self,embeding,w_pre):\r\n\t\to=self.fc_read(embeding).reshape(1,sum(self.read_lengths))\r\n\t\tk,b,g,s,y=_split_cols(o, self.read_lengths)\r\n\t\t#read memory\r\n\t\tw = self.address_memory(k, b, g, s, y, w_pre)\r\n\t\tr = self.memory.read(w)\r\n\r\n\t\treturn r,w\r\n\r\nclass write_head(nn.Module):\r\n\tdef __init__(self,memory,controller_size):\r\n\t\tsuper(write_head,self).__init__()\r\n\t\tself.memory=memory\r\n\t\tself.controller_size=controller_size\r\n\t\tself.N,self.M=self.memory.size()\r\n\t\t# Corresponding to k, β, g, s, γ, e, a sizes from the paper\r\n\t\tself.write_lengths = [self.M, 1, 1, 3, 1, self.M, self.M]\r\n\t\tself.fc_write = nn.Linear(controller_size, sum(self.write_lengths))\r\n\t\r\n\tdef address_memory(self, k, β, g, s, γ, w_prev):\r\n\t\tk = k.clone()\r\n\t\tβ = F.softplus(β)\r\n\t\tg = torch.sigmoid(g)\r\n\t\ts = F.softmax(s, dim=1)\r\n\t\tγ = 1 + F.softplus(γ)\r\n\r\n\t\tw = self.memory.address(k, β, g, s, γ, w_prev)\r\n\r\n\t\treturn w\r\n\r\n\tdef forward(self,embedings,w_preV):\r\n\t\to=self.fc_write(embedings).reshape(1,-1)\r\n\t\tk,b,g,s,y,e,a=_split_cols(o,self.write_lengths)\r\n\t\tw=self.address_memory(k,b,g,s,y,w_preV)\r\n\t\tself.memory.write(w,e,a)\r\n\t\treturn w\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass ntm(nn.Module):\r\n\tdef __init__(self,memory,controller):\r\n\t\tsuper(ntm,self).__init__()\r\n\t\tself.memory=memory\r\n\t\tself.N,self.M=self.memory.size()\r\n\t\tself.controller=controller\r\n\t\tself.r_head=read_head(self.memory,128)\r\n\t\tself.w_head=write_head(self.memory,128)\r\n\t\tself.fc1=nn.Linear(self.M+self.r_head.controller_size,200)\r\n\t\tself.fc2=nn.Linear(200,10)\r\n\t\tself.re=nn.ReLU()\r\n\t\t\r\n\tdef forward(self,x):\r\n\t\treal_out=torch.empty((4,10))\r\n\t\t#input size is (4,10)\r\n\t\tstate=None\r\n\t\tW_rpre=F.softmax(torch.empty(1,self.N).fill_(0.1))\r\n\t\tW_wpre=F.softmax(torch.empty(1,self.N).fill_(0.1))\r\n\t\tinpt=x.reshape(1,x.shape[0],x.shape[1])\r\n\t\tcont_out=self.controller(inpt)\r\n\t\tcont_out=cont_out.squeeze()\r\n\t\t\r\n\t\tfor i in range(4):\r\n\t\t\teve_inp=cont_out[i].reshape(-1)\r\n\t\t\t#inp shape is [1,4,10]\r\n\t\t\t# cont_out,out_state=controller(inp,state)\r\n\r\n\t\t\t# state=out_state\r\n\t\t\tW_wpre=self.w_head(eve_inp,W_wpre)\r\n\t\t\tr,W_rpre=self.r_head(eve_inp,W_rpre)\r\n\t\t\t# cont_out=cont_out.reshape(-1)\r\n\t\t\t# inpt2=torch.cat((eve_inp,r))\r\n\t\t\tout=self.fc1(torch.cat((eve_inp,r)))\r\n\t\t\tout=self.re(out)\r\n\t\t\tout=self.fc2(out).reshape(-1)\r\n\t\t\treal_out[i]=out\r\n\r\n\t\t# out=torch.softmax(out,1)\r\n\t\t\r\n\t\treturn real_out\r\n\r\n\r\n# This is the net combine all things together\r\nclass convNTM(nn.Module):\r\n\tdef __init__(self,conv,ntm):\r\n\t\tsuper(convNTM,self).__init__()\r\n\t\tself.conv=conv\r\n\t\tself.ntm=ntm\r\n\r\n\tdef forward(self,x):\r\n\t\tinpt=self.conv(x)\r\n\t\tinpt=inpt.view(-1,10)\r\n\t\tbatch_num=int((inpt.size()[0])/4)\r\n\t\tout_form=torch.empty((batch_num,4,10))\r\n\t\tfor bat in range(batch_num):\r\n\t\t\t#one_batch_inpt size should be (4,10)\r\n\t\t\tone_batch_inpt=inpt[bat:4+bat]\r\n\t\t\tout=self.ntm(one_batch_inpt)\r\n\t\t\tout_form[bat]=out\r\n\t\t\tself.ntm.memory.rest_memory()\r\n\t\t\t\r\n\t\treturn out_form\r\n\r\n# def test_accuracy(mynet,inpt,label):\r\n# \t#inpt size should be [batch,4,1,28,28]\r\n# \t#label should be [batch,4]\r\n# \t#my_net should be a convNTM\r\n# \t#oupt size should be [batch,4,4]\r\n# \toupt=mynet(inpt)\r\n# \toupt=torch.softmax(oupt,2).argmax(2).reshape(-1)\r\n# \tlabel=label.reshape(-1)\r\n# \taccuracy=int(sum(oupt==label))/label.shape[0]\r\n# \treturn accuracy\r\ndef test_accuracy(mynet,inpt,label):\r\n\t#inpt size should be [batch,4,1,28,28]\r\n\t#label should be [batch,4]\r\n\t#my_net should be a convNTM\r\n\t#oupt size should be [batch,4,4]\r\n\toupt=mynet(inpt)\r\n\toupt=torch.argmax(oupt,2).reshape(-1)\r\n\tlabel=label.reshape(-1)\r\n\toupt,label=oupt.numpy(),label.numpy()\r\n\taccuracy=np.sum(oupt==label)/oupt.shape[0]\r\n\treturn accuracy\r\n\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n\ttraining_size=1000\r\n\tLR=0.05\r\n\tnet_train_input,net_train_output=get_st_in_out(train_data,training_size,4)\r\n\tnet_test_input,net_test_output=get_st_in_out(test_data,100,4)\r\n\t# [5,4,1,28,28] [10,4]\r\n\t#create batch training\r\n\ttorch_dataset=Data.TensorDataset(net_train_input,net_train_output)\r\n\tloader=Data.DataLoader(dataset=torch_dataset,\r\n\t\t\t\t\t\t\tbatch_size=5,\r\n\t\t\t\t\t\t\tshuffle=True,\r\n\t\t\t\t\t\t\tnum_workers=2)\r\n\r\n\r\n\ttorch.manual_seed(0)\r\n\tconv=CNN()\r\n\t# conv=torch.load('cnn1.pkl')\r\n\t# for i in conv.parameters():\r\n\t# \ti.requires_grad_(False)\r\n\t\r\n\tmemory=Memory(50,50)\r\n\tcontroller=LSTMController()\r\n\tNTM=ntm(memory,controller)\r\n\tmynet=convNTM(conv,NTM)\r\n\t#inpt size should be (N,1,28,28),N is the number of images\r\n\t# inpt=net_train_input[0:3]\r\n\t# out=mynet(inpt)\r\n\t# print(out)\r\n\toptimizer=torch.optim.Adam(mynet.parameters(),lr=LR)\r\n\tloss_func=nn.CrossEntropyLoss()\r\n\r\n\taccuracy_list=[]\r\n\r\n\tfor epoch in range(1):\r\n\t\tfor step,(x,y) in enumerate(loader):\r\n\t\t\t# b_x's size should be [batch_size=5,4,1,28,28]\r\n\t\t\t# out's size is [batch_size=5,4,10]\r\n\t\t\t# b_y's size should be [batch_size=5,4]\r\n\t\t\tb_x=Variable(x)\r\n\t\t\tb_y=Variable(y)\r\n\t\t\tout=mynet(b_x)\r\n\t\t\tout=out.reshape(-1,10)\r\n\t\t\tb_y=b_y.reshape(-1)\r\n\t\t\tloss=loss_func(out,b_y)\r\n\t\t\toptimizer.zero_grad()\r\n\t\t\tloss.backward()\r\n\t\t\toptimizer.step()\r\n\t\t\tif step%10==0:\r\n\t\t\t\taccuracy=test_accuracy(mynet,net_test_input,net_test_output)\r\n\t\t\t\tprint('this is epoch',epoch,'step',step,' is finished')\r\n\t\t\t\tprint('the accuracy is ',accuracy)\r\n\t\t\t\taccuracy_list.append(accuracy)\r\n\t\t\t\t# print('loss:',loss)\r\n\t\t\t\t# train_loss.append(loss.clone().detach().numpy())\r\n\r\n\taccuracy_list=np.array(accuracy_list)\r\n\tnp.save('redommemo.npy',accuracy_list)\r\n\r\n\t\t\r\n" }, { "alpha_fraction": 0.6303362250328064, "alphanum_fraction": 0.6656762957572937, "avg_line_length": 26.225664138793945, "blob_id": "1a4f0e6679a3d09663e6b22140969b122ff7f3c8", "content_id": "b8430b81c7f36f9efb68f6d5436b8533d75a6152", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6395, "license_type": "no_license", "max_line_length": 103, "num_lines": 226, "path": "/conlstm.py", "repo_name": "jiajingchen113322/Jiajing", "src_encoding": "UTF-8", "text": "import numpy as np\r\nfrom torchvision import datasets,transforms\r\nimport torch\r\nimport torch.nn as nn\r\n# import cv2\r\nimport matplotlib.pyplot as plt\r\nimport torch.nn.functional as F\r\nimport torch.utils.data as Data\r\nfrom torch.autograd import Variable\r\nimport matplotlib.pyplot as plt\r\ntorch.manual_seed(0)\r\n\r\ntrain_data=datasets.MNIST(root='./mnist/',train=True\\\r\n\t,transform=transforms.ToTensor(),download=False)\r\n\r\ntest_data=datasets.MNIST(root='./mnist/',train=False\\\r\n\t,transform=transforms.ToTensor(),download=False)\r\n#here we want to define a function which give the stardand input and output\r\n\r\ndef get_st_in_out(alldata,batch_size):\r\n\ttrain_input_img=(alldata.data.float())/255\r\n\ttrain_input_img=train_input_img[0:4*batch_size]\r\n\t#the following code could help me to show the image as a try\r\n\t# img=train_input_img[3].numpy()\r\n\t# plt.imshow(img,cmap='gray')\r\n\t# plt.show_img_label()\r\n\r\n\ttrain_output_img_label=(alldata.targets)[0:4*batch_size].reshape(batch_size,4)\r\n\tlabel=torch.sort(train_output_img_label,1)[0]\r\n\r\n\t#make the real input whose size is (1000,4,1,28,28)\r\n\tnet_train_input=np.empty((batch_size,4,1,28,28))\r\n\tfor indice, img in enumerate(train_input_img):\r\n\t\tbatch_num=indice//4 #find out which batch the img belongs\r\n\t\tele_num=indice%4 # find out wihch position the img should belong within 4 position for each batch\r\n\t\tnet_train_input[batch_num,ele_num]=img.unsqueeze(0)\r\n\r\n\r\n\t#the net_train_input size is [1000,4,28,28]\r\n\t#the net_train_ouput size is [1000,4,4]\r\n\t#the position of input and output are corresponding to each other\r\n\tnet_train_input=torch.tensor(net_train_input).float()\r\n\tnet_train_label=train_output_img_label.reshape((batch_size,4))\r\n\t#doing sort\r\n\tnet_train_label=torch.sort(net_train_label,1)[0]\r\n\toutput_eye=torch.eye(10,10)\r\n\r\n\t# we make the net_train_out,whose size is (1000,4,4), is the one-hot of sort\r\n\tnet_train_out=torch.empty((net_train_label.size()[0],4,10))\r\n\tfor i in range(net_train_label.size()[0]):\r\n\t\treal_num_set=list(net_train_label[i])\r\n\t\tnet_train_out[i]=torch.cat([output_eye[j] for j in real_num_set]).reshape(4,10)\r\n\r\n\t#net_train_input size is (batch*4,1,28,28)\r\n\t#net_train_out size is (batch,4,4)\r\n\treturn net_train_input,label\r\n\r\n\r\n\r\n\r\n\r\n# input of CNN is (N,C,H,W)\r\n\r\nclass CNN(nn.Module):\r\n\tdef __init__(self):\r\n\t\tsuper(CNN,self).__init__()\r\n\t\tself.Conv1=nn.Sequential(\r\n\t\t\tnn.Conv2d(1,16,5,1,2),\r\n\t\t\tnn.ReLU(),\r\n\t\t\tnn.MaxPool2d(2))\r\n\t\tself.Conv2=nn.Sequential(\r\n\t\t\tnn.Conv2d(16,32,5,1,2),\r\n\t\t\tnn.ReLU(),\r\n\t\t\tnn.MaxPool2d(2))\r\n\t\tself.out=nn.Linear(32*7*7,10)\r\n\r\n\tdef forward(self,x):\r\n\t\tx=x.reshape(-1,1,28,28)\r\n\t\tx=self.Conv1(x)\r\n\t\tx=self.Conv2(x)\r\n\t\tx=x.view(x.size(0),-1)\r\n\t\toutput=self.out(x)\r\n\t\t# output=torch.softmax(output,1)\r\n\t\treturn output\r\n\r\n# img=net_train_input[0]\r\n# print(img.shape)\r\n# cnn=CNN()\r\n# out=cnn(img)\r\n# out shape is (4,10)\r\n\r\n\r\n#Here we define the controller\r\nclass BidrectionLstm(nn.Module):\r\n\tdef __init__(self):\r\n\t\tsuper(BidrectionLstm,self).__init__()\r\n\t\tself.rnn=nn.LSTM(input_size=10,\r\n\t\t\t\t\t\t\t\thidden_size=64,\r\n\t\t\t\t\t\t\t\tnum_layers=1,\r\n\t\t\t\t\t\t\t\tbatch_first=True,\r\n\t\t\t\t\t\t\t\tbidirectional=True)\r\n\t\tself.fc1=nn.Linear(128,10)\r\n\tdef forward(self,x):\r\n\t\t# input size is (batch,time_step,inpt_size)\r\n\t\tout,_=self.rnn(x,None)\r\n\t\tout=self.fc1(out)\r\n\t\tout=torch.softmax(out,2)\r\n\t\treturn out\r\n\r\nclass conlstm(nn.Module):\r\n\tdef __init__(self,conv,lstm):\r\n\t\tsuper(conlstm,self).__init__()\r\n\t\tself.conv=conv\r\n\t\tself.lstm=lstm\r\n\r\n\tdef forward(self,x):\r\n\t\tx=x.reshape(-1,1,28,28)\r\n\t\tout_cnn=self.conv(x)\r\n\t\tout_cnn_onehot=torch.zeros(out_cnn.shape[0],out_cnn.shape[1])\r\n\t\tlabel=torch.argmax(out_cnn,1).unsqueeze(1)\r\n\t\tout_cnn_onehot=out_cnn_onehot.scatter_(1,label,1.)\r\n\t\tinital_data=out_cnn_onehot.reshape(-1,4,10)\r\n\t\tlstm_out=self.lstm(inital_data)\r\n\t\tlstm_out=torch.softmax(lstm_out,2)\r\n\t\treturn lstm_out\r\n\r\n# cnn=CNN()\r\n# out=cnn(net_train_input[0])\r\n# out=out.view(1,4,10)\r\n# controller=LSTMController()\r\n# controller_out=controller(out,None)\r\n# print(controller_out.shape)\r\n# controller_out shape is [1,4,64]\r\n\r\n\r\n\r\ndef test_accuracy(mynet,inpt,label):\r\n\t#inpt size should be [batch,4,1,28,28]\r\n\t#label should be [batch,4]\r\n\t#my_net should be a convNTM\r\n\t#oupt size should be [batch,4,4]\r\n\toupt=mynet(inpt)\r\n\toupt=torch.argmax(oupt,2).reshape(-1)\r\n\tlabel=label.reshape(-1)\r\n\toupt,label=oupt.numpy(),label.numpy()\r\n\taccuracy=np.sum(oupt==label)/oupt.shape[0]\r\n\treturn accuracy\r\n\t\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n\r\n\ttraining_size=4000\r\n\tLR=0.05\r\n\r\n\t#[1000,4,1,28,28] [1000,4] \r\n\tnet_train_input,net_train_output=get_st_in_out(train_data,training_size)\r\n\tnet_test_input,net_test_output=get_st_in_out(test_data,100)\r\n\ttorch_dataset=Data.TensorDataset(net_train_input,net_train_output)\r\n\tloader=Data.DataLoader(dataset=torch_dataset,\r\n\t\t\t\t\t\t\tbatch_size=5,\r\n\t\t\t\t\t\t\tshuffle=True,\r\n\t\t\t\t\t\t\tnum_workers=2)\r\n\r\n\r\n\t# torch.manual_seed(0)\r\n\tconv=CNN()\r\n\t# conv=torch.load('cnn1.pkl')\r\n\t# for i in conv.parameters():\r\n\t# \ti.requires_grad_(False)\r\n\r\n\tlst=BidrectionLstm()\r\n\t# lst=torch.load('lstm.pkl')\r\n\t\r\n\tmynet=conlstm(conv,lst)\r\n\t# accuracy=test_accuracy(mynet,net_test_input,net_test_output)\r\n\t\t\t\t\r\n\t# inpt=net_test_input[:2]\r\n\t# oupt=mynet(inpt)\r\n\t# outpt=torch.argmax(oupt,2)\r\n\t# accuracy=test_accuracy(mynet,net_test_input,net_test_output)\r\n\t# print(accuracy)\r\n\r\n\t# for i in lst.parameters():\r\n\t# \ti.requires_grad_(False)\r\n\t# mynet=conlstm(conv,lst)\r\n\t# inpt=net_test_input[:2]\r\n\t# oupt=mynet(inpt)\r\n\r\n\t# oupt=torch.argmax(oupt,2)\r\n\r\n\t# inpt=net_train_input[:2]\r\n\t# out=mynet(inpt)\r\n\t# here out shape is [2,4,10]\r\n\toptimizer=torch.optim.Adam(mynet.parameters(),lr=LR)\r\n\tloss_func=nn.CrossEntropyLoss()\r\n\taccuracy_list=[]\r\n\r\n\tfor i in range(3):\r\n\t\tfor step,(b_x,b_y) in enumerate(loader):\r\n\t\t\tb_x=Variable(b_x)\r\n\t\t\tb_y=Variable(b_y)\r\n\t\t\tb_y=b_y.reshape(-1)\r\n\t\t\toutpt=mynet(b_x)\r\n\t\t\toutpt=outpt.reshape(-1,10)\r\n\t\t\tloss=loss_func(outpt,b_y)\r\n\t\t\toptimizer.zero_grad()\r\n\t\t\tloss.backward()\r\n\t\t\toptimizer.step()\r\n\t\t\tif step%10==0:\r\n\t\t\t\taccuracy=test_accuracy(mynet,net_test_input,net_test_output)\r\n\t\t\t\tprint('step',step,' is finished')\r\n\t\t\t\tprint('the accuracy is ',accuracy)\r\n\t\t\t\taccuracy_list.append(accuracy)\r\n\t\t\t\t# inpt=net_test_input[0].reshape(-1,1,28,28)\r\n\t\t\t\t# outpt=mynet(inpt)\r\n\t\t\t\t# outpt=torch.argmax(outpt,2)\r\n\t\t\t\t# print('label:',net_test_output[0])\r\n\t\t\t\t# print('outpt:',outpt)\r\n\taccuracy=np.array(accuracy_list)\r\n\tnp.save('prcnn_for_comlstm.npy',accuracy)\r\n\r\n\t\r\n\r\n\r\n\t\r\n\t\t\r\n" }, { "alpha_fraction": 0.7803163528442383, "alphanum_fraction": 0.7961335778236389, "avg_line_length": 55.900001525878906, "blob_id": "b6455b6b5b0c727f57aa37d66168be1722f0ee1d", "content_id": "a88b88dc979c3cceba25f2da272ae4a0b3132559", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 569, "license_type": "no_license", "max_line_length": 118, "num_lines": 10, "path": "/README.md", "repo_name": "jiajingchen113322/Jiajing", "src_encoding": "UTF-8", "text": "# Jiajing\n700 homework.\nIn this taks, I design a network for sorting hand writting image\nThe ConNTM.py contains all code for the combination of CNN and NTM\nBesides, the conlistm.py is the network combines CNN and LSTM for images sorting.\nEven though the performance of both work is not good, but the accuracy is surely improved by training.\ncnn.pkl and lstm.pkl is the pytorch parameters file which saves the pretrained cnn and lstm, you could go into py file\nto choose whether to use them.\n\n![image](https://github.com/jiajingchen113322/Jiajing/blob/master/image.PNG)\n" } ]
3
aryanation12/aimlay
https://github.com/aryanation12/aimlay
b393f014b28489286b055503be52837d0717bc51
4ec7891fde7f811c01f1aa73a8da247be2d1f8dd
ddbe804ad00f43918930429ef81e51ae1d08f730
refs/heads/main
2023-03-06T22:19:54.780660
2021-02-22T13:08:20
2021-02-22T13:08:20
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5336617231369019, "alphanum_fraction": 0.587848961353302, "avg_line_length": 25.478260040283203, "blob_id": "772598d340c8c252eea7ec5833b43742b95eadc6", "content_id": "450dfa8535b3abd138c99219184fa5f0cea5bd7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 609, "license_type": "no_license", "max_line_length": 71, "num_lines": 23, "path": "/app/migrations/0008_auto_20210218_0414.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2021-02-17 22:44\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0007_auto_20210218_0345'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='postabout',\n name='banner_carAboutImage6',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postabout',\n name='banner_carAboutImage7',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n ]\n" }, { "alpha_fraction": 0.5613207817077637, "alphanum_fraction": 0.5943396091461182, "avg_line_length": 25.5, "blob_id": "11a998e08568f48d416034153cbc94401d3e6b7d", "content_id": "b9b6551d336931db0be949b76ec9cf2b839fd78e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 212, "license_type": "no_license", "max_line_length": 54, "num_lines": 8, "path": "/adminapp/templates/setting.html", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "{% extends 'basefile.html' %} {% block contentAdmin %}\n\n<div class=\"container-fluid my-4 py-5 mt-4\">\n <br /><br /><br /><br /><br />\n <h1 class=\"mt-5 pt-5\">Setting Page</h1>\n</div>\n\n{% endblock contentAdmin %}\n" }, { "alpha_fraction": 0.7648115158081055, "alphanum_fraction": 0.7648115158081055, "avg_line_length": 25.571428298950195, "blob_id": "e0c61d334df206ddfdaa13d7c8ffc43901c647d9", "content_id": "e074cd670fe9e531bab2ad574bc100c3fd33b04c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 557, "license_type": "no_license", "max_line_length": 67, "num_lines": 21, "path": "/app/api/urls.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from django.urls import path, include\nfrom app.api import views\nfrom rest_framework import routers\n\n\n\n\n# creating router object\nrouter = routers.DefaultRouter()\n\n#register router\nrouter.register('homes', views.HomeView, basename='homes')\nrouter.register('custom', views.CustomerView, basename='custom')\nrouter.register('abouts', views.AboutView, basename='abouts')\nrouter.register('visions', views.VisionView, basename='visions')\nrouter.register('serivces', views.ServiceView, basename='services')\n\n\nurlpatterns = [\n path('api/', include(router.urls)),\n]" }, { "alpha_fraction": 0.7109570503234863, "alphanum_fraction": 0.7250144481658936, "avg_line_length": 30.289155960083008, "blob_id": "d85dc682fa6ef1c4fa908648437535fb4f7fddb1", "content_id": "18d25506354f6813548985a0bde5876e39875d6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5193, "license_type": "no_license", "max_line_length": 94, "num_lines": 166, "path": "/app/models.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from django.db import models\nimport cloudinary\nfrom cloudinary.models import CloudinaryField\nfrom django.contrib.auth.models import User\nfrom django.urls import reverse\nfrom ckeditor.fields import RichTextField\n\n\n# Create your models here.\nSTATE_CHOICES = (\n ('Andaman & Nicobar Island','Andaman & Nicobar Island'),('Andhra Pardesh','Andhra Pardesh'), \n ('Arunachal Pardesh','Arunachal Pardesh'),\n ('Assam','Assam'),\n ('Bihar','Bihar'),\n ('Chandigarh','Chandigarh'),\n ('Chhattishgarh','Chhattishgarh'),\n ('Dadra & Nagar Haveli','Dadra & Nagar Haveli'),\n ('Daman and Diu','Daman and Diu'),\n ('Delhi', 'Delhi'),\n ('Goa','Goa'),\n ('Gujarat','Gujarat'),\n ('Haryana','Haryana'),\n ('Himachal Pardesh','Himachal Pardesh'),\n ('Jammu & Kashmir','Jammu & Kashmir'),\n ('Jharkhand','Jharkhand'),\n ('Karnataka','Karnataka'),\n ('Lakshadweep','Lakshadweep'),\n ('MAdhya Pardesh','MAdhya Pardesh'),\n ('Maharashtra','Maharashtra'),\n ('Manipur','Manipur'),\n ('Meghalya','Meghalya'),\n ('Mizoram','Mizoram'),\n ('Nagaland','Nagaland'),\n ('Odisha','Odisha'),\n ('Pondicherry','Pondicherry'),\n ('Punjab','Punjab'),\n ('Rajashthan','Rajashthan'),\n ('Sikkim','Sikkim'),\n ('Tamil Nadu','Tamil Nadu'),\n ('Telangana','Telangana'),\n ('Tripura','Tripura'),\n ('Uttarakhand','Uttarakhand'),\n ('Uttar Pardesh','Uttar Pardesh'),\n ('West Bengal','West Bengal')\n)\n\n\nTARGET_GROUP = (\n ('Candidate','Candidate'),\n ('Referral','Referral'),\n ('Business_Partner','Business_Partner'),\n)\n\nclass Customer(models.Model):\n name = models.CharField(max_length=50)\n email= models.EmailField(max_length=254)\n address = models.CharField(max_length=50)\n city = models.CharField(max_length=50)\n target = models.CharField(choices=TARGET_GROUP, max_length=50)\n zipcode = models.IntegerField()\n state = models.CharField(choices=STATE_CHOICES,max_length=50)\n message = models.TextField()\n\n def __str__(self):\n return str(self.id)\n \n def get_absolute_url(self):\n return reverse('home')\n\n\nclass PostHome(models.Model):\n banner_homeImage1 =cloudinary.models.CloudinaryField('image')\n banner_homeImage2 =cloudinary.models.CloudinaryField('image')\n banner_homeImage3 =cloudinary.models.CloudinaryField('image')\n banner_review_image1 =cloudinary.models.CloudinaryField('image')\n banner_review_image2 =cloudinary.models.CloudinaryField('image')\n banner_review_image3 =cloudinary.models.CloudinaryField('image')\n\n def __str__(self):\n return str()\n\n\nclass PostAbout(models.Model):\n banner_Abtimage1 =cloudinary.models.CloudinaryField('image')\n banner_Abtimage2 =cloudinary.models.CloudinaryField('image')\n banner_Abtimage3 =cloudinary.models.CloudinaryField('image')\n aboutheading = models.CharField( max_length=50)\n banner_carAboutImage1 =cloudinary.models.CloudinaryField('image')\n banner_carAboutImage2 =cloudinary.models.CloudinaryField('image')\n banner_carAboutImage3 =cloudinary.models.CloudinaryField('image')\n banner_carAboutImage4 =cloudinary.models.CloudinaryField('image')\n banner_carAboutImage5 =cloudinary.models.CloudinaryField('image')\n banner_carAboutImage6 =cloudinary.models.CloudinaryField('image')\n banner_carAboutImage7 =cloudinary.models.CloudinaryField('image')\n Aboutbody = RichTextField()\n\n def __str__(self):\n return str(self.id)\n\n\nclass PostService(models.Model):\n Service_heading = models.CharField( max_length=50)\n banner_serv1 =cloudinary.models.CloudinaryField('image')\n banner_serv2 =cloudinary.models.CloudinaryField('image')\n banner_serv3 =cloudinary.models.CloudinaryField('image')\n Servicebody = RichTextField()\n def __str__(self):\n return str(self.id)\n\n\nclass PostVision(models.Model):\n banner_Visimage1 =cloudinary.models.CloudinaryField('image')\n banner_Visimage2 =cloudinary.models.CloudinaryField('image')\n banner_Visimage3 =cloudinary.models.CloudinaryField('image')\n Vision_heading = models.CharField( max_length=50)\n Visionbody = RichTextField() \n \n def __str__(self):\n return str(self.id)\n\nCANDIDATE_GROUP = (\n ('Candidate','Candidate'),\n)\n\nclass Student(models.Model):\n Name = models.CharField(max_length=50)\n Email = models.EmailField(max_length=254)\n Mobile = models.IntegerField()\n Target = models.CharField(choices=CANDIDATE_GROUP, max_length=50, default=None)\n Address = models.CharField(max_length=50)\n Message = models.TextField()\n\n\nBUSINESS_GROUP = (\n ('Business_Partner','Business_Partner'),\n)\n \nclass Business(models.Model):\n Name = models.CharField(max_length=50)\n Email = models.EmailField(max_length=254)\n Mobile = models.IntegerField()\n Target = models.CharField(choices=BUSINESS_GROUP, max_length=50, default=None)\n Address = models.CharField(max_length=50)\n Message = models.TextField()\n\n\n\nREFERRAL_GROUP = (\n ('Referral','Referral'),\n)\n\n\n\nclass Refferal(models.Model):\n Name = models.CharField(max_length=50)\n Email = models.EmailField(max_length=254)\n Mobile = models.IntegerField()\n Target = models.CharField(choices=REFERRAL_GROUP, max_length=50, default=None)\n Address = models.CharField(max_length=50)\n Message = models.TextField()\n\n\nclass quickuser(models.Model):\n name = models.CharField(max_length=50)\n email = models.EmailField(max_length=254)\n message = models.TextField()" }, { "alpha_fraction": 0.6246006488800049, "alphanum_fraction": 0.6246006488800049, "avg_line_length": 40.733333587646484, "blob_id": "56694a1eaf2bf878fa7d1d709a1d98f1a8bfed2a", "content_id": "5237dfdc64f77928f8b8b328e8858668c588b5ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 65, "num_lines": 15, "path": "/app/urls.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home.as_view(), name='home'),\n path('ref/', views.referral.as_view(), name='ref'),\n path('student/', views.student.as_view(), name='student'),\n path('business/', views.business.as_view(), name='business'),\n path('about/', views.about.as_view(), name='about'),\n path('vision/', views.vision, name='vision'),\n path('services/', views.services, name='service'),\n path('contact/', views.contact.as_view(), name='contact'),\n path('join/', views.join, name='join'),\n path('form/', views.Query.as_view(), name='form'),\n]\n" }, { "alpha_fraction": 0.5151171684265137, "alphanum_fraction": 0.5291005373001099, "avg_line_length": 32.92307662963867, "blob_id": "483ce14aac93b9f98c08592aac53cafa4ad51ca7", "content_id": "360a41eedb4994995574b9348d81fbae6140baf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2646, "license_type": "no_license", "max_line_length": 114, "num_lines": 78, "path": "/app/migrations/0006_auto_20210216_1410.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2021-02-16 08:40\n\nimport ckeditor.fields\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0005_auto_20210216_1313'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='PostAbout',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('banner_Abtimage', models.ImageField(upload_to='images/')),\n ('aboutheading', models.CharField(max_length=50)),\n ('banner_carAboutImage', models.ImageField(upload_to='images/')),\n ('Aboutbody', ckeditor.fields.RichTextField()),\n ],\n ),\n migrations.CreateModel(\n name='PostService',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Service_heading', models.CharField(max_length=50)),\n ('banner_serv', models.ImageField(upload_to='images/')),\n ('Servicebody', ckeditor.fields.RichTextField()),\n ],\n ),\n migrations.CreateModel(\n name='PostVision',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('banner_Visimage', models.ImageField(upload_to='images/')),\n ('Vision_heading', models.CharField(max_length=50)),\n ('Visionbody', ckeditor.fields.RichTextField()),\n ],\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='About_body',\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='About_heading',\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='Service_body',\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='Service_heading',\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='Vision_body',\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='Vision_heading',\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='banner_AboutImage',\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='banner_Abtimage',\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='banner_serv',\n ),\n ]\n" }, { "alpha_fraction": 0.5324459075927734, "alphanum_fraction": 0.5640599131584167, "avg_line_length": 24.04166603088379, "blob_id": "b14b6a9be9ad03ac192e487b9d0051ac9a1bc887", "content_id": "f6cab0c9e8ce010618670c66665b412b61df2978", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "no_license", "max_line_length": 69, "num_lines": 24, "path": "/app/migrations/0005_auto_20210216_1313.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2021-02-16 07:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0004_posthome'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='posthome',\n old_name='banner_Aboutcarousel_image',\n new_name='banner_Abtimage',\n ),\n migrations.AddField(\n model_name='posthome',\n name='banner_serv',\n field=models.ImageField(default='', upload_to='images/'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.7299935221672058, "alphanum_fraction": 0.7430058717727661, "avg_line_length": 34.76744079589844, "blob_id": "ce07fd3b5ec4dce3d930a0cff7ed3d62b6ad487b", "content_id": "d5b8a38881485b4a5e8c230488cfd258e5999dc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1537, "license_type": "no_license", "max_line_length": 216, "num_lines": 43, "path": "/adminapp/forms.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from ckeditor.fields import RichTextField\nfrom django import forms\nfrom django.db.models import fields\nfrom django.forms import widgets\nfrom app.models import PostAbout, PostHome, PostService, PostVision\nfrom ckeditor.fields import RichTextField\n\n\nclass HomeForm(forms.ModelForm):\n class Meta:\n model = PostHome\n fields = ['banner_homeImage1','banner_homeImage2','banner_homeImage3','banner_review_image1','banner_review_image2','banner_review_image3']\n\n\n\n\nclass AboutForm(forms.ModelForm):\n class Meta:\n model = PostAbout\n fields = ['banner_Abtimage1','banner_Abtimage2','banner_Abtimage3','aboutheading','banner_carAboutImage1','banner_carAboutImage2','banner_carAboutImage3','banner_carAboutImage4','banner_carAboutImage5','Aboutbody']\n widgets = {\n 'aboutheading': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'Aboutbody': RichTextField()\n }\n\n\nclass VisionForm(forms.ModelForm):\n class Meta:\n model = PostVision\n fields = ['banner_Visimage1','banner_Visimage2','banner_Visimage3','Vision_heading', 'Visionbody']\n widgets = {\n 'Vision_heading': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'Visionbody': RichTextField()\n }\n\nclass ServiceForm(forms.ModelForm):\n class Meta:\n model = PostService\n fields = ['Service_heading','banner_serv1','banner_serv2','banner_serv3','Servicebody']\n widgets = {\n 'Service_heading': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'Servicebody': RichTextField()\n }" }, { "alpha_fraction": 0.5480928421020508, "alphanum_fraction": 0.578772783279419, "avg_line_length": 39.20000076293945, "blob_id": "f848f9b151106b519a57e0b6796ee0d27d43835e", "content_id": "1ce31d48b42e8c8d7b674d260dfed54a5383c1fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1206, "license_type": "no_license", "max_line_length": 114, "num_lines": 30, "path": "/app/migrations/0004_posthome.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2021-02-16 07:35\n\nimport ckeditor.fields\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0003_auto_20210213_1831'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='PostHome',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('banner_homeImage', models.ImageField(upload_to='images/')),\n ('banner_AboutImage', models.ImageField(upload_to='images/')),\n ('banner_Aboutcarousel_image', models.ImageField(upload_to='images/')),\n ('banner_review_image', models.ImageField(upload_to='images/')),\n ('About_heading', models.CharField(max_length=50)),\n ('Vision_heading', models.CharField(max_length=50)),\n ('Service_heading', models.CharField(max_length=50)),\n ('About_body', ckeditor.fields.RichTextField()),\n ('Vision_body', ckeditor.fields.RichTextField()),\n ('Service_body', ckeditor.fields.RichTextField()),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.4455924332141876, "alphanum_fraction": 0.450208842754364, "avg_line_length": 32.94776153564453, "blob_id": "ae5c0c4e9a951322ee293fb1fab7d98433c0fd63", "content_id": "eb0021c4eada46ed7941cd480e8bebe1cc938d68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 4549, "license_type": "no_license", "max_line_length": 102, "num_lines": 134, "path": "/app/templates/about.html", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %} {% load static %} {% block content %}<!--{% comment \"\" %}{% endcomment %}-->\n{% include 'banner.html' %}\n\n<div class=\"about_sec\">\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-md-6\">\n <div>\n <h3 class=\"main_heading\">ABOUT US</h3>\n </div>\n <p>\n Our whole purpose of <span>EDUCATION</span> is to turn our candidates\n into a successful achiever.\n </p>\n <p>\n We started as an educational counselling for needy students and our\n professional guidance greatly helped them in achieving academic\n excellence. Slowly our reputation grew among students and working\n professionals who had a desire for completing their education from\n where they had left. We helped them too and managed to get them\n admission in good universities and colleges! The effect was\n incredible. And now hundreds of students started approaching us and we\n thought what we needed was a broader and greater prospective.\n </p>\n <a href=\"#\" class=\"learn_more-button\">Learn More</a>\n </div>\n <div class=\"col-md-6\">\n <div class=\"about_us-slider\">\n <div\n id=\"carouselExampleIndicators\"\n class=\"carousel slide\"\n data-bs-ride=\"carousel\"\n >\n <ol class=\"carousel-indicators\">\n <li\n data-bs-target=\"#carouselExampleIndicators\"\n data-bs-slide-to=\"0\"\n class=\"active\"\n ></li>\n <li\n data-bs-target=\"#carouselExampleIndicators\"\n data-bs-slide-to=\"1\"\n ></li>\n <li\n data-bs-target=\"#carouselExampleIndicators\"\n data-bs-slide-to=\"2\"\n ></li>\n <li\n data-bs-target=\"#carouselExampleIndicators\"\n data-bs-slide-to=\"3\"\n ></li>\n <li\n data-bs-target=\"#carouselExampleIndicators\"\n data-bs-slide-to=\"4\"\n ></li>\n <li\n data-bs-target=\"#carouselExampleIndicators\"\n data-bs-slide-to=\"5\"\n ></li>\n <li\n data-bs-target=\"#carouselExampleIndicators\"\n data-bs-slide-to=\"6\"\n ></li>\n </ol>\n <!--inner-->\n <div class=\"carousel-inner\">\n <div class=\"carousel-item active\">\n {% for obj in object_list %}\n <img\n src=\"{{obj.banner_carAboutImage1.url}}\"\n class=\"d-block\"\n alt=\"about_banner-img\"\n />\n </div>\n <div class=\"carousel-item\">\n <img\n src=\"{{obj.banner_carAboutImage2.url}}\"\n class=\"d-block\"\n alt=\"about_banner-img\"\n />\n </div>\n <div class=\"carousel-item\">\n <img\n src=\"{{obj.banner_carAboutImage3.url}}\"\n class=\"d-block\"\n alt=\"about_banner-img\"\n />\n </div>\n <div class=\"carousel-item\">\n <img\n src=\"{{obj.banner_carAboutImage4.url}}\"\n class=\"d-block\"\n alt=\"about_banner-img\"\n />\n </div>\n <div class=\"carousel-item\">\n <img\n src=\"{{obj.banner_carAboutImage5.url}}\"\n class=\"d-block\"\n alt=\"about_banner-img\"\n />\n </div>\n <div class=\"carousel-item\">\n <img\n src=\"{{obj.banner_carAboutImage6.url}}\"\n class=\"d-block\"\n alt=\"about_banner-img\"\n />\n </div>\n <div class=\"carousel-item\">\n <img\n src=\"{{obj.banner_carAboutImage7.url}}\"\n class=\"d-block\"\n alt=\"about_banner-img\"\n />\n </div>\n </div>\n {% endfor %}\n <!--inner carasoul-->\n </div>\n </div>\n </div>\n </div>\n </div>\n</div>\n\n{% for obj in object_list %}\n<div class=\"container\">\n <h1 class=\"alert-primary\">{{obj.aboutheading|striptags }}</h1>\n <p class=\"mt-3\">{{obj.Aboutbody|striptags}}</p>\n</div>\n{% endfor %}\n<!---->\n{% endblock content %}\n" }, { "alpha_fraction": 0.5069929957389832, "alphanum_fraction": 0.5297203063964844, "avg_line_length": 27.600000381469727, "blob_id": "ac5e5dd58202f8d8d44d415d5ac763c8254645b7", "content_id": "16a4eae4881cd04728b803ad2e396a1d0b3deeb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 138, "num_lines": 40, "path": "/app/migrations/0002_auto_20210213_1714.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2021-02-13 11:44\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='customer',\n old_name='locality',\n new_name='address',\n ),\n migrations.RemoveField(\n model_name='customer',\n name='user',\n ),\n migrations.AddField(\n model_name='customer',\n name='email',\n field=models.EmailField(default='timezone.now', max_length=254),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='customer',\n name='message',\n field=models.TextField(default='-1'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='customer',\n name='target',\n field=models.CharField(choices=[('C', 'Candidate'), ('R', 'Referral'), ('BP', 'Business_Partner')], default=1, max_length=50),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.7514285445213318, "alphanum_fraction": 0.7639999985694885, "avg_line_length": 37.065216064453125, "blob_id": "8507d696f6313615a7745cab494ed87cc475802a", "content_id": "a1048da576dbe475789f5f3936dd16d8610c18c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1750, "license_type": "no_license", "max_line_length": 146, "num_lines": 46, "path": "/app/admin.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom . import models\nfrom .models import Customer, PostHome, PostAbout, PostService, PostVision, Student, Business, Refferal, quickuser\n\n# Register your models here.\[email protected](Customer)\nclass CustomerAdmin(admin.ModelAdmin):\n list_display = ['name','email','target','address','city','zipcode','state','message']\n\n\[email protected](PostHome)\nclass HomeAdmin(admin.ModelAdmin):\n list_display = ['banner_homeImage1','banner_homeImage2','banner_homeImage3','banner_review_image1','banner_review_image2','banner_review_image3']\n\n\[email protected](PostAbout)\nclass AboutAdmin(admin.ModelAdmin):\n list_display = ['banner_Abtimage1','banner_Abtimage2','banner_Abtimage3','aboutheading','banner_carAboutImage1','banner_carAboutImage2',\n 'banner_carAboutImage3','banner_carAboutImage4','banner_carAboutImage5','banner_carAboutImage6','banner_carAboutImage5','Aboutbody']\n\n\[email protected](PostService)\nclass ServiceAdmin(admin.ModelAdmin):\n list_display = ['Service_heading','banner_serv1','banner_serv2','banner_serv3','Servicebody']\n\n\[email protected](PostVision)\nclass VisionAdmin(admin.ModelAdmin):\n list_display = ['banner_Visimage1','banner_Visimage2','banner_Visimage3','Vision_heading','Visionbody']\n\n\[email protected](Student)\nclass StudentAdmin(admin.ModelAdmin):\n list_display = ['Name','Email','Mobile','Target','Address','Message']\n\[email protected](Business)\nclass BusinessAdmin(admin.ModelAdmin):\n list_display = ['Name','Email','Mobile','Target','Address','Message']\n\[email protected](Refferal)\nclass ReferralAdmin(admin.ModelAdmin):\n list_display = ['Name','Email','Mobile','Target','Address','Message']\n\[email protected](quickuser)\nclass quickAdmin(admin.ModelAdmin):\n list_display = ['name','email','message']" }, { "alpha_fraction": 0.5005605220794678, "alphanum_fraction": 0.5297085046768188, "avg_line_length": 37.78260803222656, "blob_id": "f12c18de2a189fef939dc585b91dedef00c0efd4", "content_id": "374a4799eb3f352e771366da522b0510971c9eea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1784, "license_type": "no_license", "max_line_length": 114, "num_lines": 46, "path": "/app/migrations/0009_business_refferal_student.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-02-20 05:27\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0008_auto_20210218_0414'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Business',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('businame', models.CharField(max_length=50)),\n ('busiemail', models.EmailField(max_length=254)),\n ('busimobile', models.IntegerField()),\n ('busiaddress', models.CharField(max_length=50)),\n ('busimsg', models.TextField()),\n ],\n ),\n migrations.CreateModel(\n name='Refferal',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('refname', models.CharField(max_length=50)),\n ('refemail', models.EmailField(max_length=254)),\n ('refmobile', models.IntegerField()),\n ('refaddress', models.CharField(max_length=50)),\n ('refmsg', models.TextField()),\n ],\n ),\n migrations.CreateModel(\n name='Student',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('stuname', models.CharField(max_length=50)),\n ('stuemail', models.EmailField(max_length=254)),\n ('stumobile', models.IntegerField()),\n ('stuaddress', models.CharField(max_length=50)),\n ('stumsg', models.TextField()),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.49065420031547546, "alphanum_fraction": 0.7102803587913513, "avg_line_length": 16.83333396911621, "blob_id": "67a0b1a1d516dd39f31e05385e8a91b14cb603b7", "content_id": "75439369035efd5a6e53ad77712dcc75982e8cfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 214, "license_type": "no_license", "max_line_length": 27, "num_lines": 12, "path": "/requirements.txt", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "asgiref==3.3.1\ncertifi==2020.12.5\ncloudinary==1.24.0\nDjango==3.1.7\ndjango-ckeditor==6.0.0\ndjango-js-asset==1.2.2\ndjangorestframework==3.12.2\npytz==2021.1\nsix==1.15.0\nsqlparse==0.4.1\nurllib3==1.26.3\nwaitress==1.4.4\n" }, { "alpha_fraction": 0.7385371327400208, "alphanum_fraction": 0.7385371327400208, "avg_line_length": 22.139240264892578, "blob_id": "6a8fc480ccacfd78ccbbffe53f4034bdf0ce198a", "content_id": "3de49246aacefdaf1ae52647be1f294ce9593c4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1832, "license_type": "no_license", "max_line_length": 88, "num_lines": 79, "path": "/app/views.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, HttpResponseRedirect\nfrom django.views.generic import CreateView, DetailView\nfrom django.views.generic import ListView\nfrom .forms import CustomerForm, RefferalForm, BusinessForm, CandidateForm\nfrom .models import Customer, PostAbout, PostHome,Student, Refferal, Business, quickuser\nfrom django.urls import reverse_lazy\n\nclass home(ListView):\n model = PostHome\n template_name = 'index.html'\n def get_success_url(self):\n return reverse_lazy('home')\n \ndef extract(request):\n \n nm = request.POST['name']\n em = request.POST['email']\n msg = request.POST['email-message']\n userinfo = quickuser(name=nm, email=em, message=msg)\n userinfo.save()\n return(request, 'index.html')\n\n\nclass referral(CreateView):\n model = Refferal\n form_class = RefferalForm\n template_name = 'referral.html'\n def get_success_url(self):\n return reverse_lazy('ref')\n\n\nclass student(CreateView):\n model = Student\n form_class = CandidateForm\n template_name = 'student.html'\n def get_success_url(self):\n return reverse_lazy('student')\n\n\nclass business(CreateView):\n model = Business\n form_class = BusinessForm\n template_name = 'business_partner.html'\n def get_success_url(self):\n return reverse_lazy('business')\n\n\nclass about(ListView):\n model = PostAbout\n template_name = 'about.html'\n def get_success_url(self):\n return reverse_lazy('about')\n\n\n\ndef vision(request):\n return render(request, 'vision.html')\n\n\ndef services(request):\n return render(request, 'service.html')\n\n\n# def contact(request):\n # return render(request, 'contact.html')\n\nclass contact(CreateView):\n model = Customer\n form_class = CustomerForm\n template_name = 'contact.html'\n\ndef join(request):\n return render(request, 'join.html')\n\n\nclass Query(CreateView):\n model = Customer\n form_class = CustomerForm\n template_name = 'form.html'\n\n \n " }, { "alpha_fraction": 0.7320452928543091, "alphanum_fraction": 0.7320452928543091, "avg_line_length": 22.617511749267578, "blob_id": "83500ce68f6390b6d26bdfdf56e65c87fb2de253", "content_id": "1a142ab2ea041d96c0f21e69244a0846d27f8b8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5124, "license_type": "no_license", "max_line_length": 106, "num_lines": 217, "path": "/adminapp/views.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from adminapp.forms import HomeForm\nfrom django.shortcuts import render, HttpResponseRedirect\nfrom django.views.generic import ListView, UpdateView, DetailView\nfrom django.views.generic.edit import CreateView, DeleteView\nfrom app.models import Customer, PostHome, PostAbout, PostService, PostVision, Student, Business, Refferal\nfrom app.forms import EditForm, RefferalForm, BusinessForm, CandidateForm\nfrom django.urls import reverse_lazy\nfrom .forms import PostHome, HomeForm, AboutForm, ServiceForm, VisionForm\n\n#admin start customer detail\n\nclass Admin(ListView):\n model = Customer\n template_name = 'admin.html'\n\nclass detailCustomer(DetailView):\n model = Customer\n template_name = 'detail.html'\n\n\nclass updateAdmin(UpdateView):\n model = Customer\n form_class = EditForm\n template_name = 'updateadmin.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\n\nclass DeleteAdmin(DeleteView):\n model = Customer\n template_name = 'deleteCustomer.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\n#admin end customer detail\n\n\n# start home\n\nclass HomePost(CreateView):\n model = PostHome\n form_class = HomeForm\n template_name = 'posthome.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\nclass Homeview(ListView):\n model = PostHome\n template_name = 'show/homeview.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\nclass Homeupdate(UpdateView):\n model = PostHome\n form_class = HomeForm\n template_name = 'updateshow/homeupdate.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\nclass Homedelete(DeleteView):\n model = PostHome\n template_name = 'deletepost/deletehome.html'\n success_url = 'admin'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\n# end home\n\n\n#start about\nclass AboutPost(CreateView):\n model = PostAbout\n form_class = VisionForm\n template_name = 'postabout.html'\n\nclass Aboutview(ListView):\n model = PostAbout\n template_name = 'show/aboutview.html'\n\nclass Aboutupdate(UpdateView):\n model = PostAbout\n form_class = AboutForm\n template_name = 'updateshow/aboutupdate.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n \n\nclass Aboutdelete(DeleteView):\n model = PostAbout\n template_name = 'deletepost/deleteabout.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\n#end about\n\n\n#start vision\nclass VisionPost(CreateView):\n model = PostVision\n form_class = VisionForm\n template_name = 'postvision.html'\n\nclass Visionview(ListView):\n model = PostVision\n template_name = 'show/visionview.html'\n\nclass Visionupdate(UpdateView):\n model = PostVision\n form_class = VisionForm\n template_name = 'updateshow/visionupdate.html'\n \n\nclass Visiondelete(DeleteView):\n model = PostVision\n template_name = 'deletepost/deletevision.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\n# end vision\n\n\n \nclass ServicePost(CreateView):\n model = PostService\n form_class = ServiceForm\n template_name = 'postservice.html'\n\n\nclass Serviceview(ListView):\n model = PostService\n template_name = 'show/serviceview.html'\n\nclass Serviceupdate(UpdateView):\n model = PostVision\n form_class = VisionForm\n template_name = 'updateshow/serviceupdate.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n \n\nclass Servicedelete(DeleteView):\n model = PostVision\n template_name = 'deletepost/deleteservice.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\n\n#student \n\nclass Studentview(ListView):\n model = Student\n template_name = 'candidate.html'\n\nclass Studentdelete(DeleteView):\n model = Student\n template_name = 'deletepost/deletestudent.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\nclass studentupdate(UpdateView):\n model = Student\n form_class = CandidateForm\n template_name = 'updateshow/studentupdate.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\n\n#end student\n\n#referral\n\n\nclass referralview(ListView):\n model = Refferal\n template_name = 'referralAdmin.html'\n\n\nclass Refferaldelete(DeleteView):\n model = Refferal\n template_name = 'deletepost/deleteReferral.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\nclass Refferalupdate(UpdateView):\n model = Refferal\n form_class = RefferalForm\n template_name = 'updateshow/updateref.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\nclass businessview(ListView):\n model = Business\n template_name = 'busiAdmin.html'\n\n\nclass Businessdelete(DeleteView):\n model = Business\n template_name = 'deletepost/deletebusiness.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\nclass Businessupdate(UpdateView):\n model = Business\n form_class = BusinessForm\n template_name = 'updateshow/businessupdate.html'\n def get_success_url(self):\n return reverse_lazy('dashboard')\n\n\n \n\ndef profile(request):\n return render(request, 'profile.html')\n\n\ndef setting(request):\n return render(request, 'setting.html')" }, { "alpha_fraction": 0.5713097453117371, "alphanum_fraction": 0.5935550928115845, "avg_line_length": 37.790321350097656, "blob_id": "c0ad78742b94f2ab085cbff88ebfdbcfe3e24d27", "content_id": "16aa90b65fa0c5c8a3f8ad065e9df63b5f76b316", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4810, "license_type": "no_license", "max_line_length": 90, "num_lines": 124, "path": "/app/migrations/0013_auto_20210222_0005.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-02-21 18:35\n\nimport cloudinary.models\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0012_quickuser'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='postabout',\n name='banner_Abtimage1',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postabout',\n name='banner_Abtimage2',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postabout',\n name='banner_Abtimage3',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postabout',\n name='banner_carAboutImage1',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postabout',\n name='banner_carAboutImage2',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postabout',\n name='banner_carAboutImage3',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postabout',\n name='banner_carAboutImage4',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postabout',\n name='banner_carAboutImage5',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postabout',\n name='banner_carAboutImage6',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postabout',\n name='banner_carAboutImage7',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='posthome',\n name='banner_homeImage1',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='posthome',\n name='banner_homeImage2',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='posthome',\n name='banner_homeImage3',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='posthome',\n name='banner_review_image1',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='posthome',\n name='banner_review_image2',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='posthome',\n name='banner_review_image3',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postservice',\n name='banner_serv1',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postservice',\n name='banner_serv2',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postservice',\n name='banner_serv3',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postvision',\n name='banner_Visimage1',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postvision',\n name='banner_Visimage2',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n migrations.AlterField(\n model_name='postvision',\n name='banner_Visimage3',\n field=cloudinary.models.CloudinaryField(max_length=255, verbose_name='image'),\n ),\n ]\n" }, { "alpha_fraction": 0.5483871102333069, "alphanum_fraction": 0.5771889686584473, "avg_line_length": 30, "blob_id": "4a8fbc69efe00a7486cbeaf1f7e403b87b17a860", "content_id": "0efb2d70d982ec4c82482667cc57adedd53372a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "no_license", "max_line_length": 116, "num_lines": 28, "path": "/app/migrations/0010_auto_20210221_1223.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-02-21 06:53\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0009_business_refferal_student'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='business',\n name='busi_grp',\n field=models.CharField(choices=[('Business_Partner', 'Business_Partner')], default=None, max_length=50),\n ),\n migrations.AddField(\n model_name='refferal',\n name='ref_grp',\n field=models.CharField(choices=[('Referral', 'Referral')], default=None, max_length=50),\n ),\n migrations.AddField(\n model_name='student',\n name='candi_grp',\n field=models.CharField(choices=[('Candidate', 'Candidate')], default=None, max_length=50),\n ),\n ]\n" }, { "alpha_fraction": 0.5346938967704773, "alphanum_fraction": 0.6020408272743225, "avg_line_length": 26.22222137451172, "blob_id": "68ecd3f6b4c91ebfdeb8be5f31416d819814ab90", "content_id": "1bebdfb0e8d91e0766fee76b9016e8e28e12334c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 490, "license_type": "no_license", "max_line_length": 156, "num_lines": 18, "path": "/app/migrations/0003_auto_20210213_1831.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2021-02-13 13:01\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0002_auto_20210213_1714'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='customer',\n name='target',\n field=models.CharField(choices=[('Candidate', 'Candidate'), ('Referral', 'Referral'), ('Business_Partner', 'Business_Partner')], max_length=50),\n ),\n ]\n" }, { "alpha_fraction": 0.5584415793418884, "alphanum_fraction": 0.5584415793418884, "avg_line_length": 76, "blob_id": "b85bc4b72fcc6954fefa6c660481bd7939832465", "content_id": "d08cdbe31a5da800fd82dba337f7f033332f48fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 154, "license_type": "no_license", "max_line_length": 102, "num_lines": 2, "path": "/app/templates/join.html", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %} {% load static %} {% block content %}<!--{% comment \"\" %}{% endcomment %}-->\n{% include 'banner.html' %} {% endblock content %}\n" }, { "alpha_fraction": 0.7560975551605225, "alphanum_fraction": 0.7729184031486511, "avg_line_length": 36.1875, "blob_id": "8cec7d4215f7ec4a71e8157932755d92691a0659", "content_id": "4027192d746c71323b06a8e60dab9539bc98a2b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1189, "license_type": "no_license", "max_line_length": 216, "num_lines": 32, "path": "/app/api/serializers.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from app.models import Customer, PostHome, PostAbout, PostService, PostVision\nfrom rest_framework import serializers\n\n\n\nclass CustomerSerializer(serializers.ModelSerializer):\n class Meta:\n model = Customer\n fields = ['name','email','target','address','city','zipcode','state','message']\n\n\nclass HomeSerializer(serializers.ModelSerializer):\n class Meta:\n model = PostHome\n fields = ['banner_homeImage1','banner_homeImage2','banner_homeImage3','banner_review_image1','banner_review_image2','banner_review_image3']\n\nclass AboutSerializer(serializers.ModelSerializer):\n class Meta:\n model = PostAbout\n fields = ['banner_Abtimage1','banner_Abtimage2','banner_Abtimage3','aboutheading','banner_carAboutImage1','banner_carAboutImage2','banner_carAboutImage3','banner_carAboutImage4','banner_carAboutImage5','Aboutbody']\n\n\nclass VisionSerializer(serializers.ModelSerializer):\n class Meta:\n model = PostVision\n fields = ['banner_Visimage1','banner_Visimage2','banner_Visimage3','Vision_heading', 'Visionbody']\n\n\nclass ServiceSerializer(serializers.ModelSerializer):\n class Meta:\n model = PostService\n fields = ['Service_heading','banner_serv1','banner_serv2','banner_serv3','Servicebody']" }, { "alpha_fraction": 0.6899288296699524, "alphanum_fraction": 0.6899288296699524, "avg_line_length": 49.76388931274414, "blob_id": "bb783a3f2c9ecba726aed061f99c2e42d8133a42", "content_id": "c414f148ef9a4a66cb63763ec95d0fe598bd618b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3654, "license_type": "no_license", "max_line_length": 114, "num_lines": 72, "path": "/app/forms.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.db.models import fields\nfrom django.forms import widgets\nfrom .models import Customer, Student, Business, Refferal\n\nclass CustomerForm(forms.ModelForm):\n class Meta:\n model = Customer\n fields = ['name','email','target','address','city','zipcode','state','message']\n widgets = {\n 'name': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'email': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your email'}),\n 'target': forms.Select(attrs={'class':'form-control'}),\n 'address': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your address'}),\n 'city': forms.TextInput(attrs={'class':'form-control','placeholder':'enter your city name'}),\n 'zipcode': forms.NumberInput(attrs={'class':'form-control','placeholder':'enter your zipcode'}),\n 'state':forms.Select(attrs={'class':'form-control','placeholder':'enter your state'}),\n 'message':forms.Textarea(attrs={'class':'form-control','placeholder':'write your message here'})\n }\n\n\nclass EditForm(forms.ModelForm):\n class Meta:\n model = Customer\n fields = ['name','email','target','address']\n widgets = {\n 'name': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'email': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your email'}),\n 'target': forms.Select(attrs={'class':'form-control'}),\n 'address': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your address'}),\n }\n\nclass CandidateForm(forms.ModelForm):\n class Meta:\n model = Student\n fields = ['Name','Email','Mobile','Target','Address','Message']\n widgets = {\n 'Name': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'Email': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'Mobile': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your mobile or Whatsapp number'}),\n 'Target': forms.Select(attrs={'class':'form-control'}),\n 'Address': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your address'}),\n 'Message' : forms.Textarea(attrs={'class':'form-control','placeholder':'Enter your Message'})\n }\n \n\nclass BusinessForm(forms.ModelForm):\n class Meta:\n model = Business\n fields = ['Name','Email','Mobile','Target','Address','Message']\n widgets = {\n 'Name': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'Email': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'Mobile': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your mobile or Whatsapp number'}),\n 'Target': forms.Select(attrs={'class':'form-control'}),\n 'Address': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your address'}),\n 'Message' : forms.Textarea(attrs={'class':'form-control','placeholder':'Enter your Message'})\n }\n\n\nclass RefferalForm(forms.ModelForm):\n class Meta:\n model = Refferal\n fields = ['Name','Email','Mobile','Target','Address','Message']\n widgets = {\n 'Name': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'Email': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your name'}),\n 'Mobile': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your mobile or Whatsapp number'}),\n 'Target': forms.Select(attrs={'class':'form-control'}),\n 'Address': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter your address'}),\n 'Message' : forms.Textarea(attrs={'class':'form-control','placeholder':'Enter your Message'})\n }" }, { "alpha_fraction": 0.8233917951583862, "alphanum_fraction": 0.8233917951583862, "avg_line_length": 30.66666603088379, "blob_id": "2eeeb73c4b941055c2710ccfedd711d6a123174a", "content_id": "3309e326a1ef0900d74f3ad81f80b3acdf780617", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 855, "license_type": "no_license", "max_line_length": 120, "num_lines": 27, "path": "/app/api/views.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from app.models import Customer, PostHome, PostAbout, PostService, PostVision\nfrom app.api.serializers import CustomerSerializer, HomeSerializer, AboutSerializer, ServiceSerializer, VisionSerializer\nfrom rest_framework import viewsets\nfrom rest_framework.views import APIView\n\nclass CustomerView(viewsets.ModelViewSet):\n queryset = Customer.objects.all()\n serializer_class = CustomerSerializer\n\nclass AboutView(viewsets.ModelViewSet):\n queryset = PostAbout.objects.all()\n serializer_class = AboutSerializer\n\n\nclass HomeView(viewsets.ModelViewSet):\n queryset = PostHome.objects.all()\n serializer_class = HomeSerializer\n\n\nclass ServiceView(viewsets.ModelViewSet):\n queryset = PostService.objects.all()\n serializer_class = ServiceSerializer\n\n\nclass VisionView(viewsets.ModelViewSet):\n queryset = PostVision.objects.all()\n serializer_class = VisionSerializer\n" }, { "alpha_fraction": 0.5348936915397644, "alphanum_fraction": 0.5458449721336365, "avg_line_length": 32.99270248413086, "blob_id": "3f8d5f3e98ebfac47256b587a5f45563c154f3ee", "content_id": "ce7543fadc18e13fe248083be8d0cedab0d0cd4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4657, "license_type": "no_license", "max_line_length": 71, "num_lines": 137, "path": "/app/migrations/0007_auto_20210218_0345.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.1 on 2021-02-17 22:15\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0006_auto_20210216_1410'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='postabout',\n name='banner_Abtimage',\n ),\n migrations.RemoveField(\n model_name='postabout',\n name='banner_carAboutImage',\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='banner_homeImage',\n ),\n migrations.RemoveField(\n model_name='posthome',\n name='banner_review_image',\n ),\n migrations.RemoveField(\n model_name='postservice',\n name='banner_serv',\n ),\n migrations.RemoveField(\n model_name='postvision',\n name='banner_Visimage',\n ),\n migrations.AddField(\n model_name='postabout',\n name='banner_Abtimage1',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postabout',\n name='banner_Abtimage2',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postabout',\n name='banner_Abtimage3',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postabout',\n name='banner_carAboutImage1',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postabout',\n name='banner_carAboutImage2',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postabout',\n name='banner_carAboutImage3',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postabout',\n name='banner_carAboutImage4',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postabout',\n name='banner_carAboutImage5',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='posthome',\n name='banner_homeImage1',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='posthome',\n name='banner_homeImage2',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='posthome',\n name='banner_homeImage3',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='posthome',\n name='banner_review_image1',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='posthome',\n name='banner_review_image2',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='posthome',\n name='banner_review_image3',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postservice',\n name='banner_serv1',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postservice',\n name='banner_serv2',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postservice',\n name='banner_serv3',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postvision',\n name='banner_Visimage1',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postvision',\n name='banner_Visimage2',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n migrations.AddField(\n model_name='postvision',\n name='banner_Visimage3',\n field=models.ImageField(default=None, upload_to='images/'),\n ),\n ]\n" }, { "alpha_fraction": 0.46520015597343445, "alphanum_fraction": 0.4763793647289276, "avg_line_length": 25.922330856323242, "blob_id": "afe666de18526838261286c31e91ac693c0b9369", "content_id": "18687f8ffb05e97e8c88bbd75bc274bbab894c7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2773, "license_type": "no_license", "max_line_length": 47, "num_lines": 103, "path": "/app/migrations/0011_auto_20210221_1427.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-02-21 08:57\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0010_auto_20210221_1223'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='business',\n old_name='busiaddress',\n new_name='Address',\n ),\n migrations.RenameField(\n model_name='business',\n old_name='busiemail',\n new_name='Email',\n ),\n migrations.RenameField(\n model_name='business',\n old_name='busimsg',\n new_name='Message',\n ),\n migrations.RenameField(\n model_name='business',\n old_name='busimobile',\n new_name='Mobile',\n ),\n migrations.RenameField(\n model_name='business',\n old_name='businame',\n new_name='Name',\n ),\n migrations.RenameField(\n model_name='business',\n old_name='busi_grp',\n new_name='Target',\n ),\n migrations.RenameField(\n model_name='refferal',\n old_name='refaddress',\n new_name='Address',\n ),\n migrations.RenameField(\n model_name='refferal',\n old_name='refemail',\n new_name='Email',\n ),\n migrations.RenameField(\n model_name='refferal',\n old_name='refmsg',\n new_name='Message',\n ),\n migrations.RenameField(\n model_name='refferal',\n old_name='refmobile',\n new_name='Mobile',\n ),\n migrations.RenameField(\n model_name='refferal',\n old_name='refname',\n new_name='Name',\n ),\n migrations.RenameField(\n model_name='refferal',\n old_name='ref_grp',\n new_name='Target',\n ),\n migrations.RenameField(\n model_name='student',\n old_name='stuaddress',\n new_name='Address',\n ),\n migrations.RenameField(\n model_name='student',\n old_name='stuemail',\n new_name='Email',\n ),\n migrations.RenameField(\n model_name='student',\n old_name='stumsg',\n new_name='Message',\n ),\n migrations.RenameField(\n model_name='student',\n old_name='stumobile',\n new_name='Mobile',\n ),\n migrations.RenameField(\n model_name='student',\n old_name='stuname',\n new_name='Name',\n ),\n migrations.RenameField(\n model_name='student',\n old_name='candi_grp',\n new_name='Target',\n ),\n ]\n" }, { "alpha_fraction": 0.7184693217277527, "alphanum_fraction": 0.7184693217277527, "avg_line_length": 63.025001525878906, "blob_id": "57eff37de3f087ba0a0298bf616b439bf3e5b10c", "content_id": "da6ef54313101da414b9db807a05a8c68bbbe8ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2561, "license_type": "no_license", "max_line_length": 132, "num_lines": 40, "path": "/adminapp/urls.py", "repo_name": "aryanation12/aimlay", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n\n path('admin/', views.Admin.as_view(), name='dashboard'),\n path('homepost/', views.HomePost.as_view(), name='homepost'),\n path('visionpost/', views.VisionPost.as_view(), name='visionpost'),\n path('aboutpost/', views.AboutPost.as_view(), name='aboutpost'),\n path('servicepost/', views.ServicePost.as_view(), name='servicepost'),\n path('homeview/', views.Homeview.as_view(), name='homeview'),\n path('updatehome/<int:pk>', views.Homeupdate.as_view(), name='updatehome'),\n path('deletehome/<int:pk>', views.Homedelete.as_view(), name='deletehome'),\n path('aboutview/', views.Aboutview.as_view(), name='aboutview'),\n path('updateabout/<int:pk>', views.Aboutupdate.as_view(), name='updateabout'),\n path('deleteabout/<int:pk>', views.Aboutdelete.as_view(), name='deleteabout'),\n path('visionview/', views.Visionview.as_view(), name='visionview'),\n path('updatevision/<int:pk>', views.Visionupdate.as_view(), name='updatevision'),\n path('deletevision/<int:pk>', views.Visiondelete.as_view(), name='deletevision'),\n path('serviceview/', views.Serviceview.as_view(), name='serviceview'),\n path('updateservice/<int:pk>', views.Serviceupdate.as_view(), name='updateservice'),\n path('deleteservice/<int:pk>', views.Servicedelete.as_view(), name='deleteservice'),\n path('busiAdmin/', views.businessview.as_view(), name='busiAdmin'),\n path('deletebusiness/<int:pk>', views.Businessdelete.as_view(), name='deletebusiness'),\n path('updatebusiness/<int:pk>', views.Businessupdate.as_view(), name='updatebusiness'),\n path('referral/', views.referralview.as_view(), name='referral'),\n path('deletereferral/<int:pk>', views.referralview.as_view(), name='deleteref'),\n path('updatereferral/<int:pk>', views.referralview.as_view(), name='updateref'),\n path('candidate/', views.Studentview.as_view(), name='candidate'),\n path('deletestudent/<int:pk>', views.Studentdelete.as_view(), name='deletestudent'),\n path('updatestudent/<int:pk>', views.studentupdate.as_view(), name='updatestudent'),\n path('pro/', views.profile, name='profile'),\n path('sets/', views.setting, name='setting'),\n path('update/<int:pk>', views.updateAdmin.as_view(), name='update'),\n path('detailCustomer/<int:pk>', views.detailCustomer.as_view(), name='detailCustomer'),\n path('deleteCustomer/<int:pk>', views.DeleteAdmin.as_view(), name='detelecustomer'),\n path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change-password.html'), name='reset_password'),\n\n]\n" } ]
26
artykbayevk/ROS_Turtledraw_pkg
https://github.com/artykbayevk/ROS_Turtledraw_pkg
eacaaf9383abbd9cad06d3b8c43310736b226712
e9b5376d0bda8b5f7a40599f561d575bfc4af328
e774c8d32ac1638a75bfb8ea798078bf06b4fce5
refs/heads/master
2020-05-05T13:41:03.548480
2019-04-08T08:00:44
2019-04-08T08:00:44
180,088,876
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.46385541558265686, "alphanum_fraction": 0.46987950801849365, "avg_line_length": 22.85714340209961, "blob_id": "a23ecb59fa3f6fd54aecdcaa573b6a775d731d91", "content_id": "55c418a2e2814c2238c6f052249cd07cf8255e1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 38, "num_lines": 7, "path": "/src/Pose.py", "repo_name": "artykbayevk/ROS_Turtledraw_pkg", "src_encoding": "UTF-8", "text": "class Pose():\n def __init__(self, x, y, theta=0):\n self.theta = theta\n self.y = y\n self.x = x\n def __repr__(self):\n return str(self)" }, { "alpha_fraction": 0.6436619758605957, "alphanum_fraction": 0.6549295783042908, "avg_line_length": 36.3684196472168, "blob_id": "117e1d4fbbbbc3fccf57e0299bec1e474024567d", "content_id": "29ea0b964dcf0a1f6c40ef50a9ec63bf3f52f8af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2840, "license_type": "no_license", "max_line_length": 119, "num_lines": 76, "path": "/src/util.py", "repo_name": "artykbayevk/ROS_Turtledraw_pkg", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport math\nimport rospy\nfrom Pose import Pose\n\n\ndef draw(points, func_dict):\n func_dict[\"pen\"](False)\n move_forward(Pose(x=points[0].x, y=points[0].y), 1, 1, 0.1, func_dict)\n\n func_dict[\"pen\"](True)\n for point in points[1:]:\n move_forward(Pose(x=point.x, y=point.y), 1, 1, 0.1, func_dict)\n\n func_dict[\"log\"](\"Finished!\")\n\ndef move_forward(target, move_speed, spin_speed, pos_tolerance, func_dict):\n target_theta = _angle_between_points(func_dict[\"current\"](), target)\n while not _are_angles_equal(func_dict[\"current\"]().theta, target_theta, _deg_to_rad(5)):\n spin_func(spin_speed, _is_spin_clockwise(func_dict[\"current\"]().theta, target_theta), func_dict)\n rospy.Rate(10).sleep\n stop_method(func_dict)\n _move(target, move_speed, spin_speed, pos_tolerance, func_dict)\n stop_method(func_dict)\n\ndef _move(target, move_speed, spin_speed, pos_tolerance, func_dict):\n while not _are_points_equal(func_dict[\"current\"](), target, pos_tolerance):\n target_theta = _angle_between_points(func_dict[\"current\"](), target)\n angle_correction = _min_angle_between_angles(func_dict[\"current\"]().theta, target_theta)\n correction_spin_speed = _clamp(angle_correction, -spin_speed, spin_speed)\n func_dict[\"move\"](move_speed, correction_spin_speed)\n rospy.Rate(10).sleep\n\ndef spin_func(speed, clockwise, func_dict):\n func_dict[\"move\"](0, speed * (-1 if clockwise else 1))\n\ndef stop_method(func_dict):\n func_dict[\"move\"](0, 0)\n\n\ndef _angle_between_points(point_a, point_b):\n return math.atan2((point_b.y - point_a.y), (point_b.x - point_a.x))\n\ndef _min_angle_between_angles(angle_a, angle_b):\n angle_a = _normalize_rad(angle_a)\n angle_b = _normalize_rad(angle_b)\n\n possible_angle_as = [angle_a - 2 * math.pi, angle_a, angle_a + 2 * math.pi]\n angle_differences = [angle_b - possible_angle_a for possible_angle_a in possible_angle_as]\n\n min_abs_diff, idx = min((abs(diff), idx) for (idx, diff) in enumerate(angle_differences))\n return angle_differences[idx]\n\ndef _is_spin_clockwise(current_angle, target_angle):\n return _min_angle_between_angles(current_angle, target_angle) < 0\n\ndef _are_points_equal(point_a, point_b, tolerance):\n return math.sqrt((point_a.x - point_b.x) ** 2 + (point_a.y - point_b.y) ** 2) < tolerance\n\ndef _are_angles_equal(angle_a, angle_b, tolerance):\n return (abs(angle_a - angle_b) < tolerance) or (abs(_normalize_rad(angle_a) - _normalize_rad(angle_b)) < tolerance)\n\ndef _normalize_rad(rad):\n while rad > math.pi:\n rad -= 2 * math.pi\n while rad <= -math.pi:\n rad += 2 * math.pi\n return rad\n\ndef _deg_to_rad(deg):\n return math.pi * deg / 180\n\ndef _clamp(val, min_val, max_val):\n if min_val > max_val: raise ValueError\n return max(min_val, min(val, max_val))\n" }, { "alpha_fraction": 0.7664233446121216, "alphanum_fraction": 0.7883211970329285, "avg_line_length": 16.125, "blob_id": "97a691955221b517ef8cd175d2fdea5b91dbfbff", "content_id": "a757c7badca4628e68d283095e67925c519489c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 137, "license_type": "no_license", "max_line_length": 49, "num_lines": 8, "path": "/README.MD", "repo_name": "artykbayevk/ROS_Turtledraw_pkg", "src_encoding": "UTF-8", "text": "In terminal 1:\nroscore\n\nIn terminal 2:\nrosrun turtlesim turtlesim_node\n\nIn terminal 3:\nrosrun artykbayev_temir main.py --figure rect.txt\n" }, { "alpha_fraction": 0.631361186504364, "alphanum_fraction": 0.6487380862236023, "avg_line_length": 27.104650497436523, "blob_id": "7adddf47c8e2f414191315804c6f2463884ff52e", "content_id": "9d0744b398869a6119e0bbf42257807127945a8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2417, "license_type": "no_license", "max_line_length": 127, "num_lines": 86, "path": "/src/main.py", "repo_name": "artykbayevk/ROS_Turtledraw_pkg", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os\nimport sys\nimport time\nimport util\nimport rospy\nimport argparse\nfrom math import pi\nfrom random import random\nfrom functools import partial\nfrom std_msgs.msg import Bool\nfrom turtlesim.msg import Pose\nfrom std_srvs.srv import Empty\nfrom geometry_msgs.msg import Twist, Point\nfrom turtlesim.srv import Kill, Spawn, SetPen\n\npositions = {}\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--file\", help=\"file of element\")\n\n args = vars(parser.parse_args())\n\n with open(args[\"file\"], \"r\") as f:\n lines = f.readlines()\n coords = []\n for line in lines:\n coords.append([float(i) for i in line.split(\",\")])\n\n\n points = []\n for coord in coords:\n points.append(Point(x=transform_coord(coord[0]), y=transform_coord(coord[1])))\n\n\n rospy.init_node(\"turtle_draw\")\n rospy.ServiceProxy(\"/reset\", Empty)()\n rospy.ServiceProxy(\"/kill\", Kill)(\"turtle1\")\n\n\n turtle_name = rospy.ServiceProxy(\"/spawn\", Spawn)(random() * 11, random() * 11, random() * 2 * pi, \"\").name\n\n subscribe_(turtle_name)\n\n func_dict = {\n \"log\" : lambda s: rospy.loginfo(\"[%s] %s\" % (turtle_name, s)),\n \"pen\" : partial(set_pen_on_off, set_pen=rospy.ServiceProxy(\"/%s/set_pen\" % turtle_name, SetPen)),\n \"move\" : partial(move_turtle, pub=rospy.Publisher(\"/%s/cmd_vel\" % turtle_name, Twist, queue_size=10)),\n \"current\" : partial(get_turtle_pose, turtle_name)\n }\n\n func_dict[\"pen\"](True)\n\n util.draw(points, func_dict)\n\ndef subscribe_(turtle_name):\n rospy.Subscriber(\"/%s/pose\" % turtle_name, Pose, partial(new_pose_callback, turtle_name=turtle_name))\n\n while turtle_name not in positions: # We need to sleep for a bit to let the subscriber fetch the current pose at least once\n time.sleep(0)\n\ndef new_pose_callback(pose, turtle_name):\n global positions\n positions[turtle_name] = pose\n\n\ndef get_turtle_pose(turtle_name):\n pose = positions[turtle_name]\n return util.Pose(pose.x, pose.y, pose.theta)\n\ndef move_turtle(linear_speed, angular_speed, pub):\n pub.publish(Twist(linear=Point(linear_speed, 0, 0), angular=Point(0, 0, angular_speed)))\n\n\ndef set_pen_on_off(on, set_pen):\n if on:\n set_pen(255, 255, 255, 3, 0) # On, white, width of 3\n else:\n set_pen(255, 255, 255, 3, 1) # Off\n\ndef transform_coord(coord):\n return ((coord + 1) / 2) * 11\n\nmain()\n" } ]
4
Mohamed-Albakosh/The-Tech-Academy-Python-Coding-Projects
https://github.com/Mohamed-Albakosh/The-Tech-Academy-Python-Coding-Projects
c1e82d1a301e52180b81219ac679dcad5796924c
f567af1ee10b15d7c9f31baad0cbe4b36c9ddf40
b4d2e1d2520f920aa17a5677f82aff26ec238f5e
refs/heads/master
2023-03-09T16:39:31.222118
2020-05-08T00:38:07
2020-05-08T00:38:07
247,150,377
0
0
null
2020-03-13T19:48:02
2020-05-08T00:39:33
2023-03-03T07:46:17
JavaScript
[ { "alpha_fraction": 0.5220938324928284, "alphanum_fraction": 0.5220938324928284, "avg_line_length": 31.711111068725586, "blob_id": "d8462eb21b96d229ae8e19fa16069787a0a470be", "content_id": "978e328fbb05a8cc9bca6005445c28e67e5847e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1473, "license_type": "no_license", "max_line_length": 138, "num_lines": 45, "path": "/CarInsurance/CarInsurance/Controllers/InsureeController.cs", "repo_name": "Mohamed-Albakosh/The-Tech-Academy-Python-Coding-Projects", "src_encoding": "UTF-8", "text": "using CarInsurance.Models;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace CarInsurance.Controllers\n{\n public class InsureeController : Controller\n {\n // public ActionResult Index()\n // {\n // return View();\n // }\n //GET: Admin\n [HttpPost]\n public ActionResult Index(string firstName, string lastName, string emailAddress,DateTime dateOfBirth,int carYear, string carMake,\n string carModel,bool dUI,int speedingTickets, bool CoverageType,decimal quote)\n {\n \n\n using (InsuranceEntities db = new InsuranceEntities())\n {\n var insure = new Table();\n insure.FirstName = firstName;\n insure.LastName = lastName;\n insure.EmailAddress = emailAddress;\n insure.DateOfBirth = dateOfBirth;\n insure.CarYear = carYear;\n insure.CarMake = carMake;\n insure.CarModel = carModel;\n insure.DUI = dUI;\n insure.SpeedingTickets = speedingTickets;\n insure.CoverageType = CoverageType;\n insure.Quote = quote;\n\n db.Tables.Add(insure);\n db.SaveChanges();\n }\n return View();\n }\n \n }\n}" }, { "alpha_fraction": 0.5579965114593506, "alphanum_fraction": 0.5641476511955261, "avg_line_length": 21.19607925415039, "blob_id": "d677c2fbf9780b021ca4748f86b8e30a0bbf06ab", "content_id": "ec9c17e39c8d66ae9df8b48fcf37e203905eee56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1138, "license_type": "no_license", "max_line_length": 63, "num_lines": 51, "path": "/database_assignment.py", "repo_name": "Mohamed-Albakosh/The-Tech-Academy-Python-Coding-Projects", "src_encoding": "UTF-8", "text": "import sqlite3\n\nconn = sqlite3.connect('db_files.db')\n\nwith conn:\n cur = conn.cursor()\n cur.execute(\"CREATE TABLE IF NOT EXISTS tbl_Files(\\\n ID INTEGER PRIMARY KEY AUTOINCREMENT,\\\n file_Name TEXT\\\n )\")\n conn.commit()\nconn.close()\n\nfileList = ('information.docx','Hello.txt','myImage.png', \\\n 'myMovie.mpg','World.txt','data.pdf','myPhoto.jpg')\nlist_str = []\n\nfor file in fileList:\n str=file.split('.')\n if str[1] == 'txt':\n str='.'.join(str)\n list_str.append(str)\nprint(list_str) \n\n\n\n\n\n \nconn = sqlite3.connect('db_files.db')\nwith conn:\n cur = conn.cursor()\n cur.execute(\"INSERT INTO tbl_Files(file_Name) VALUES (?)\",\\\n (list_str[0],))\n cur.execute(\"INSERT INTO tbl_Files(file_Name) VALUES (?)\",\\\n (list_str[1],))\n conn.commit()\nconn.close()\n \n \n\n\nconn = sqlite3.connect('db_files.db')\n\nwith conn:\n cur = conn.cursor()\n cur.execute(\"SELECT file_Name FROM tbl_Files\")\n varPerson = cur.fetchall()\n for item in varPerson:\n msg =\"File Name:{}\\n \".format(item)\n print(msg)\n\n \n" }, { "alpha_fraction": 0.681347131729126, "alphanum_fraction": 0.681347131729126, "avg_line_length": 20.44444465637207, "blob_id": "82e1c2a1b7b743e9d22ac00a3441d13330265dc0", "content_id": "058980a9fc8a757a282d1c77bc5ac9f034bcc25c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 386, "license_type": "no_license", "max_line_length": 42, "num_lines": 18, "path": "/fileIO.py", "repo_name": "Mohamed-Albakosh/The-Tech-Academy-Python-Coding-Projects", "src_encoding": "UTF-8", "text": "import os\n\nfname = 'Hello.exe'\n\nfpath = 'C:\\\\Users\\\\Mohamed\\\\Desktop\\\\A\\\\'\n\nabPath = os.path.join(fpath,fname)\nprint(abPath)\nlistPath= os.listdir(fpath)\nprint(listPath)\ntimePath=os.path.getmtime(fpath)\nprint(timePath)\n\nfor file in os.listdir(fpath):\n if file.endswith(\".txt\"):\n print(os.path.join(fpath, file))\n timePath=os.path.getmtime(fpath)\n print(timePath)\n" }, { "alpha_fraction": 0.5830048322677612, "alphanum_fraction": 0.6206745505332947, "avg_line_length": 34.671875, "blob_id": "4ec87d9a6ff1ea588e483609cc378ade956785b0", "content_id": "9651cbc32d2055db461a9e5c093f9c3b831362cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2283, "license_type": "no_license", "max_line_length": 130, "num_lines": 64, "path": "/GUI_askdirectory.py", "repo_name": "Mohamed-Albakosh/The-Tech-Academy-Python-Coding-Projects", "src_encoding": "UTF-8", "text": "import tkinter\nfrom tkinter import *\nimport tkinter as tk\nfrom tkinter import filedialog\nimport os\n\nclass ParentWindow(Frame):\n def __init__ (self,master):\n Frame.__init__ (self)\n\n self.master = master\n self.master.resizable(width=False, height=False)\n self.master.geometry('{}x{}'.format(700,300))\n self.master.title('Learning Tkinter!')\n self.master.config(bg='lightgray')\n \n self.vardirectory = StringVar()\n self.varLdirectory = StringVar()\n \n self.lblDisplay =Label(self.master,text='', font=(\"Helvetica\", 16), fg='black', bg='lightgray')\n self.lblDisplay.grid(row=3,column=1,padx=(30,0),pady=(30,0))\n\n\n self.txtFdirectory =Entry(self.master,text=self.vardirectory,width=40, font=(\"Helvetica\", 16), fg='black', bg='lightblue')\n self.txtFdirectory.grid(row=0,column=1,columnspan=2,padx=(30,0),pady=(30,0),sticky=N+E)\n\n self.lbldirectory =Label(self.master,text='',width=40,font=(\"Helvetica\", 16), fg='black', bg='lightgray')\n self.lbldirectory.grid(row=1,column=1,columnspan=2,padx=(30,0),pady=(30,0))\n\n \n self.btnFName =Button(self.master,text='Dirctory', width=15, height=2, command='')\n self.btnFName.grid(row=0,column=0,padx=(30,0),pady=(30,0))\n\n self.lblfiles =Label(self.master,text='Files:', width=15, fg='black', bg='lightgray')\n self.lblfiles.grid(row=1,column=0,padx=(30,0),pady=(30,0))\n \n self.btnDirectory = Button(self.master, text = \"Check for Dirctory\", width=15, height=2, command=self.Dirctory)\n self.btnDirectory.grid(row=2, column=0, padx=(30,0),pady=(30,0))\n\n self.btnCancel = Button(self.master, text = \"Close Program\", width=15, height=2, command=self.cancel)\n self.btnCancel.grid(row=2, column=2, padx=(30,0),pady=(30,0), sticky=SE)\n\n \n def Dirctory (self):\n #fn = self.varFName.get()\n fpath =filedialog.askdirectory()\n listPath= os.listdir(fpath)\n print(fpath)\n self.lbldirectory.config(text=listPath)\n self.txtFdirectory.insert(0,fpath)\n \n def cancel (self):\n self.master.destroy()\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n root = Tk()\n App = ParentWindow(root)\n root.mainloop()\n" }, { "alpha_fraction": 0.5643431544303894, "alphanum_fraction": 0.5959785580635071, "avg_line_length": 38.26315689086914, "blob_id": "6f1a7909c919462a2b0356e6a2bbf140e7f13777", "content_id": "9d369c52b385b30de99da41e4060ccbd45b46684", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7460, "license_type": "no_license", "max_line_length": 126, "num_lines": 190, "path": "/database_GUI.py", "repo_name": "Mohamed-Albakosh/The-Tech-Academy-Python-Coding-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\n for searsh by put .txt for example in File extensin box the file is come on the lists boxs aftre\n that click Add to add to database ffter get from database\n for change dirctory first click check for dirctory to choose dirctory after click change dirctory to\n choose the destination\n contact me if there any quetion \n\"\"\"\nimport tkinter\nfrom tkinter import *\nimport tkinter as tk\nfrom tkinter import filedialog\nimport os\nimport sqlite3\nimport shutil\n\nclass ParentWindow(Frame):\n def __init__ (self,master):\n Frame.__init__ (self)\n\n self.master = master\n self.master.resizable(width=False, height=False)\n self.master.geometry('{}x{}'.format(700,550))\n self.master.title('Learning Tkinter!')\n self.master.config(bg='lightgray')\n \n self.vardirectory = StringVar()\n self.varFilex = StringVar()\n self.varfname = StringVar()\n \n self.lblDisplay =Label(self.master,text='', font=(\"Helvetica\", 16), fg='black', bg='lightgray')\n self.lblDisplay.grid(row=3,column=1,padx=(30,0),pady=(30,0))\n\n\n self.txtFdirectory =Entry(self.master,text=self.vardirectory,width=40, font=(\"Helvetica\", 16), fg='black', bg='white')\n self.txtFdirectory.grid(row=0,column=1,columnspan=2,padx=(30,0),pady=(30,0),sticky=N+E)\n\n self.txtFname =Entry(self.master,text= self.varfname,width=40,font=(\"Helvetica\", 16), fg='black', bg='white')\n self.txtFname.grid(row=1,column=1,columnspan=2,padx=(30,0),pady=(30,0))\n \n self.txtfilex =Entry(self.master,text= self.varFilex,width=40,font=(\"Helvetica\", 16), fg='black', bg='white')\n self.txtfilex.grid(row=2,column=1,columnspan=2,padx=(30,0),pady=(30,0))\n\n\n \n self.lblApath =Label(self.master,text='Absolute path:', width=15,fg='black', bg='lightgray')\n self.lblApath.grid(row=0,column=0,padx=(30,0),pady=(30,0))\n\n self.lblfiles =Label(self.master,text='Files:', width=15, fg='black', bg='lightgray')\n self.lblfiles.grid(row=1,column=0,padx=(30,0),pady=(30,0))\n\n self.lblfiles =Label(self.master,text='Files extension:', width=15, fg='black', bg='lightgray')\n self.lblfiles.grid(row=2,column=0,padx=(30,0),pady=(30,0))\n\n #Define the listbox with a scrollbar and grid them\n self.scrollbar1 = Scrollbar(self.master,orient=VERTICAL)\n self.lstList1 = Listbox(self.master,exportselection=0,yscrollcommand=self.scrollbar1.set)\n self.lstList1.bind('<<ListboxSelect>>',lambda event: drill50_phonebook_func.onSelect(self,event))\n self.scrollbar1.config(command=self.lstList1.yview)\n self.scrollbar1.grid(row=3,column=2,rowspan=6,columnspan=1,padx=(30,0),pady=(30,0),sticky=N+E+S)\n self.lstList1.grid(row=3,column=1,rowspan=6,columnspan=1,padx=(30,0),pady=(30,0),sticky=N+E+S+W)\n\n self.scrollbar2 = Scrollbar(self.master,orient=VERTICAL)\n self.lstList2 = Listbox(self.master,exportselection=0,yscrollcommand=self.scrollbar1.set)\n self.lstList2.bind('<<ListboxSelect>>',lambda event: drill50_phonebook_func.onSelect(self,event))\n self.scrollbar2.config(command=self.lstList1.yview)\n self.scrollbar2.grid(row=3,column=2,rowspan=6,columnspan=1,padx=(30,0),pady=(30,0),sticky=N+E+S)\n self.lstList2.grid(row=3,column=2,rowspan=6,columnspan=1,padx=(30,0),pady=(30,0),sticky=N+E+S+W)\n \n \n self.btnDirectory = Button(self.master, text = \"Check for Dirctory\", width=15, height=2, command=self.Dirctory)\n self.btnDirectory.grid(row=9, column=0, padx=(30,0),pady=(30,0))\n\n self.btnCancel = Button(self.master, text = \"Close Program\", width=15, height=2, command=self.cancel)\n self.btnCancel.grid(row=9, column=2, padx=(30,0),pady=(30,0), sticky=SE)\n\n self.btGetfrom = Button(self.master, text = \"Get from Database\", width=15, height=2, command=self.Getfrom)\n self.btGetfrom.grid(row=6, column=0, padx=(30,0),pady=(30,0), sticky=SE)\n\n self.btnCDirctory = Button(self.master, text = \"Change Dirctory\", width=15, height=2, command=self.CDirctory)\n self.btnCDirctory.grid(row=9, column=1, padx=(30,0),pady=(30,0), sticky=SE)\n \n\n self.btnAdd = Button(self.master, text = \"Add\", width=15, height=2, command=self.Add)\n self.btnAdd.grid(row=7, column=0, padx=(30,0),pady=(30,0), sticky=SE)\n \n self.btnSearch = Button(self.master, text = \"Search by extension\", width=15, height=2, command=self.Search)\n self.btnSearch.grid(row=8, column=0, padx=(30,0),pady=(30,0), sticky=SE)\n\n \n def Dirctory (self):\n #fn = self.varFName.get()\n fpath =filedialog.askdirectory()\n file=self.txtFname.get()\n os.path.join(fpath, file)\n joinpfile=os.path.join(fpath, file)\n #listPath= os.listdir(fpath)\n #print(fpath)\n #self.txtFname.insert(0,listPath)\n self.txtFdirectory.insert(0,joinpfile)\n \n def cancel (self):\n self.master.destroy()\n\n def Search(self):\n str1= StringVar()\n extension=self.txtfilex.get()\n fpath =filedialog.askdirectory()\n file=self.txtFname.get()\n #listPath= os.listdir(fpath)\n #list_str = []\n for fil in os.listdir(fpath):\n if fil.endswith(extension):\n self.lstList1.insert(0,fil)\n joinpfile=os.path.join(fpath, fil)\n self.lstList2.insert(0,os.path.getmtime(joinpfile))\n \n \n \n #list_str.append(str1)\n print(list_str) \n\n def Add(self):\n \n\n conn = sqlite3.connect('db_file_project.db')\n\n with conn:\n cur = conn.cursor()\n cur.execute(\"CREATE TABLE IF NOT EXISTS tbl_File(\\\n ID INTEGER PRIMARY KEY AUTOINCREMENT,\\\n file_Name TEXT,\\\n last_Update int\\\n )\")\n conn.commit()\n conn.close()\n\n \n conn = sqlite3.connect('db_file_project.db')\n with conn:\n cur = conn.cursor()\n sn=self.lstList1.size()\n values = self.lstList1.get(1)\n print(values)\n i=0\n print(sn)\n while i < sn:\n cur.execute(\"INSERT INTO tbl_File(file_Name,last_Update) VALUES (?,?)\",\\\n (self.lstList1.get(i),self.lstList2.get(i)))\n i=i+1\n print(i)\n \n conn.commit()\n conn.close()\n\n def Getfrom(self):\n conn = sqlite3.connect('db_file_project.db')\n with conn:\n cur = conn.cursor()\n cur.execute(\"select file_Name from tbl_File\")\n varPerson = cur.fetchall()\n print(varPerson)\n for item in varPerson:\n self.lstList1.insert(0,item)\n cur.execute(\"select last_Update from tbl_File\")\n varPerson = cur.fetchall()\n for item in varPerson:\n self.lstList2.insert(0,item) \n \n conn.commit()\n conn.close()\n\n def CDirctory(self):\n fileDirc=self.txtFdirectory.get()\n file=self.txtFname.get()\n fpath =filedialog.askdirectory()\n \n shutil.move(fpath, fileDirc) \n \n \n \n \n\n\n\n\n\nif __name__ == \"__main__\":\n root = Tk()\n App = ParentWindow(root)\n root.mainloop()\n" }, { "alpha_fraction": 0.5644076466560364, "alphanum_fraction": 0.6057941317558289, "avg_line_length": 31.21666717529297, "blob_id": "f1ef60ea2e02c86f1bc3a48dda58f7a0f8201fdb", "content_id": "e1355ac0fc68ad1d703743b40b92f2add4b2d192", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1933, "license_type": "no_license", "max_line_length": 122, "num_lines": 60, "path": "/GUI_TK.py", "repo_name": "Mohamed-Albakosh/The-Tech-Academy-Python-Coding-Projects", "src_encoding": "UTF-8", "text": "import tkinter\nfrom tkinter import *\nimport tkinter as tk\nfrom tkinter import filedialog\nimport os\n\nclass ParentWindow(Frame):\n def __init__ (self,master):\n Frame.__init__ (self)\n\n self.master = master\n self.master.resizable(width=False, height=False)\n self.master.geometry('{}x{}'.format(700,300))\n self.master.title('Learning Tkinter!')\n self.master.config(bg='lightgray')\n \n self.varFName = StringVar()\n self.varLName = StringVar()\n \n \n\n\n self.txtBrowse =Entry(self.master,text=self.varFName,width=40, font=(\"Helvetica\", 16), fg='black', bg='lightblue')\n self.txtBrowse.grid(row=0,column=1,columnspan=2,padx=(30,0),pady=(30,0),sticky=N+E)\n\n self.txtBrowse1 =Entry(self.master,text=self.varLName,width=40,font=(\"Helvetica\", 16), fg='black', bg='lightblue')\n self.txtBrowse1.grid(row=1,column=1,columnspan=2,padx=(30,0),pady=(30,0),sticky=N+E)\n\n \n self.btnBrowse =Button(self.master,text='Browse...', width=15, height=2, command='')\n self.btnBrowse.grid(row=0,column=0,padx=(30,0),pady=(30,0))\n\n self.btnBrowse1 =Button(self.master,text='Browse... ', width=15, height=2, command='')\n self.btnBrowse1.grid(row=1,column=0,padx=(30,0),pady=(30,0))\n \n self.btnSubmit = Button(self.master, text = \"Check for files\", width=15, height=2, command=self.Browse)\n self.btnSubmit.grid(row=2, column=0, padx=(30,0),pady=(30,0))\n\n self.btnCancel = Button(self.master, text = \"Close Program\", width=15, height=2, command=self.cancel)\n self.btnCancel.grid(row=2, column=2, padx=(30,0),pady=(30,0), sticky=SE)\n\n \n def Browse (self):\n fn = self.varBrowse.get()\n \n \n \n def cancel (self):\n self.master.destroy()\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n root = Tk()\n App = ParentWindow(root)\n root.mainloop()\n" }, { "alpha_fraction": 0.7011494040489197, "alphanum_fraction": 0.7011494040489197, "avg_line_length": 13.666666984558105, "blob_id": "fe2c3ecedd589d3ef8fb354100d7b69ac835c6ec", "content_id": "10b7c546fa411b1afb8d549b5f2fe5fe00b8a597", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 89, "license_type": "no_license", "max_line_length": 35, "num_lines": 6, "path": "/CarInsurance/CarInsurance/Controllers/InsurnceEntities.cs", "repo_name": "Mohamed-Albakosh/The-Tech-Academy-Python-Coding-Projects", "src_encoding": "UTF-8", "text": "namespace CarInsurance.Controllers\n{\n internal class InsurnceEntities\n {\n }\n}" } ]
7
Jodagito/Shapass
https://github.com/Jodagito/Shapass
cfd43912bb0cab2f3cca2bcef78fdb72c7d7bcd2
05c5d09107c7f6c55ed311baca347e55faa951a3
228a7712046d39ff3914680f38b452e7331d0e40
refs/heads/master
2021-01-19T20:57:00.168733
2017-08-24T01:40:23
2017-08-24T01:40:23
101,241,020
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5720338821411133, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 31.714284896850586, "blob_id": "250a9259b94cd453680245544e04f6630003c2c4", "content_id": "f52fbc350fd47821f42b2c1c25f2f05c3951d177", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 73, "num_lines": 21, "path": "/Shapass.py", "repo_name": "Jodagito/Shapass", "src_encoding": "UTF-8", "text": "# By Dagito from 0xDev\r\nimport hashlib\r\n\r\n\r\ndef cryptopass(password):\r\n aplication = input(\"What app is this password for? \")\r\n for random in range(len(password)):\r\n sha = hashlib.sha256(password.encode('utf-8')).hexdigest()\r\n print(\"Your new password is \" + \"\".join(sha).replace(' ', ''))\r\n save = open(\"Password.txt\", \"a\")\r\n save2 = open(\"Key Phrase.txt\", \"a\")\r\n save2.write(\"Your key phrase for \" + aplication + \" was \" + password)\r\n save2.write(\"\\n\")\r\n save.write(\"Your new password for \" + aplication + \" is \" + \" \" +\r\n \"\".join(sha).replace(' ', ''))\r\n save.write(\"\\n\")\r\n save.close()\r\n\r\n\r\npassword = input(\"Type a key phrase \")\r\ncryptopass(password)\r\n" }, { "alpha_fraction": 0.8160919547080994, "alphanum_fraction": 0.8160919547080994, "avg_line_length": 86, "blob_id": "f02fcf32756576c364df3b8dccd86b157e31f3cb", "content_id": "69003f1d8514a701772b76b279578aa8c9847657", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 174, "license_type": "no_license", "max_line_length": 163, "num_lines": 2, "path": "/README.md", "repo_name": "Jodagito/Shapass", "src_encoding": "UTF-8", "text": "# Shapass\nPeople often create easy passwords and when they make a complicated password they are often forgotten, so I thought in a very simple password storer and encrypter.\n" } ]
2
chenxvan/TkMap_PhaseI
https://github.com/chenxvan/TkMap_PhaseI
e87223316e7140e99d61d3bd3922546b38644280
0170982af68cee947f20e1b55e3c82a0dc4703e5
c928c4460210a5113c3f0e55a97954f9a74b9452
refs/heads/master
2021-01-23T10:47:49.232705
2017-06-06T16:29:46
2017-06-06T16:29:46
93,096,749
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5856717824935913, "alphanum_fraction": 0.6014030575752258, "avg_line_length": 33.59558868408203, "blob_id": "2db4b0ab36fcfebcd0ba2b8f2d6994aea1bdd8fe", "content_id": "ed37be3bedd4ddb4cf5a9a6d06f825f4400afa2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4704, "license_type": "no_license", "max_line_length": 196, "num_lines": 136, "path": "/PixelPhase1Scripts/CMSPixelTrackerMap/pixelcablingweb.php", "repo_name": "chenxvan/TkMap_PhaseI", "src_encoding": "UTF-8", "text": "<?php\n\nheader(\"Content-type: text/html\");\n\n$execOut = \"\";\n$execErr = \"\";\n\n$cablingTxt = \"\";\n\n$detid_fedid_searchOption = \"rawid\";\n$outDicTxtFileName = \"/tmp/pixelcablingweb_cablingInfo.dat\";\n\nif (isset($_POST[\"getCabling\"]))\n{\n $cablingTxt = $_POST[\"getCabling\"];\n $entity_id = $_POST[\"entity_id\"];\n $detid_fedid_searchOption = $_POST[\"detid_fedid_searchOption\"];\n \n $entity_id = str_replace(\"\\r\", \" \", $entity_id);\n\t$entity_id = str_replace(\"\\n\", \"\", $entity_id); \n $entity_idSpl = explode(\" \", $entity_id);\n $deltaTime = 0;\n \n $execTime = time();\n \n $inputFileName = \"/tmp/pixelCablingIds_\".$execTime.\".dat\";\n $outputXMLFileName = \"/tmp/pixelTrackerMap_\".$execTime.\".xml\";\n $fedDBInfoFile = \"/tmp/pixelFEDCablingInfo.dat\";\n \n exec(\"echo > $inputFileName\"); // create empty input file for Pixel Tracker Map Builder\n for ($i = 0; $i < count($entity_idSpl); $i++)\n {\n if ($entity_idSpl[$i] != \"\" && $entity_idSpl[$i] != \" \")\n {\n // right now only static (one) color is allowed\n exec(\"echo '$entity_idSpl[$i] 255 0 0' >> $inputFileName\"); // append (>>) to the file \n }\n } \n $output = shell_exec(\"python ConcatScript.py > DATA/CablingDB/pxCabl.csv 2>&1\");\n // echo \"<pre>$output</pre>\";\n\n if (file_exists($fedDBInfoFile)) # PREVENTS FROM HUGE LOADING TIMES, DB file is going to be updated after an hour\n {\n $fileChangedTime = filemtime($fedDBInfoFile);\n $deltaTime = time() - $fileChangedTime;\n \n if ($deltaTime > 3600)\n {\n // exec(\"rm $fedDBInfoFile\");\n $output = shell_exec(\"bash runCMSSW.sh > $fedDBInfoFile\");\n echo \"<pre>$output</pre>\";\n }\n }\n else{\n // echo \"<pre>Creating new file...</pre>\";\n $output = shell_exec(\"bash runCMSSW.sh > $fedDBInfoFile\");\n // echo \"<pre>$output</pre>\";\n }\n \n // NOW CREATE XML FILE\n \n $output = shell_exec(\"python PixelTrackerMap.py $inputFileName $fedDBInfoFile $detid_fedid_searchOption $outDicTxtFileName > $outputXMLFileName 2>&1\");\n // echo \"<pre>$output</pre>\";\n}\n?>\n\n<link rel=\"stylesheet\" href=\"https://unpkg.com/[email protected]/build/pure-min.css\" integrity=\"sha384-UQiGfs9ICog+LwheBSRCt1o5cbyKIHbwjWscjemyBMT9YCUMZffs6UqUTd0hObXD\" crossorigin=\"anonymous\">\n<link rel=\"stylesheet\" href=\"DATA/main.css\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n<div class=\"pure-g\">\n <div class= \"pure-u-1-5\">\n <div class=\"l-box\">\n <img style=\"height: 4em;\" src=\"http://radecs2017.vitalis-events.com/wp-content/uploads/2016/09/CERN_logo2.svg_.png\"/>\n </div>\n </div>\n <div class= \"pure-u-3-5\">\n <div class=\"l-box\">\n <h1> Pixel Cabling Viewer </h1>\n </div>\n </div>\n <div class= \"pure-u-1-5\">\n <div class=\"l-box\">\n <img style=\"position: absolute; right: 1em; height: 4em\" src=\"https://cms-docdb.cern.ch/cgi-bin/PublicDocDB/RetrieveFile?docid=3045&filename=CMSlogo_black_label_1024_May2014.png&version=3\"/>\n </div>\n </div>\n</div>\n\n<div class=\"pure-g\">\n <div class=\"pure-u-1-6\">\n <div class=\"l-box\">\n <form class=\"pure-form\" enctype = \"multipart/form-data\" action = \"pixelcablingweb.php\" method = \"POST\">\n <legend>Insert Pixel IDs to be marked:</legend>\n \n <label for=\"option-two\" class=\"pure-radio\">\n <input id=\"option-two\" type=\"radio\" name=\"detid_fedid_searchOption\" value=\"rawid\" <?php if ($detid_fedid_searchOption == \"rawid\") echo \"checked\" ?> >\n Det ID\n </label>\n \n <label for=\"option-three\" class=\"pure-radio\">\n <input id=\"option-three\" type=\"radio\" name=\"detid_fedid_searchOption\" value=\"fedid\" <?php if ($detid_fedid_searchOption == \"fedid\") echo \"checked\" ?>>\n FED ID\n </label>\n \n <textarea name=\"entity_id\" placeholder=\"353309700\"><?php echo $entity_id ?></textarea>\n \n <button class=\"pure-button pure-button-primary\" name=\"getCabling\" type=\"submit\" value=\"GetCabling\" style=\"width: 100%\">Get Cabling</button>\n </form>\n <?php\n echo \"<p style=\\\"text-align: right;\\\">Delta time: \".$deltaTime.\" s</p>\";\n ?>\n </div>\n </div>\n \n <div class=\"pure-u-5-6\">\n <div class=\"l-box\">\n <?php \n if (isset($_POST[\"getCabling\"]))\n {\n // echo \"<div style=\\\"transform: scale(0.7);\\\">\";\n echo \"<embed src='render_cabling_web_from_tmp.php?file=$outputXMLFileName&contenttype=text/xml'>\";\n // echo \"<iframe src='txt_cablingweb_from_tmp.php?file=$outDicTxtFileName'></iframe>\";\n // echo \"</div>\";\n }\n ?>\n <div>\n </div>\n <div class=\"pure-u-1-1\">\n <?php\n if (isset($_POST[\"getCabling\"]))\n {\n echo \"<a href='render_cabling_web_from_tmp.php?file=$outDicTxtFileName&contenttype=text/plain'>Link to the cabling info file </a>\";\n }\n ?>\n </div>\n</div>" }, { "alpha_fraction": 0.6521739363670349, "alphanum_fraction": 0.6521739363670349, "avg_line_length": 22.25, "blob_id": "55b8724fafa218feabd4436dba74d72175b8bef2", "content_id": "ffb75efec723932c52bdfb3a388cb9964d5dbc3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 92, "license_type": "no_license", "max_line_length": 55, "num_lines": 4, "path": "/PixelPhase1Scripts/CMSPixelTrackerMap/README.md", "repo_name": "chenxvan/TkMap_PhaseI", "src_encoding": "UTF-8", "text": "Pixel Tracker Map\n=================\n\nThis is a web interface to show Pixel Detector Cabling." }, { "alpha_fraction": 0.7617108225822449, "alphanum_fraction": 0.771894097328186, "avg_line_length": 69.14286041259766, "blob_id": "2afd99bb71e7051d72fb6b33756d14c5db38e495", "content_id": "22042e33322a8babd9c6d3277c6fab8f9fe61ff1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 982, "license_type": "no_license", "max_line_length": 233, "num_lines": 14, "path": "/PixelPhase1Scripts/README.md", "repo_name": "chenxvan/TkMap_PhaseI", "src_encoding": "UTF-8", "text": "Content of the repository\n=========================\n\nThis repository keeps small utilities for PixelPhase1 (mainly for debugging purposes)\n\n 1. *CMSPixelTrackerMap* - web interface for printing Pixel Detector Cabling information.\n 2. *DeadROCViewer* - script that produces maps with marked desired ROCs inside modules.\n 3. *HotPixels* - analyzer that looks for 'hyperreactive' ROCs.\n 4. *PythonBINReader* - script which takes DQM file as an input, looks for all module level Pixel plots and reads bins' values (bin content reflects activity in a specified module) to produce simple ROOT tree used by TkCommissioner.\n 5. *SiPixelPhase1Analyzer* - CMSSW tool to produce Offline Pixel Tracker maps which layout resambles real detector.\n 6. *TH2PolyOfflineMaps* - creates Pixel Tracker Maps from DQM module level plots.\n 7. *TMComparator* - utility to create graphical comparisons between Tracker Maps.\n \nMore information about scripts is provided inside each script directory.\n" }, { "alpha_fraction": 0.734455943107605, "alphanum_fraction": 0.7461140155792236, "avg_line_length": 44.411766052246094, "blob_id": "034c3e38ecab682f1da68e4c49207783cd18539d", "content_id": "5d61df6c64312112e56527d588dcea5b4860e512", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 772, "license_type": "no_license", "max_line_length": 296, "num_lines": 17, "path": "/PixelPhase1Scripts/TH2PolyOfflineMaps/README.md", "repo_name": "chenxvan/TkMap_PhaseI", "src_encoding": "UTF-8", "text": "TH2PolyOfflineMaps\n==================\n\nThe script which behaviour is very similar to the https://github.com/pjurgielewicz/cmssw/tree/pjAnalyzerBranch/DQM/SiPixelPhase1Analyzer in the *MODE_REMAP* but it additionally produces full Tracker Maps (Barrel + Pixel) in the single image for all module level plots available in the input file.\n\nMoreover it looks for 20 minimum and maximum values in Tracker Map bins and prints them (with a corresponding det ID) in the output text file.\n\nHow to use\n----------\n\n`python TH2PolyOfflineMaps.py <name of the input file>`\n\nwhere the run number has to be able to be deducted from the input file name. Supported format is as follows\n\n`*_R000######*` - run number is a 6-digit value\n\nOutputs (maps + text file) are saved inside `.OUT/`.\n" }, { "alpha_fraction": 0.6164670586585999, "alphanum_fraction": 0.6390820145606995, "avg_line_length": 40.02405548095703, "blob_id": "5143233e58d1778adcd18f39f429b4d2fda35fd8", "content_id": "62eb8c073c89f38e89c9d2faa406838aadcf7dd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11939, "license_type": "no_license", "max_line_length": 294, "num_lines": 291, "path": "/TkMap_script_automatic_DB.py", "repo_name": "chenxvan/TkMap_PhaseI", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport sys\nfrom ROOT import *\nimport os\nfrom subprocess import call\nimport os.path\nimport shutil\nimport subprocess\nimport codecs\n\n\nRun_type = sys.argv[1]\nRun_Number = [int(x) for x in sys.argv[2:]]\n\n\n\nif Run_type == 'Cosmics':\n print Run_type\nelif Run_type == 'MinimumBias':\n print Run_type\nelif Run_type == 'StreamExpress':\n print Run_type\nelif Run_type == 'StreamExpressCosmics':\n print Run_type\nelse: \n print \"please enter a valid run type: Cosmics | MinimumBias | StreamExpress | StreamExpressCosmics \";\n sys.exit(0)\n\n#########Checking Data taking period##########\nfor i in range(len(Run_Number)):\n\n if Run_Number[i] > 294644:\n DataLocalDir='Data2017'\n DataOfflineDir='Run2017'\n\n elif Run_Number[i] > 290123:\n DataLocalDir='Data2017'\n DataOfflineDir='Commissioning2017'\n\n\n elif Run_Number[i] > 284500:\n DataLocalDir='Data2016';\n DataOfflineDir='PARun2016';\n\n##2016 data taking period run > 271024\n elif Run_Number[i] > 271024:\n DataLocalDir='Data2016';\n DataOfflineDir='Run2016';\n\n#2016 - Commissioning period \n elif Run_Number[i] > 264200:\n DataLocalDir='Data2016';\n DataOfflineDir='Commissioning2016';\n\n#Run2015A\n elif Run_Number[i] > 246907:\n DataLocalDir='Data2015';\n DataOfflineDir='Run2015'\n \n#2015 Commissioning period (since January)\n elif Run_Number[i] > 232881:\n DataLocalDir='Data2015';\n DataOfflineDir='Commissioning2015';\n\n#2013 pp run (2.76 GeV)\n elif Run_Number[i] > 211658:\n DataLocalDir='Data2013';\n DataOfflineDir='Run2013';\n\n#2013 HI run\n elif Run_Number[i] > 209634:\n DataLocalDir='Data2013';\n DataOfflineDir='HIRun2013';\n \n elif Run_Number[i] > 190450:\n DataLocalDir='Data2012';\n DataOfflineDir='Run2012';\n\n else:\n print \"Please enter vaild run numbers\"\n sys.exit(0)\n\n\n nnn=Run_Number[i]/100\n nnnOut = Run_Number[i]/1000\n \n if Run_type == \"Cosmics\":\n checkdir='/data/users/event_display/'+DataLocalDir+'/Cosmics/'+str(nnnOut)+'/'+str(Run_Number[i])+'/StreamExpressCosmics'\n if not os.path.isdir(checkdir):\n os.makedirs(checkdir)\n\n else:\n checkdir='/data/users/event_display/'+DataLocalDir+'/Beam/'+str(nnnOut)+'/'+str(Run_Number[i])+'/StreamExpress'\n if not os.path.isdir(checkdir):\n os.makedirs(checkdir)\n\n\n print 'Processing '+Run_type+ ' in '+DataOfflineDir+\"...\"\n\n\n print 'Directory to fetch the DQM file from: https://cmsweb.cern.ch/dqm/offline/data/browse/ROOT/OfflineData/'+DataOfflineDir+'/'+Run_type+'/000'+str(nnn)+'xx/'\n url = 'https://cmsweb.cern.ch/dqm/offline/data/browse/ROOT/OfflineData/'+DataOfflineDir+'/'+Run_type+'/000'+str(nnn)+'xx/'\n os.popen(\"curl -k --cert /data/users/cctrkdata/current/auth/proxy/proxy.cert --key /data/users/cctrkdata/current/auth/proxy/proxy.cert -X GET \"+url+\" > index.html\") \n f=codecs.open(\"index.html\", 'r')\n index = f.readlines()\n for s in range(len(index)): \n if str(Run_Number[i]) in index[s]:\n if str(\"__DQMIO.root\") in index[s]:\n File_Name=str(str(index[s]).split(\"xx/\")[1].split(\"'>DQM\")[0])\n\n print 'Downloading DQM file:'+File_Name\n\n \n os.system('curl -k --cert /data/users/cctrkdata/current/auth/proxy/proxy.cert --key /data/users/cctrkdata/current/auth/proxy/proxy.cert -X GET https://cmsweb.cern.ch/dqm/offline/data/browse/ROOT/OfflineData/'+DataOfflineDir+'/'+Run_type+'/000'+str(nnn)+'xx/'+File_Name+' > /tmp/'+File_Name)\n\n filepath = '/tmp/'\n \n\n################Check if run is complete##############\n\n print \"get the run status from DQMFile\"\n\n\n check_command = 'check_runcomplete '+filepath+File_Name\n Check_output = subprocess.call(check_command, shell=True)\n\n\n if Check_output == 0:\n print 'Using DQM file: '+File_Name\n else:\n print '*****************Warning: DQM file is not ready************************';\n input_var = raw_input(\"DQM file is incompleted, do you want to continue? (y/n): \")\n if (input_var == 'y') or (input_var == 'Y'):\n print 'Using DQM file: '+File_Name\n else:\n sys.exit(0)\n\n \n###################Start making TkMaps################\n checkfolder = os.path.exists(str(Run_Number[i]))\n if checkfolder == True:\n shutil.rmtree(str(Run_Number[i]))\n os.makedirs(str(Run_Number[i])+'/'+Run_type)\n else:\n os.makedirs(str(Run_Number[i])+'/'+Run_type)\n \n globalTag = str(os.popen('getGTfromDQMFile.py '+ filepath+File_Name+' ' +str(Run_Number[i])+' globalTag_Step1').readline().strip())\n print globalTag\n\n \n if globalTag == \"\":\n print \" No GlobalTag found: trying from DAS.... \";\n globalTag = str(os.popen('getGTscript.sh '+filepath+ File_Name+' ' +str(Run_Number[i])));\n if globalTag == \"\":\n print \" No GlobalTag found for run: \"+str(Run_Number[i]);\n \n print \" Creating the TrackerMap.... \"\n\n detIdInfoFileName = 'TkDetIdInfo_Run'+str(Run_Number[i])+'_'+Run_type+'.root'\n workPath = os.popen('pwd').readline().strip()\n\n os.chdir(str(Run_Number[i])+'/'+Run_type)\n \n\n\n os.system('cmsRun '+workPath+'/DQM/SiStripMonitorClient/test/SiStripDQM_OfflineTkMap_Template_cfg_DB.py globalTag='+globalTag+' runNumber='+str(Run_Number[i])+' dqmFile='+filepath+'/'+File_Name+' detIdInfoFile='+detIdInfoFileName)\n \n# rename bad module list file\n sefile = 'QualityTest_run'+str(Run_Number[i])+'.txt'\n shutil.move('QTBadModules.log',sefile)\n\n# put color legend in the TrackerMap \n os.system('/usr/bin/python '+workPath+'/DQM/SiStripMonitorClient/scripts/LegendToQT.py QTestAlarm.png /data/users/cctrack/FinalLegendTrans.png')\n shutil.move('result.png', 'QTestAlarm.png')\n\n\n\n if Run_type == \"Cosmics\":\n os.system('cat '+workPath+'/DQM/SiStripMonitorClient/data/index_template_TKMap_cosmics.html | sed -e \"s@RunNumber@'+str(Run_Number[i])+'@g\" > index.html')\n else:\n os.system('cat '+workPath+'/DQM/SiStripMonitorClient/data/index_template_TKMap.html | sed -e \"s@RunNumber@'+str(Run_Number[i])+'@g\" > index.html')\n shutil.copyfile(workPath+'/DQM/SiStripMonitorClient/data/fedmap.html','fedmap.html')\n shutil.copyfile(workPath+'/DQM/SiStripMonitorClient/data/psumap.html','psumap.html')\n\n \n print \" Check TrackerMap on \"+str(Run_Number[i])+'/'+Run_type+\" folder\"\n \n output =[]\n output.append(os.popen(\"/bin/ls \").readline().strip())\n print output\n\n## Producing the list of bad modules\n print \" Creating the list of bad modules \"\n \n os.system('listbadmodule '+filepath+'/'+File_Name+' PCLBadComponents.log')\n if Run_type != \"StreamExpress\":\n shutil.copyfile(sefile, checkdir+'/'+sefile)\n os.system('/usr/bin/python '+workPath+'/DQM/SiStripMonitorClient/scripts/findBadModT9.py -p '+sefile+' -s /'+checkdir+'/'+sefile);\n \n \n## Producing the run certification by lumisection\n \n print \" Creating the lumisection certification:\"\n\n if (Run_type == \"MinimumBias\") or (Run_type == \"StreamExpress\"):\n os.system('ls_cert 0.95 0.95 '+filepath+'/'+File_Name)\n\n## Producing the PrimaryVertex/BeamSpot quality test by LS..\n if (Run_type != \"Cosmics\") and ( Run_type != \"StreamExpress\") and (Run_type != \"StreamExpressCosmics\"):\n print \" Creating the BeamSpot Calibration certification summary:\"\n os.system('lsbs_cert '+filepath+'/'+File_Name)\n\n## .. and harvest the bad beamspot LS with automatic emailing (if in period and if bad LS found)\n os.system('bs_bad_ls_harvester . '+str(Run_Number[i]))\n \n\n## Producing the Module difference for ExpressStream\n if (Run_type == \"StreamExpress\") or (Run_type == \"StreamExpressCosmics\"):\n print \" Creating the Module Status Difference summary:\"\n\n dest='Beam'\n if (Run_type == \"Cosmics\") or (Run_type == \"StreamExpressCosmics\"):\n dest=\"Cosmics\"\n\n\n## create merged list of BadComponent from (PCL, RunInfo and FED Errors) ignore for now\n os.system('cmsRun '+workPath+'/DQM/SiStripMonitorClient/test/mergeBadChannel_Template_cfg.py globalTag='+globalTag+' runNumber='+str(Run_Number[i])+' dqmFile='+filepath+'/'+File_Name)\n shutil.move('MergedBadComponents.log','MergedBadComponents_run'+str(Run_Number[i])+'.txt')\n\n# HOST='cctrack@vocms062'\n HOST='cctrack@vocms061'\n COMMAND=\"mkdir -p /data/users/event_display/TkCommissioner_runs/\"+DataLocalDir+\"/\"+dest+\" 2> /dev/null\" \n ssh = subprocess.Popen([\"ssh\", \"%s\" % HOST, COMMAND],\n shell=False,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n ssh.stdout\n os.system('scp *.root cctrack@vocms062:/data/users/event_display/TkCommissioner_runs/'+DataLocalDir+'/'+dest)\n# os.system('scp *.root cctrack@vocms061:/data/users/event_display/TkCommissioner_runs/'+DataLocalDir+'/'+dest)\n os.remove(detIdInfoFileName)\n\n\n\n print \"countig dead pixel ROCs\" \n if (DataLocalDir==\"Data2016\") or (DataLocalDir==\"Data2015\") or (DataLocalDir==\"Data2013\") or (DataLocalDir==\"Data2016\"):\n os.system('python '+workPath+'/DQM/SiStripMonitorClient/scripts/DeadROCCounter.py '+filepath+'/'+File_Name)\n else: \n os.system('python '+workPath+'/DQM/SiStripMonitorClient/scripts/DeadROCCounter_Phase1.py '+filepath+'/'+File_Name)\n\n Command2='mkdir -p /data/users/event_display/'+DataLocalDir+'/'+dest+'/'+str(nnnOut)+'/'+str(Run_Number[i])+'/'+Run_type+' 2> /dev/null'\n# Command2='mkdir -p /data/users/event_display/'+DataLocalDir+'/'+dest+'/'+str(nnnOut)+'/'+str(Run_Number[i])+'/'+Run_type+'/SiStrip 2> /dev/null'\n# Command3='mkdir -p /data/users/event_display/'+DataLocalDir+'/'+dest+'/'+str(nnnOut)+'/'+str(Run_Number[i])+'/'+Run_type+'/Pixel 2>/dev/null'\n\n ssh2 = subprocess.Popen([\"ssh\", \"%s\" % HOST, Command2],\n shell=False,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n ssh2.stdout\n\n shutil.move('PixZeroOccROCs_run'+str(Run_Number[i])+'.txt',workPath+'/PixZeroOccROCs_run'+str(Run_Number[i])+'.txt')\n\n# os.system('scp -r * cctrack@vocms062:/data/users/event_display/'+DataLocalDir+'/'+dest+'/'+str(nnnOut)+'/'+str(Run_Number[i])+'/'+Run_type)\n\n os.system('scp -r * cctrack@vocms061:/data/users/event_display/'+DataLocalDir+'/'+dest+'/'+str(nnnOut)+'/'+str(Run_Number[i])+'/'+Run_type)\n\n os.chdir(workPath)\n shutil.rmtree(str(Run_Number[i]))\n os.remove('index.html')\n\n # produce pixel phase1 TH2Poly maps\n os.chdir(workPath + '/PixelPhase1Scripts/TH2PolyOfflineMaps')\n os.system('python TH2PolyOfflineMaps.py ' + filepath+'/'+File_Name)\n shutil.move(workPath+'/PixZeroOccROCs_run'+str(Run_Number[i])+'.txt', 'OUT/PixZeroOccROCs_run'+str(Run_Number[i])+'.txt')\n# os.system('scp -r OUT/* cctrack@vocms062:/data/users/event_display/'+DataLocalDir+'/'+dest+'/'+str(nnnOut)+'/'+str(Run_Number[i])+'/'+Run_type)\n os.system('scp -r OUT/* cctrack@vocms061:/data/users/event_display/'+DataLocalDir+'/'+dest+'/'+str(nnnOut)+'/'+str(Run_Number[i])+'/'+Run_type)\n shutil.rmtree('OUT')\n\n os.chdir(workPath) \n\n # produce pixel phase1 tree for Offline TkCommissioner\n pixelTreeFileName = 'PixelPhase1Tree_Run'+str(Run_Number[i])+'_'+Run_type+'.root'\n os.chdir(workPath + '/PixelPhase1Scripts/PythonBINReader')\n os.system('python script.py ' + filepath+'/'+File_Name + ' detids.dat ' + pixelTreeFileName)\n\n# os.system('scp ' + pixelTreeFileName + ' cctrack@vocms062:/data/users/event_display/TkCommissioner_runs/'+DataLocalDir+'/'+dest)\n os.system('scp ' + pixelTreeFileName + ' cctrack@vocms061:/data/users/event_display/TkCommissioner_runs/'+DataLocalDir+'/'+dest)\n \n os.remove(pixelTreeFileName)\n\n os.chdir(workPath)\n\n" }, { "alpha_fraction": 0.7244898080825806, "alphanum_fraction": 0.7612245082855225, "avg_line_length": 21.272727966308594, "blob_id": "f190d0b78c3a7d7831d0f643f291f54a40eebcd0", "content_id": "43de079c305075434dbc232bad1951795d8e7289", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 490, "license_type": "no_license", "max_line_length": 108, "num_lines": 22, "path": "/PixelPhase1Scripts/CMSPixelTrackerMap/runCMSSW.sh", "repo_name": "chenxvan/TkMap_PhaseI", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# cmsenv\n\nCMSSW_BASE=/afs/cern.ch/cms/tracker/sistrcalib/MonitorConditionDB/CMSSW_9_0_0\n\nexport SCRAM_ARCH=slc6_amd64_gcc530\nsource /afs/cern.ch/cms/cmsset_default.sh\n# echo $SCRAM_ARCH\n# echo $HOSTNAME\n\ncd $CMSSW_BASE/src\n\neval `scramv1 runtime -sh`\n# echo $SCRAM_ARCH\n# echo $LD_LIBRARY_PATH\n# echo $OLDPWD\ncd $OLDPWD\n\nGT=\"90X_upgrade2017_realistic_v6\"\nRUN_COMMAND=\"cmsRun ${CMSSW_BASE}/src/DQM/SiPixelPhase1CablingAnalyzer/python/ConfFile_cfg.py globalTag=$GT\"\n$RUN_COMMAND\n" } ]
6
Macmaad/S-coding-challenge
https://github.com/Macmaad/S-coding-challenge
78776aced13fc7c563f9999d00f21a9ef0cd0296
d4036322018e289da9c3b6668e186f58e93951a0
3e67f07b4872b586124dccf1eb1dc1cff9db9265
refs/heads/master
2020-09-21T21:19:39.752546
2020-01-13T18:35:20
2020-01-13T18:35:20
224,934,754
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5560267567634583, "alphanum_fraction": 0.5650218725204468, "avg_line_length": 31.5606689453125, "blob_id": "0cde13ad4640e83e6f3277bef48a124ea7b00105", "content_id": "bb8509c77b879da05ef5d6934172f1fbbfbe12bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7784, "license_type": "no_license", "max_line_length": 120, "num_lines": 239, "path": "/s_challenge.py", "repo_name": "Macmaad/S-coding-challenge", "src_encoding": "UTF-8", "text": "\"\"\"\n Stori project:\n A city’s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed\n from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape\n photo (Input), write a program to output the skyline formed by these buildings collectively (Output)\n Input:\n [Li, Ri, Hi] = where Li and Ri are the x coordinates of the left and right edge of the ith building and Hi\n is the height. Assume that all the buildings are perfect rectangles grounded on an absolutely flat\n surface at height 0.\n Output:\n List of key points (red dots in the output figure) in the format of [ [x1,y1], [x2,y2] ] that uniquely\n defines a skyline. A key point is the left endpoint of a horizontal line segment.\n Keep in mind:\n The output list must be sorted by the X position and there must be no consecutive horizontal\n lines of equal height in the output skyline.\n\n Inputs:\n Building N = [left_edge, right_edge, height]\n Building 1 = [2, 9, 10]\n Building 2 = [3, 6, 15]\n Building 3 = [5, 12, 12]\n Building 4 = [13, 16, 10]\n Building 5 = [15, 17, 5]\n \n Functions: \n create_building_object\n read_data\n sort_data_tuples\n get_intersections\n create_all_edges\n join_edges_with_same_x_value\n sort_heights\n get_skyline\n main\n Classes: \n Building\n \n\"\"\"\n\n\nclass Building:\n def __init__(self, left_edge, right_edge, height):\n self.left_edge = left_edge\n self.right_edge = right_edge\n self.height = height\n# Create the building object, it's used to get track of the edges and height for each building.\n\n\ndef create_building_object(arr):\n \"\"\"\n Get data array that was given from the user.\n :param arr:\n :return: array of objects of type building.\n \"\"\"\n buildings = []\n for data in arr:\n buildings.append(Building(data[0], data[1], data[2]))\n return buildings\n# Gets the array of data and return an array with all the objects.\n\n\ndef read_data():\n \"\"\"\n Read data of the buildings.\n :return: array of arrays with the information.\n The array have arrays of len = 3.\n \"\"\"\n buildings_data = []\n n = 1\n print('\\n\\nReading buildings: ')\n while True:\n temp = []\n option = ''\n print(f'\\nBuilding #{n}')\n while True:\n try:\n left_edge = float(input('Left_edge: '))\n break\n except ValueError:\n print('That was no valid number! Try again.')\n while True:\n try:\n right_edge = float(input('Right_edge: '))\n break\n except ValueError:\n print('That was no valid number! Try again.')\n while True:\n try:\n height = float(input('Height: '))\n break\n except ValueError:\n print('That was no valid number! Try again.')\n temp.append(left_edge)\n temp.append(right_edge)\n temp.append(height)\n buildings_data.append(temp)\n while option.lower() != 'no' or option.lower() != 'yes':\n option = str(input('\\nNew building? (yes/no): '))\n print(option.lower())\n if option.lower() != 'no' and option.lower() != 'yes':\n print('Just yes or no!... Try again.')\n else:\n break\n if option.lower() == 'no':\n break\n n += 1\n return buildings_data\n# Read all the buildings data, its open to read the number of buildings the user wants.\n\n\ndef sort_data_tuples(arr):\n \"\"\"\n Sort array with tuples by the first entry of the tuples.\n :param arr:\n :return sorted array:\n \"\"\"\n for i in range(0, len(arr)):\n for j in range(i + 1, len(arr)):\n if arr[i][0] > arr[j][0]:\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n return arr\n# Takes array with tuples and sort them by the first element on the tuple. Bubbling sort.\n\n\ndef get_intersections(arr):\n \"\"\"\n Getting the sorted array creates the intersection points of the buildings. \n :param arr: \n :return returns the intersections dots array: \n \"\"\"\n intersection_dots = []\n for element in arr:\n lower_bound = element.left_edge\n upper_bound = element.right_edge\n for subelement in arr:\n if lower_bound < subelement.left_edge < upper_bound:\n if subelement.height > element.height:\n intersection_dots.append((subelement.left_edge, element.height))\n if lower_bound < subelement.right_edge < upper_bound:\n if subelement.height > element.height:\n intersection_dots.append((subelement.right_edge, element.height))\n return intersection_dots\n\n\ndef create_all_edges(arr):\n \"\"\"\n Creates all the edges of the buildings.\n :param arr: \n :return array with all the buildings edges. (4 for each building): \n \"\"\"\n building_edges = []\n for building in arr:\n building_edges.append((building.left_edge, 0))\n building_edges.append((building.left_edge, building.height))\n building_edges.append((building.right_edge, 0))\n building_edges.append((building.right_edge, building.height))\n return building_edges\n\n\ndef join_edges_with_same_x_value(arr):\n \"\"\"\n With the sorted elements joins the ones that have the same x axis value.\n \n :param arr: \n :return array with arrays inside.: \n \"\"\"\n initial = arr[0][0]\n temp = [arr[0]]\n all_points = []\n for i in range(1, len(arr)):\n if arr[i][0] == initial:\n temp.append(arr[i])\n else:\n initial = arr[i][0]\n all_points.append(temp)\n temp = [arr[i]]\n all_points.append(temp)\n return all_points\n\n\ndef sort_heights(arr):\n \"\"\"\n Sort array with arrays inside where each one haves tuples, we use the second entry of the tuples.\n :param arr: \n :return: \n \"\"\"\n for k in range(0, len(arr)):\n for i in range(0, len(arr[k])):\n for j in range(i, len(arr[k])):\n if arr[k][i][1] > arr[k][j][1]:\n temp = arr[k][i]\n arr[k][i] = arr[k][j]\n arr[k][j] = temp\n return arr\n\n\ndef get_skyline(arr):\n \"\"\"\n Create the final skyline. \n :param arr: \n :return array with tuples.: \n \"\"\"\n first_element = 0\n skyline = []\n for x_group in arr:\n if first_element == 0:\n skyline.append(x_group[len(x_group) - 1])\n first_element += 1\n else:\n # index = 0\n for i in range(0, len(x_group)):\n if x_group[i][1] == skyline[len(skyline) - 1][1]:\n if len(x_group) - 1 > i:\n skyline.append(x_group[i + 1])\n break\n elif len(x_group) - 1 == i:\n skyline.append(x_group[i - 1])\n break\n return skyline\n\n\ndef main():\n data = read_data()\n buildings = create_building_object(data)\n intersections = get_intersections(buildings)\n all_edges = create_all_edges(buildings)\n all_points = intersections + all_edges\n sorted_data = sort_data_tuples(all_points)\n joined_points = join_edges_with_same_x_value(sorted_data)\n sorted_heights = sort_heights(joined_points)\n skyline = get_skyline(sorted_heights)\n print('Skyline formed by these buildings:', end=\"\\n\")\n print(skyline)\n# Main function of the project.\n\n\nmain()\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 20, "blob_id": "8a576c5724eb50592b65d063bccf26e3c93eb66d", "content_id": "1675311147a309bb03823903eae9f2b583b53748", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 20, "license_type": "no_license", "max_line_length": 20, "num_lines": 1, "path": "/README.md", "repo_name": "Macmaad/S-coding-challenge", "src_encoding": "UTF-8", "text": "# S-coding-challenge" } ]
2
ProfMalina/gpro_site
https://github.com/ProfMalina/gpro_site
264c3236a876dd42ecc93dc9ed3b8f586c771271
887e8d2798c3fd3b5e6108143b45209117535771
94d57c626a48c0594cb17e35f7a7e5dd6b2a1b64
refs/heads/master
2021-10-09T00:25:32.980179
2018-12-19T08:10:41
2018-12-19T08:10:41
114,656,214
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7407407164573669, "avg_line_length": 20.600000381469727, "blob_id": "e25aa95f1b3c6d387a2037965addd4a36ede22f9", "content_id": "9013eb6c1b7dd717c74a56d9030b3021854595fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 114, "license_type": "no_license", "max_line_length": 50, "num_lines": 5, "path": "/new/forms.py", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "from django import forms\n\n\nclass GetDrivers(forms.Form):\n id_driver = forms.CharField(label='id пилота')\n" }, { "alpha_fraction": 0.40088561177253723, "alphanum_fraction": 0.40088561177253723, "avg_line_length": 44.46979904174805, "blob_id": "797ac29e9cf4c5b34586c42e555dfe7109618d68", "content_id": "a5994de89bef5d21b9c6039a18cec8bc94ec4a81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7153, "license_type": "no_license", "max_line_length": 123, "num_lines": 149, "path": "/db.py", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "from sqlalchemy.ext.declarative import declarative_base\nimport json\nfrom sqlalchemy import Column, Integer, String, update\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nimport time\n\nBase = declarative_base()\n\n\nclass Drivers(Base):\n \"\"\"\n Класс описывающий объект пилота. Так же, осуществляется взаимодействие с БД.\n Описание полей таблицы ниже.\n \"\"\"\n __tablename__ = 'new_scandrivers'\n id_driver = Column(Integer, primary_key=True) # id пилота\n name = Column(String) # Имя\n nat = Column(String) # национальность\n oa = Column(Integer) # уровень\n con = Column(Integer) # концентрация\n tal = Column(Integer) # талант\n exp = Column(Integer) # опыт\n agg = Column(Integer) # агрессивность\n tei = Column(Integer) # ТЗ\n sta = Column(Integer) # выносливость\n cha = Column(Integer) # харизма\n mot = Column(Integer) # мотивация\n rep = Column(Integer) # репутация\n age = Column(Integer) # возраст\n wei = Column(Integer) # вес\n ret = Column(Integer) # карьера\n sal = Column(Integer) # зарплата\n fee = Column(Integer) # премия\n fav = Column(String) # любимая трасса\n off = Column(Integer) # предложения\n date = Column(String) # время добавления\n\n def __init__(self, id_driver, name, nat, oa, con, tal, exp, agg, tei, sta, cha, mot, rep, age, wei, ret, sal, fee, fav,\n off, date):\n self.id_driver = id_driver\n self.name = name\n self.nat = nat\n self.oa = oa\n self.con = con\n self.tal = tal\n self.exp = exp\n self.agg = agg\n self.tei = tei\n self.sta = sta\n self.cha = cha\n self.mot = mot\n self.rep = rep\n self.age = age\n self.wei = wei\n self.ret = ret\n self.sal = sal\n self.fee = fee\n self.fav = fav\n self.off = off\n self.date = date\n\n def _keys(self):\n return (self.id_driver, self.name, self.nat, self.oa, self.con, self.tal, self.exp, self.agg, self.tei,\n self.sta, self.cha, self.mot, self.rep, self.age, self.wei, self.ret, self.sal, self.fee, self.fav,\n self.off, self.date)\n\n def __eq__(self, other):\n return self._keys() == other._keys()\n\n def __hash__(self):\n return hash(self._keys())\n\n def __repr__(self):\n return \"<Drivers(id_driver='{}', name='{}', nat='{}', oa={}, con={}, \" \\\n \"tal={}, exp={}, agg={}, tei={}, sta={}, cha={}, mot={}, rep={}, age={}, wei={}, \" \\\n \"ret={}, sal={}, fee={}, fav='{}', off={}, date={})>\" .format(\n self.id_driver,\n self.name,\n self.nat,\n self.oa,\n self.con,\n self.tal,\n self.exp,\n self.agg,\n self.tei,\n self.sta,\n self.cha,\n self.mot,\n self.rep,\n self.age,\n self.wei,\n self.ret,\n self.sal,\n self.fee,\n self.fav,\n self.off,\n self.date)\n\n\nclass Database:\n \"\"\"\n Класс для обработки сессии SQLAlchemy.\n Так же включает в себя минимальный набор методов, вызываемых в управляющем классе.\n Названия методов говорящие.\n \"\"\"\n\n def __init__(self, obj):\n engine = create_engine(obj, echo=False)\n Session = sessionmaker(bind=engine)\n self.session = Session()\n self.drivers = []\n\n def get_drivers(self, drv):\n # date = int(time.mktime(time.localtime()))\n d = json.load(open(drv))\n date = d['Last updated']\n self.drivers += [Drivers(i['ID'], i['NAME'], i['NAT'], i['OA'], i['CON'], i['TAL'], i['EXP'], i['AGG'],\n i['TEI'], i['STA'], i['CHA'], i['MOT'], i['REP'], i['AGE'], i['WEI'], i['RET'],\n i['SAL'], i['FEE'], str(i['FAV']), i['OFF'], date) for i in d['drivers']]\n return self.drivers\n\n def add_driver(self, driver):\n self.session.add(driver)\n self.session.commit()\n\n def update_driver(self, drv):\n # d = json.load(open(drv))\n # date = int(time.mktime(time.localtime()))\n # date = d['Last updated']\n self.session.query(Drivers).filter_by(id_driver=drv.id_driver).update({\n \"id_driver\": drv.id_driver, \"name\": drv.name,\n \"nat\": drv.nat, \"oa\": drv.oa, \"con\": drv.con,\n \"tal\": drv.tal, \"exp\": drv.exp, \"agg\": drv.agg,\n \"tei\": drv.tei, \"sta\": drv.sta, \"cha\": drv.cha,\n \"mot\": drv.mot, \"rep\": drv.rep, \"age\": drv.age,\n \"wei\": drv.wei, \"ret\": drv.ret, \"sal\": drv.sal,\n \"fee\": drv.fee, \"fav\": drv.fav, \"off\": drv.off,\n \"date\": drv.date})\n self.session.commit()\n\n def find_driver(self, drv_id):\n if self.session.query(Drivers).filter_by(id_driver=drv_id).first():\n return self.session.query(Drivers).filter_by(id_driver=drv_id).first()\n else:\n return False\n\n def find_all_drivers(self):\n return self.session.query(Drivers).all()\n" }, { "alpha_fraction": 0.6475972533226013, "alphanum_fraction": 0.6475972533226013, "avg_line_length": 71.83333587646484, "blob_id": "980988468c6a30077b247c9e6de88fd7b8913cd8", "content_id": "2b701034275b9678bd5688348f6f3386aa344cac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 437, "license_type": "no_license", "max_line_length": 113, "num_lines": 6, "path": "/README.MD", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "http://gpro.net/ru/GetMarketFile.asp?market=drivers&type=json\n\nCREATE TABLE drivers ( id INTEGER PRIMARY KEY NOT NULL, name TEXT, nat TEXT, oa INTEGER, con INTEGER,\n tal INTEGER, exp INTEGER, agg INTEGER, tei INTEGER, sta INTEGER, cha INTEGER, mot INTEGER,\n rep INTEGER, age INTEGER, wei INTEGER, ret INTEGER, sal INTEGER, fee INTEGER, fav TEXT,\n off INTEGER, date TEXT)\n" }, { "alpha_fraction": 0.6839622855186462, "alphanum_fraction": 0.6839622855186462, "avg_line_length": 29.285715103149414, "blob_id": "202aa86c7b8cf8053d3d71ec8034156349872397", "content_id": "01163773d1e44fd7edf91dc9175bb55d6d021289", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "no_license", "max_line_length": 86, "num_lines": 14, "path": "/new/views.py", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "from django.template.response import TemplateResponse\nfrom .models import ScanDrivers\nfrom .forms import GetDrivers\n\n\ndef index(request):\n if request.method == 'POST':\n form = GetDrivers(request.POST)\n if form.is_valid():\n drv = ScanDrivers.objects.filter(id_driver=form.cleaned_data['id_driver'])\n\n else:\n form = GetDrivers()\n return TemplateResponse(request, \"new.html\", locals())\n" }, { "alpha_fraction": 0.6417582631111145, "alphanum_fraction": 0.6417582631111145, "avg_line_length": 29.33333396911621, "blob_id": "41b46d80e2c060e92f9c7fc7f08db4c5fcf83a53", "content_id": "1959aedbb8ffff4653d02b8c69a96db05b963dd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 466, "license_type": "no_license", "max_line_length": 63, "num_lines": 15, "path": "/site_drv/views.py", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "from django.template.response import TemplateResponse\nfrom .models import SiteDrv\nfrom .forms import AddNews\n\n\ndef index(request):\n if request.method == 'POST':\n form = AddNews(request.POST)\n if form.is_valid():\n name = form.cleaned_data['name']\n # name = request.POST # не безопасно\n else:\n form = AddNews()\n drv = SiteDrv.objects.all()\n return TemplateResponse(request, \"drv_list.html\", locals())\n" }, { "alpha_fraction": 0.7232142686843872, "alphanum_fraction": 0.7366071343421936, "avg_line_length": 31, "blob_id": "8bdeb459742d3505b1d6da18fd16a15d502e2833", "content_id": "92176a90566ef06eda4a3b041174f9292b9b42da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 69, "num_lines": 7, "path": "/site_drv/models.py", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass SiteDrv(models.Model):\n name = models.CharField(verbose_name=u'Название', max_length=100)\n text = models.TextField(verbose_name=u'Контент')\n create_data = models.DateTimeField()\n" }, { "alpha_fraction": 0.6111459136009216, "alphanum_fraction": 0.6111459136009216, "avg_line_length": 28.574073791503906, "blob_id": "3809aadd361c209f9bb16de34cfcb8c5831ac5d0", "content_id": "8b2c83f772647fd20db98c531a763be4a369bfb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1743, "license_type": "no_license", "max_line_length": 74, "num_lines": 54, "path": "/main.py", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "import urllib.request\nimport gzip\nimport shutil\nfrom db import Database\nimport configparser\nimport logging, logging.config, logging.handlers\nimport time\nimport json\n\nLINK = 'http://gpro.net/ru/GetMarketFile.asp?market=drivers&type=json'\nGZ_NAME = 'DriversMarket.json.gz'\nFILE_NAME = 'DriversMarket.json'\n\nlogging.config.fileConfig('/root/gpro_site/log_main.conf')\nlogging.getLogger('main')\n\n\ndef downloader():\n \"\"\"\n Скачивает архив пилотов\n \"\"\"\n urllib.request.urlretrieve(LINK, GZ_NAME)\n\n\ndef unpacker():\n \"\"\"\n Разархивирует архив gz\n \"\"\"\n with gzip.open(GZ_NAME, 'rb') as f_in, open(FILE_NAME, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n\nif __name__ == '__main__':\n try:\n start = time.clock() # засекаем время\n downloader() # качаем файл\n unpacker() # распаковываем\n config = configparser.ConfigParser() # парсим конфиг\n config.read('/root/gpro_site/config') # читаем\n db = Database(config['Database']['Path']) # коннектимся к бд\n drv = db.get_drivers(FILE_NAME) # готовим пилотов для бд\n for i in drv: # отправляем пилотов в бд\n d = json.load(open(FILE_NAME))\n i.date = d['Last updated']\n if not db.find_driver(i.id_driver):\n logging.debug(\"New driver: {}\".format(i))\n db.add_driver(i)\n else:\n logging.debug(\"Update driver: {}\".format(i))\n db.update_driver(i)\n elapsed = time.clock() - start\n logging.info(elapsed)\n except Exception as e:\n logging.exception(e)\n" }, { "alpha_fraction": 0.4571428596973419, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 16.5, "blob_id": "be345a3f5b20b7ddbbd6a80731c0c02ddeef05af", "content_id": "fd5e499f97796176ff9855eebd41f127f214f964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 35, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/requirements.txt", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "sqlalchemy==1.1.14\ndjango>=1.11.15\n" }, { "alpha_fraction": 0.5674212574958801, "alphanum_fraction": 0.5821850299835205, "avg_line_length": 47.380950927734375, "blob_id": "7fa7e8b47ff9517d5e3834d81da85839136e6ad3", "content_id": "7929501487e38317eb7146fed1c41a0dcea54fc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2243, "license_type": "no_license", "max_line_length": 123, "num_lines": 42, "path": "/new/migrations/0001_initial.py", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.5 on 2017-10-10 11:40\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='ScanDrivers',\n fields=[\n ('id_driver', models.IntegerField(default=0, primary_key=True, serialize=False, verbose_name='id пилота')),\n ('name', models.CharField(max_length=100, verbose_name='Имя')),\n ('nat', models.CharField(max_length=100, verbose_name='Национальность')),\n ('oa', models.IntegerField(verbose_name='Уровень')),\n ('con', models.IntegerField(verbose_name='Концентрация')),\n ('tal', models.IntegerField(verbose_name='Талант')),\n ('exp', models.IntegerField(verbose_name='Опыт')),\n ('agg', models.IntegerField(verbose_name='Агрессивность')),\n ('tei', models.IntegerField(verbose_name='Технические знания')),\n ('sta', models.IntegerField(verbose_name='Выносливость')),\n ('cha', models.IntegerField(verbose_name='Харизма')),\n ('mot', models.IntegerField(verbose_name='Мотивация')),\n ('rep', models.IntegerField(verbose_name='Репутация')),\n ('age', models.IntegerField(verbose_name='Возраст')),\n ('wei', models.IntegerField(verbose_name='Вес')),\n ('ret', models.IntegerField(verbose_name='Заканчивает карьеру')),\n ('sal', models.IntegerField(verbose_name='Зарплата')),\n ('fee', models.IntegerField(verbose_name='Премия')),\n ('fav', models.CharField(max_length=100, verbose_name='id любимых трасс')),\n ('off', models.IntegerField(verbose_name='Предложений работы')),\n ('date', models.CharField(max_length=100, verbose_name='Время скачивания списка')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7444444298744202, "alphanum_fraction": 0.7444444298744202, "avg_line_length": 17, "blob_id": "c980f9404cb53957ef9f2474062783af49014b83", "content_id": "379d2783830d0c1a45308ff0231cab47d6128a89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 90, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/site_drv/apps.py", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass SiteDrvConfig(AppConfig):\n name = 'site_drv'\n" }, { "alpha_fraction": 0.8241758346557617, "alphanum_fraction": 0.8241758346557617, "avg_line_length": 21.75, "blob_id": "56a1662e66f950d558cde618c4e6f6c3062e9ca0", "content_id": "57e88df681b515c85d7035ebdf5931195a8e7845", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 91, "license_type": "no_license", "max_line_length": 32, "num_lines": 4, "path": "/site_drv/admin.py", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import SiteDrv\n\nadmin.site.register(SiteDrv)\n" }, { "alpha_fraction": 0.7109375, "alphanum_fraction": 0.7109375, "avg_line_length": 20.33333396911621, "blob_id": "832f5ff290033932eee5a131cfdf61db98b9a1c0", "content_id": "a91844b1a67bd43241d31dfc35df4bde564e0177", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 136, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/site_drv/forms.py", "repo_name": "ProfMalina/gpro_site", "src_encoding": "UTF-8", "text": "from django import forms\n\n\nclass AddNews(forms.Form):\n name = forms.CharField(label=u'Название')\n text = forms.Textarea()\n" } ]
12
zach-hunt/giraffe-in-fridge
https://github.com/zach-hunt/giraffe-in-fridge
80b569ad21b7178899d2ca3baf81391077ccb465
5bbd58915ddf410dd2c3f265ceb9744cb4714b5f
e94f505283e33b3b79f982435ff044843a3a5f39
refs/heads/main
2022-12-28T10:26:15.293162
2020-10-18T03:15:04
2020-10-18T03:15:04
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6267062425613403, "alphanum_fraction": 0.6320474743843079, "avg_line_length": 39.119049072265625, "blob_id": "597c3ab1ac75fdf0a080609d60c320025a80da30", "content_id": "ef3c369453cf7ac000ed62cbbb40e5150c809719", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1685, "license_type": "no_license", "max_line_length": 118, "num_lines": 42, "path": "/csv_to_database.py", "repo_name": "zach-hunt/giraffe-in-fridge", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sqlalchemy import create_engine\n\n\ndef sort_csv(filename):\n df = pd.read_csv(f\"./{filename}\")\n username = df.iloc[0, 0]\n df[\"Username\"] = username\n df[\"Datetime\"] = pd.to_datetime(df.Datetime).dt.strftime(\"%d-%m-%Y %H:%S\").astype(str)\n df.drop(axis=0, index=[0, len(df.index) - 1], inplace=True)\n df.drop([\"Beginning Balance\", \"Ending Balance\", \"Disclaimer\"], axis=1, inplace=True)\n df.update(df[[\"Amount (fee)\", \"Statement Period Venmo Fees\", \"Year to Date Venmo Fees\"]].fillna(0))\n df.update(df[[\"Destination\", \"Funding Source\"]].fillna(\"\"))\n df[\"Amount (total)\"] = df[\"Amount (total)\"].str.strip(\"$()\")\n df[\"Note\"] = df[\"Note\"].str.capitalize()\n df.columns = df.columns.str.replace(r\"(\\()|(\\))\", \"\", regex=True).str.strip(\" \").str.replace(\" \", \"_\").str.lower()\n df = df.rename({\"from\": \"sender\", \"id\": \"transaction_id\", \"type\": \"transaction_type\", \"to\": \"recipient\"}, axis=1)\n\n df.sort_values('datetime')\n return df\n\n\ndef create_database(datasource, dbname: str = \"transactions\") -> None:\n \"\"\"\n Generates a database from the datasource\n :param datasource: CSV Filename or Pandas Dataframe\n :param dbname: database file and table name\n :return: None\n \"\"\"\n if type(datasource) is str:\n df = sort_csv(filename=datasource)\n elif type(datasource) is pd.DataFrame:\n df = datasource\n else:\n raise ValueError(f\"{datasource} must be a CSV filename or Pandas.DataFrame\")\n\n s = create_engine(f\"sqlite:///database/{dbname}.db\")\n df.to_sql(name=dbname, con=s, if_exists=\"replace\", index=True)\n\n\nif __name__ == \"__main__\":\n create_database(\"./ACTS Challenge 1 Sample.csv\")\n" }, { "alpha_fraction": 0.5196078419685364, "alphanum_fraction": 0.5718954205513, "avg_line_length": 18.1875, "blob_id": "471dc019fc709fd0627d61455e94def5e9d69add", "content_id": "969e681587879f3c508b90f220144fafc9b7af96", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 306, "license_type": "permissive", "max_line_length": 45, "num_lines": 16, "path": "/static/custom.js", "repo_name": "zach-hunt/giraffe-in-fridge", "src_encoding": "UTF-8", "text": "jQuery(document).ready(function($) {\n\n\t$('#featured_items').slick({\n\t\tdraggable: true,\n\t arrows: true,\n\t dots: false,\n\t fade: true,\n\t speed: 900,\n\t infinite: true,\n\t cssEase: 'cubic-bezier(0.7, 0, 0.3, 1)',\n\t touchThreshold: 100,\n\t autoplay: true,\n\t autoplaySpeed: 5000\n\t});\n\n});" }, { "alpha_fraction": 0.6095646023750305, "alphanum_fraction": 0.6302641034126282, "avg_line_length": 35.842105865478516, "blob_id": "68f4340cab9aa63af1a0a57c3bc6c6edc8c4b56f", "content_id": "840e59c34e79c472675159e33f02f689bb5bd3a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1401, "license_type": "no_license", "max_line_length": 118, "num_lines": 38, "path": "/queries.py", "repo_name": "zach-hunt/giraffe-in-fridge", "src_encoding": "UTF-8", "text": "import sqlalchemy as db\nimport pandas as pd\n\ndef sort_csv(filename):\n df = pd.read_csv(f\"./{filename}\")\n username = df.iloc[0, 0]\n df[\"Username\"] = username\n df[\"Datetime\"] = pd.to_datetime(df.Datetime).dt.strftime(\"%d-%m-%Y %H:%S\").astype(str)\n df.drop(axis=0, index=[0, len(df.index) - 1], inplace=True)\n df.drop([\"Beginning Balance\", \"Ending Balance\", \"Disclaimer\"], axis=1, inplace=True)\n df.update(df[[\"Amount (fee)\", \"Statement Period Venmo Fees\", \"Year to Date Venmo Fees\"]].fillna(0))\n df.update(df[[\"Destination\", \"Funding Source\"]].fillna(\"\"))\n df[\"Amount (total)\"] = df[\"Amount (total)\"].str.strip(\"$\")\n df[\"Note\"] = df[\"Note\"].str.capitalize()\n df.columns = df.columns.str.replace(r\"(\\()|(\\))\", \"\", regex=True).str.strip(\" \").str.replace(\" \", \"_\").str.lower()\n df = df.rename({\"from\": \"sender\", \"id\": \"transaction_id\", \"type\": \"transaction_type\", \"to\": \"recipient\"}, axis=1)\n\n df.sort_values('datetime')\n return df\n\n\nfile = sort_csv('./ACTS Challenge 1 Sample.csv')\nfor row in file.values:\n\tusername = row[0]\n\ttransaction_id = row[1]\n\t_datetime = row[2]\n\ttransaction_type = row[3]\n\tstatus = row[4]\n\tnote = row[5]\n\tsender = row[6]\n\trecipient = row[7]\n\tamount_total = row[8]\n\tamount_fee = row[9]\n\tfunding_source = row[10]\n\tdestination = row[11]\n\tstatement_period_venmo_fees = row[12]\n\tterminal_location = row[13]\n\tyear_to_date_venmo_fees = row[14]\n\t" }, { "alpha_fraction": 0.6839408278465271, "alphanum_fraction": 0.691544771194458, "avg_line_length": 32.704734802246094, "blob_id": "d888996b9fc5a9dc6f326b96f195349505156549", "content_id": "101ddccd0389e4645fab89617077ccd1d74782c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12099, "license_type": "no_license", "max_line_length": 245, "num_lines": 359, "path": "/app.py", "repo_name": "zach-hunt/giraffe-in-fridge", "src_encoding": "UTF-8", "text": "from flask_login import LoginManager, login_user, current_user, login_required, logout_user, UserMixin\nfrom flask import Flask,jsonify,request,render_template,Response,flash,redirect,url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom flask_wtf import Form\nfrom wtforms import TextField, BooleanField, validators, PasswordField, SubmitField, SelectField, FileField, \\\n\tSelectMultipleField, BooleanField, DateTimeField, TextAreaField\nfrom werkzeug.security import generate_password_hash, \\\n\t check_password_hash\nimport datetime\nfrom sqlalchemy import create_engine\n#from wtforms.validators import Required\nfrom werkzeug.utils import secure_filename\nimport os\nimport uuid\nimport string\nimport pandas as pd\nimport json\n\nfrom decimal import *\n\napp = Flask(__name__)\n\nDATABASE_PATH = 'sqlite:///database/venmodata.db'\n\nUPLOAD_FOLDER = os.path.join(app.instance_path, 'uploads')\n# only allow images to be uploaded\nALLOWED_EXTENSIONS = set(['csv'])\ndef allowed_file(filename):\n\treturn '.' in filename and \\\n\t\t filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\napp = Flask(__name__)\ndb = SQLAlchemy(app)\n\napp.config.update(dict(\n\tSECRET_KEY=\"powerful secretkey\",\n\tWTF_CSRF_SECRET_KEY=\"a csrf secret key\"\n))\n\napp.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_PATH\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\ne = create_engine(DATABASE_PATH)\n\nlogin_manager = LoginManager()\n\nCOMPANY = {\n\t'name': 'Giraffe in Fridge',\n\t'motto': 'GIF is pronounced with a hard G.',\n\t'initials': 'GIF'\n}\n\n\n@login_manager.user_loader\ndef get_user(ident):\n\treturn User.query.get(int(ident))\n\nclass User(db.Model, UserMixin):\n\t__tablename__ = 'users'\n\tid = db.Column(db.Integer, primary_key=True)\n\tusername = db.Column(db.String(32))\n\tfirstname = db.Column(db.String(32))\n\tlastname = db.Column(db.String(32))\n\temail = db.Column(db.String(32))\n\tpassword = db.Column(db.String(32))\n\n\tdef __init__(self, username, firstname, lastname, email, password):\n\t\tself.username = username\n\t\tself.set_password(password)\n\t\tself.email = email\n\t\tself.firstname = firstname\n\t\tself.lastname = lastname\n\n\tdef set_password(self, password):\n\t\tself.password = generate_password_hash(password)\n\n\tdef check_password(self, password):\n\t\treturn check_password_hash(self.password, password)\n\t\t#return password == self.password\n\nclass VenmoData(db.Model):\n\t__tablename__ = 'transactions'\n\tid = db.Column(db.Integer, primary_key=True)\n\tusername = db.Column(db.String(32))\n\ttransaction_id = db.Column(db.Float())\n\tdatetime = db.Column(db.String(32))\n\ttransaction_type = db.Column(db.String(32))\n\tstatus = db.Column(db.String(32))\n\tnote = db.Column(db.String(128))\n\tsender = db.Column(db.String(32))\n\trecipient = db.Column(db.String(32))\n\tamount_total = db.Column(db.Float())\n\tfunding_source = db.Column(db.String(32))\n\tdestination = db.Column(db.String(32))\n\tstatement_period_venmo_fees = db.Column(db.Float())\n\tterminal_location = db.Column(db.String(32))\n\tyear_to_date_venmo_fees = db.Column(db.Float())\n\n\t@property\n\tdef formatted_date(self):\n\t\tdatetime_object = datetime.datetime.strptime(self.datetime, '%d-%m-%Y %H:%M')\n\t\treturn datetime_object.strftime(\"%B %d, %Y\")\n\n\t@property\n\tdef formatted_amount_total(self):\n\t\treturn '{:0.2f}'.format(self.amount_total)\n\n\tdef as_dict(self):\n\t\treturn {c.name: getattr(self, c.name) for c in self.__table__.columns}\n\n\tdef __init__(self, username, transaction_id, _datetime, transaction_type, status, note, sender, recipient, amount_total, amount_fee, funding_source, destination, statement_period_venmo_fees, terminal_location, year_to_date_venmo_fees):\n\t\tself.username = username\n\t\tself.transaction_id = transaction_id\n\t\tself.datetime = _datetime\n\t\tself.transaction_type = transaction_type\n\t\tself.status = status\n\t\tself.note = note\n\t\tself.sender = sender\n\t\tself.recipient = recipient\n\t\tself.amount_total = amount_total\n\t\tself.amount_fee = amount_fee\n\t\tself.funding_source = funding_source\n\t\tself.destination = destination\n\t\tself.statement_period_venmo_fees = statement_period_venmo_fees\n\t\tself.terminal_location = terminal_location\n\t\tself.year_to_date_venmo_fees = year_to_date_venmo_fees\n\n\nclass LoginForm(Form):\n\tusername = TextField('Username', [validators.Required()])\n\tpassword = PasswordField('Password', [validators.Required()])\n\tsubmit = SubmitField('Log In')\n\n\tdef __init__(self, *args, **kwargs):\n\t\tForm.__init__(self, *args, **kwargs)\n\t\tself.user = None\n\n\tdef validate(self):\n\t\tuser = User.query.filter_by(\n\t\t\tusername=self.username.data).first()\n\t\tif user is None:\n\t\t\tself.password.errors = ['Invalid username or password']\n\t\t\treturn False\n\n\t\tif not user.check_password(self.password.data):\n\t\t\tself.password.errors = ['Invalid username or password']\n\t\t\treturn False\n\n\t\tself.user = user\n\t\tlogin_user(user)\n\t\treturn True\n\nclass RegisterForm(Form):\n\tusername = TextField('Username', validators=[validators.Required()])\n\temail = TextField('E-Mail', validators=[validators.Required(), validators.Email()])\n\tpassword = PasswordField('Password', [\n\t\tvalidators.Required(),\n\t\tvalidators.EqualTo('confirm', message='Passwords must match')\n\t])\n\tconfirm = PasswordField('Repeat Password')\n\tfirstname = TextField('First Name', validators=[validators.Required(), validators.Length(min=8, max=32, message=\"Password must be between 8 and 32 characters long\")])\n\tlastname = TextField('Last Name', validators=[validators.Required()])\n\tsubmit = SubmitField('Register Now')\n\n\tdef __init__(self, *args, **kwargs):\n\t\tForm.__init__(self, *args, **kwargs)\n\n\tdef validate(self):\n\t\tif self.username.data and self.password.data and self.confirm.data:\n\t\t\tif User.query.filter_by(username=self.username.data).first():\n\t\t\t\tflash('An account with that username already exists.', category='red')\n\t\t\t\treturn False\n\t\t\tif User.query.filter_by(email=self.email.data).first():\n\t\t\t\tflash('An account with that email already exists.', category='red')\n\t\t\t\treturn False\n\t\t\treturn True\n\t\treturn False\n\nclass FileUploadForm(Form):\n\tfile = FileField('Upload Venmo CSV File', [validators.Required()])\n\tsubmit = SubmitField('Upload')\n\n\tdef __init__(self, *args, **kwargs):\n\t\tForm.__init__(self, *args, **kwargs)\n\n\tdef validate(self):\n\t\tif not self.file:\n\t\t\treturn False\n\t\treturn True\n\nclass SortTableForm(Form):\n\tsort_by = SelectField('Sort Transactions', choices=[('id', 'ID ASC'), ('iddesc', 'ID DSC'), ('date', 'Date ASC'), ('datedesc', 'Date DSC'), ('amount', 'Amount ASC'), ('amountdesc', 'Amount DSC')])\n\tsubmit = SubmitField('Sort')\n\n\tdef __init__(self, *args, **kwargs):\n\t\tForm.__init__(self, *args, **kwargs)\n\n\tdef validate(self):\n\t\tif not self.sort_by:\n\t\t\treturn False\n\t\treturn True\n\[email protected]('/', methods=['GET', 'POST'])\ndef home():\n\tform = RegisterForm()\n\tif form.validate_on_submit():\n\t\tif form.validate():\n\t\t\tuser = User(form.username.data, form.firstname.data, form.lastname.data, form.email.data, form.password.data)\n\t\t\tdb.session.add(user)\n\t\t\tdb.session.commit()\n\t\t\tflash(\"You're now registered!\", category='green')\n\t\t\treturn redirect('/login')\n\t\telse:\n\t\t\tflash(\"Error: Check your inputs\", category='red')\n\treturn render_template('index.html', company=COMPANY, form=form)\n\[email protected]('/login', methods=['GET', 'POST'])\ndef admin_login():\n\tform = LoginForm()\n\tif form.validate_on_submit():\n\t\tif form.validate():\n\t\t\tflash(\"You're now logged in!\", category='green')\n\t\t\treturn redirect('/dashboard')\n\t\telse:\n\t\t\tflash(\"No user with that email/password combo\", category='red')\n\treturn render_template('login.html', form=form, company=COMPANY)\n\[email protected]('/admin', methods=['GET', 'POST'])\ndef login():\n\tform = LoginForm()\n\tif form.validate_on_submit():\n\t\tif form.validate():\n\t\t\tflash(\"You're now logged in!\", category='green')\n\t\t\treturn redirect('/dashboard')\n\t\telse:\n\t\t\tflash(\"No user with that email/password combo\", category='red')\n\treturn render_template('login.html', form=form, company=COMPANY)\n\n\ndef sort_csv(file):\n df = pd.read_csv(file)\n username = df.iloc[0, 0]\n df[\"Username\"] = username\n df[\"Datetime\"] = pd.to_datetime(df.Datetime).dt.strftime(\"%d-%m-%Y %H:%S\").astype(str)\n df.drop(axis=0, index=[0, len(df.index) - 1], inplace=True)\n df.drop([\"Beginning Balance\", \"Ending Balance\", \"Disclaimer\"], axis=1, inplace=True)\n df.update(df[[\"Amount (fee)\", \"Statement Period Venmo Fees\", \"Year to Date Venmo Fees\"]].fillna(0))\n df.update(df[[\"Destination\", \"Funding Source\"]].fillna(\"\"))\n df[\"Amount (total)\"] = df[\"Amount (total)\"].str.strip(\"$()\")\n df[\"Note\"] = df[\"Note\"].str.capitalize()\n df.columns = df.columns.str.replace(r\"(\\()|(\\))\", \"\", regex=True).str.strip(\" \").str.replace(\" \", \"_\").str.lower()\n df = df.rename({\"from\": \"sender\", \"id\": \"transaction_id\", \"type\": \"transaction_type\", \"to\": \"recipient\"}, axis=1)\n\n df.sort_values('datetime')\n return df\n\n\[email protected]('/dashboard', methods=['GET', 'POST'])\n@login_required\ndef dashboard():\n\tform = FileUploadForm()\n\tif request.files:\n\t\tif form.validate_on_submit():\n\t\t\tif form.validate():\n\t\t\t\t# check if the post request has the file part)\n\t\t\t\tfile = request.files['file']\n\t\t\t\t# if user does not select file, browser also\n\t\t\t\t# submit an empty part without filename\n\t\t\t\tif file.filename == '':\n\t\t\t\t\tflash('No selected file', category='red')\n\t\t\t\t\treturn redirect(request.url)\n\t\t\t\tif file and allowed_file(file.filename):\n\t\t\t\t\treadcsv = sort_csv(file)\n\t\t\t\t\tfor row in readcsv.values:\n\t\t\t\t\t\tusername = row[0] or ''\n\t\t\t\t\t\ttransaction_id = row[1] or 0\n\t\t\t\t\t\t_datetime = row[2] or ''\n\t\t\t\t\t\ttransaction_type = row[3] or ''\n\t\t\t\t\t\tstatus = row[4] or ''\n\t\t\t\t\t\tnote = row[5] or ''\n\t\t\t\t\t\tsender = row[6] or ''\n\t\t\t\t\t\trecipient = row[7] or ''\n\t\t\t\t\t\tamount_total = row[8] or 0.0\n\t\t\t\t\t\tamount_fee = row[9] or 0.0\n\t\t\t\t\t\tfunding_source = row[10] or ''\n\t\t\t\t\t\tdestination = row[11] or ''\n\t\t\t\t\t\tstatement_period_venmo_fees = row[12] or 0\n\t\t\t\t\t\tterminal_location = row[13] or ''\n\t\t\t\t\t\tyear_to_date_venmo_fees = row[14] or 0\n\n\t\t\t\t\t\ttransaction = VenmoData(username, transaction_id, _datetime, transaction_type, status, note, sender, recipient, amount_total, amount_fee, funding_source, destination, statement_period_venmo_fees, terminal_location, year_to_date_venmo_fees)\n\t\t\t\t\t\tdb.session.add(transaction)\n\n\t\t\t\t\tdb.session.commit()\n\n\t\t\t\tflash('Upload successful', category='green')\n\t\t\t\treturn redirect('/dashboard')\n\t\t\telse:\n\t\t\t\tflash('Upload failed', category='red')\n\n\tsort_form = SortTableForm()\n\tif sort_form.validate_on_submit():\n\t\tif sort_form.validate():\n\t\t\tkey = sort_form.sort_by.data\n\t\t\tif key == 'id':\n\t\t\t\tdata = VenmoData.query.order_by(VenmoData.id.asc()).all()\n\t\t\telif key == 'iddesc':\n\t\t\t\tdata = VenmoData.query.order_by(VenmoData.id.desc()).all()\n\t\t\telif key == 'date':\n\t\t\t\tdata = VenmoData.query.order_by(VenmoData.datetime.asc()).all()\n\t\t\telif key == 'datedesc':\n\t\t\t\tdata = VenmoData.query.order_by(VenmoData.datetime.desc()).all()\n\t\t\telif key == 'amount':\n\t\t\t\tdata = VenmoData.query.order_by(VenmoData.amount_total.asc()).all()\n\t\t\telif key == 'amountdesc':\n\t\t\t\tdata = VenmoData.query.order_by(VenmoData.amount_total.desc()).all()\n\t\telse:\n\t\t\tdata = VenmoData.query.order_by(VenmoData.id).all()\n\telse:\n\t\tdata = VenmoData.query.order_by(VenmoData.id).all()\n\n\treturn render_template('dashboard.html', company=COMPANY, transactions=data, form=form, sort_form=sort_form)\n\[email protected](\"/logout\")\n@login_required\ndef logout():\n\tlogout_user()\n\treturn redirect('/')\n\[email protected]('/signup', methods=['GET', 'POST'])\ndef signup():\n\tform = RegisterForm()\n\tif form.validate_on_submit():\n\t\tif form.validate():\n\t\t\tuser = User(form.username.data, form.firstname.data, form.lastname.data, form.email.data, form.password.data)\n\t\t\tdb.session.add(user)\n\t\t\tdb.session.commit()\n\t\t\tflash(\"You're now registered!\", category='green')\n\t\t\treturn redirect('/login')\n\t\telse:\n\t\t\tflash(\"Error: Check your inputs\", category='red')\n\treturn render_template('register.html', form=form, company=COMPANY)\n\[email protected]('/about')\ndef about():\n\treturn render_template('about.html', company=COMPANY)\n\[email protected](404)\ndef page_not_found(e):\n\treturn render_template('404.html', company=COMPANY)\n\n\nlogin_manager.init_app(app)\n\nif __name__ == \"__main__\":\n\t# app.run(host=\"0.0.0.0\", debug=True)\n\tapp.run(host='0.0.0.0', port=80)\n\t# pass" }, { "alpha_fraction": 0.8666666746139526, "alphanum_fraction": 0.8666666746139526, "avg_line_length": 9.600000381469727, "blob_id": "7973eb5933b623a2dfea0e87ce08ef7387608007", "content_id": "fbce0d80c9441182df78766bf2a3618903219fcd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 105, "license_type": "no_license", "max_line_length": 16, "num_lines": 10, "path": "/requirements.txt", "repo_name": "zach-hunt/giraffe-in-fridge", "src_encoding": "UTF-8", "text": "flask_login\nflask\nflask_restless\nflask_sqlalchemy\nflask_cors\nflask_wtf\npandas\nwtforms\nwerkzeug\nsqlalchemy" }, { "alpha_fraction": 0.7757296562194824, "alphanum_fraction": 0.7834101319313049, "avg_line_length": 55.60869598388672, "blob_id": "3df4a441d3667f04ebe622dbc8507e121dbedd9d", "content_id": "a6f89f3af0800ee94c39aa2b5d24bd9680251de0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1302, "license_type": "no_license", "max_line_length": 137, "num_lines": 23, "path": "/README.md", "repo_name": "zach-hunt/giraffe-in-fridge", "src_encoding": "UTF-8", "text": "# Giraffe - A Venmo CSV Dashboard\n#### Indigitous #Hack 2020\n\nGiraffe is a Venmo CSV Dashboard providing a clean interface for visualizing transaction history.\n\n\n### Use\nFirst, log onto [Venmo](https://www.venmo.com). Then, access your account `Statements` from the top menu bar.\n![Venmo Statements](https://github.com/voidiker66/giraffe-in-fridge/blob/main/Documentation/VenmoDashboard.png?raw=True)\nFrom there, click `Download CSV`. Save that file anywhere - we're going to need it in a second!\n\nNow, we're going to upload that CSV to the Giraffe website: [Giraffe](https://www.example.com)\n\nFirst, create an account, and then sign in!\n![Landing Page](https://github.com/voidiker66/giraffe-in-fridge/blob/main/Documentation/Homepage.png?raw=True)\nOnce you're signed in, click home to get to your dashboard. Giraffe provides a clean interface for visualizing Venmo transaction history.\n\nYou can upload the CSV from easlier with the dialog in the upper right: `Upload Venmo CSV File`\n![Homepage](https://github.com/voidiker66/giraffe-in-fridge/blob/main/Documentation/DashboardHome.png?raw=True)\nFrom there, you can view transactions and visualize payment statistics!\n\n### Future\nGiraffe can be expanded relatively easily to provide additional visualizations, such as spending by user and time period.\n" } ]
6
rojter-tech/podme_tracker
https://github.com/rojter-tech/podme_tracker
80e72954203d6d2fcad7c863fec3b78fcf1feb6e
2289bbd476c55432fdec13e6dc056d37d9c91458
5d932722f8a59445057bd4f782d6b66ddb11becc
refs/heads/master
2021-02-09T12:57:35.054763
2020-03-02T05:12:17
2020-03-02T05:12:17
244,285,418
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5779967308044434, "alphanum_fraction": 0.6026272773742676, "avg_line_length": 22.461538314819336, "blob_id": "ef2849a92341b8f30d46891a568bfe4af3b5f4f4", "content_id": "2028c0d4eba726937d305251bd214f30edac5878", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 609, "license_type": "permissive", "max_line_length": 52, "num_lines": 26, "path": "/download_pods.py", "repo_name": "rojter-tech/podme_tracker", "src_encoding": "UTF-8", "text": "from utils import *\n\nGET_MP3_URL = re.compile(r'.*(\\.mp3)')\n\ndef get_content_url(episode):\n global urls\n del driver.requests\n driver.get(PODME_URL+\"?episode=\"+episode)\n for request in driver.requests:\n if request.response:\n request_path = request.path\n if GET_MP3_URL.match(str(request_path)):\n print('url found:', request_path)\n urls.append(request_path)\n del driver.requests\n break\n\n\nurls = []\ndriver = establish_connection()\nget_content_url('221266')\nget_content_url('221592')\ndriver.close()\n\n\nprint(urls)" }, { "alpha_fraction": 0.7013574838638306, "alphanum_fraction": 0.7123464941978455, "avg_line_length": 34.181819915771484, "blob_id": "9003d161aa312d0bd9cbc1aa4706ee02b57ffd31", "content_id": "babfae9cb72d27e2f9783223bf8dd8e3002955de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1547, "license_type": "permissive", "max_line_length": 90, "num_lines": 44, "path": "/utils.py", "repo_name": "rojter-tech/podme_tracker", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nimport os, re, sys, json, codecs\nfrom seleniumwire import webdriver\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\nfrom time import sleep\n\nPODME_URL=r'https://podme.com/'\n\nLOGIN_PAGE=r'/html/body/div/div/div[1]/nav/button'\nEMAIL=r'//*[@id=\"logonIdentifier\"]'\nPASSWORD=r'//*[@id=\"password\"]'\nLOGIN=r'//*[@id=\"next\"]'\nMY_PODCASTS=r'/html/body/div/div/nav/div[2]/a[2]'\nFOOTER=r'/html/body/div/div/footer'\n\n\ndef store_dict_as_json(dictionary, filepath):\n path = os.path.dirname(filepath)\n if not os.path.exists(path):\n os.mkdir(path)\n with codecs.open(filepath, 'w', \"utf-8\") as f:\n json_string = json.dumps(dictionary, sort_keys=True, indent=4, ensure_ascii=False)\n f.write(json_string)\n\ndef wait_for_access(driver, XPATH, timer=20):\n element = WebDriverWait(driver, timer).until(\n EC.element_to_be_clickable((By.XPATH, XPATH)))\n return element\n\n\ndef establish_connection():\n driver = webdriver.Firefox(seleniumwire_options={'verify_ssl': False})\n driver.get(PODME_URL)\n\n wait_for_access(driver, LOGIN_PAGE, timer=20).click()\n wait_for_access(driver, EMAIL, timer=20).send_keys('[email protected]')\n wait_for_access(driver, PASSWORD, timer=20).send_keys('DownloadPodme123')\n wait_for_access(driver, LOGIN, timer=20).click()\n wait_for_access(driver, MY_PODCASTS, timer=20)\n\n return driver" }, { "alpha_fraction": 0.8181818127632141, "alphanum_fraction": 0.8181818127632141, "avg_line_length": 26.5, "blob_id": "20785ec6f8683852658423adb24efe6b2b64ce69", "content_id": "4f05f8c2910bada8956a4536d1b53d15ae6a87f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 55, "license_type": "permissive", "max_line_length": 38, "num_lines": 2, "path": "/README.md", "repo_name": "rojter-tech/podme_tracker", "src_encoding": "UTF-8", "text": "# podme_tracker\nscrape and download content from podme\n" }, { "alpha_fraction": 0.6248477697372437, "alphanum_fraction": 0.6309378743171692, "avg_line_length": 27.34482765197754, "blob_id": "b08db5dbabe848ed742907799d0f372f1e0ea238", "content_id": "d04bf20ce11bb5dbd55d60f55ba379cc5420caa1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 821, "license_type": "permissive", "max_line_length": 67, "num_lines": 29, "path": "/gather_pods.py", "repo_name": "rojter-tech/podme_tracker", "src_encoding": "UTF-8", "text": "from utils import *\n\ndriver = establish_connection()\nwait_for_access(driver, MY_PODCASTS, timer=20).click()\nwait_for_access(driver, FOOTER, timer=20).click()\n\npod_dict = {}\npod_ids = []\npod_names = []\npod_urls = []\n\nfor podelement in driver.find_elements_by_tag_name('a'):\n if podelement.get_attribute('class') == 'pod-item':\n image_element=podelement.find_element_by_tag_name('img')\n\n name = image_element.get_attribute('alt')\n url = podelement.get_attribute('href')\n pod_id = url.split('/')[-1]\n\n pod_names.append(name)\n pod_urls.append(url)\n pod_ids.append(pod_id)\n \n\nfor pod_id, pod_name, pod_url in zip(pod_ids, pod_names, pod_urls):\n pod_dict[pod_id] = {'name': pod_name, 'url': pod_url}\n\n\nstore_dict_as_json(pod_dict, os.path.join('data', 'pods.json'))" } ]
4
irpepper/Smart-Mirror
https://github.com/irpepper/Smart-Mirror
179e652c023649873d55d458e9e05e937bb2eb76
1ff31aecf27b7364165ded040f1ded6d0a4a5388
de572fe13fe56eb00f81a493cedc95518d8f698c
refs/heads/master
2021-01-10T11:06:08.795365
2016-04-27T07:25:56
2016-04-27T07:25:56
51,194,976
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.6244784593582153, "alphanum_fraction": 0.6411682963371277, "avg_line_length": 27.799999237060547, "blob_id": "f9e53f1e882dcc87dd14ec41ae2d488f65047cfc", "content_id": "00c0ee31a4445bd8ca81990eeafe5fba14c6bf28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 719, "license_type": "no_license", "max_line_length": 85, "num_lines": 25, "path": "/Code/Web/welcome_php.php", "repo_name": "irpepper/Smart-Mirror", "src_encoding": "UTF-8", "text": "<html>\n<head>\n<title>Stuff</title>\n<link href=\"style_backend.css\" rel=\"stylesheet\" type=\"text/css\">\n</head>\n<body>\n<?php\n\necho \"<p style='text-size:80px;'>Your IP is </p>\";\n\n//$localIP = getHostByName(php_uname('n'));\n//echo $localIP;\n\n//might need to try something like this on the pi to get the correct IP:\n$command=\"/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'\";\n$localIP = exec ($command);\necho \"<p style='text-size:80px;'>\".$localIP.\"</p>\";\n\n?><br><br>\n<div id=\"welcome2\" class=\"welcome2\">\n<h1>iOS: <img src=\"qrcode_ios.png\"><br><br><br>\nAndroid: <img src=\"qrcode_android.png\"></h1></div>\n<div class=\"continue\" id=\"continue\"><a href=\"welcome2.html\">continue ></a></div>\n</body>\n</html>" }, { "alpha_fraction": 0.7490909099578857, "alphanum_fraction": 0.7490909099578857, "avg_line_length": 33.5, "blob_id": "e015e9da9d7c3251c87d0348e26039fd31df70b7", "content_id": "83d14e924db2202cdf1f6c66c5285a748d973834", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 275, "license_type": "no_license", "max_line_length": 115, "num_lines": 8, "path": "/Code/Web/README.md", "repo_name": "irpepper/Smart-Mirror", "src_encoding": "UTF-8", "text": "# Smart-Mirror Web \"OS\"\n\nInstructions:\n- Throw on a webserver (XAMPP or something similar, all paths are relative, so it should work just about anywhere).\n- Open index.html\n- Ta-da, it will determine if it has been run before and take you through set up if it hasn't.\n\nEnjoy." }, { "alpha_fraction": 0.610223650932312, "alphanum_fraction": 0.6453673839569092, "avg_line_length": 17.41176414489746, "blob_id": "c43da9d311aa84abb5f6fc28e68b244460a1ff08", "content_id": "55791b948f1fe8868d3bced6a887a6441633b4d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "no_license", "max_line_length": 33, "num_lines": 17, "path": "/Code/OS/home/pi/sensor.py", "repo_name": "irpepper/Smart-Mirror", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nfrom pymouse import pymouse\nimport time\n\npirPin = 13\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(pirPin, GPIO.IN)\nm = PyMouse()\nres = m.screen_size()\n\n\nwhile True:\n value = GPIO.input(pirPin)\n if value = True:\n m.move(res[0]-100,res[1])\n m.move(res[0],res[1])\n time.sleep(10)\n" }, { "alpha_fraction": 0.7743242979049683, "alphanum_fraction": 0.7756756544113159, "avg_line_length": 24.517240524291992, "blob_id": "889877701a1069476e8d5f4fad41499cc55ad8c4", "content_id": "039d7ea4b0ec51610cf5c9a48410ca3e337408c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 740, "license_type": "no_license", "max_line_length": 137, "num_lines": 29, "path": "/README.md", "repo_name": "irpepper/Smart-Mirror", "src_encoding": "UTF-8", "text": "# Smart-Mirror\nMonitor behind a one way mirror with a GUI run on a Raspberry Pi\n\n\nRequirements:\n- Weather Display with image/animation\n- Digital/Analog Clock\n- Greeting messages based on time with user's name\n- RSS Feed chosen by user\n- Have Pandora music capabilities\n- A motion sensor for screen on/off\n- Light sensor with and LED for temporary night light\n- Picture display for comparison (Hairstyle, makeup, etc)\n- A power button\n- Air Play Mouse support for iPhone and android so a user could configure the mirror (Login to Pandora, select station, move UI elements)\n- Startup animation\n- Pause and play button for music\n\nNon-Functional Requirements:\n-Who\n-how\n-when\n-why\n-where\n-performance\n\nContraints:\n- 3 Group Members\n- due dates\n" }, { "alpha_fraction": 0.5843405723571777, "alphanum_fraction": 0.6188557744026184, "avg_line_length": 34.46190643310547, "blob_id": "d28e809769626cf3c4ffb46a3a92f82addacfb7c", "content_id": "a66265655c6a800f9f9488d1b3883808e6315704", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7446, "license_type": "no_license", "max_line_length": 167, "num_lines": 210, "path": "/Code/Web/weather.js", "repo_name": "irpepper/Smart-Mirror", "src_encoding": "UTF-8", "text": "// JavaScript Document\nvar loc = 'NULL';\nvar defaultMode = false;\n\n$(document).ready(function() {\n\t\n\tgetInfo();\n\tgetWeather();\n\t\n});\n\nfunction getCookie(name) {\n\tvar cname = name + \"=\";\n\tvar ca = document.cookie.split(';');\n\t\n\tfor (var i = 0; i < ca.length; i++) {\n\t\tvar c = ca[i];\n\t\twhile (c.charAt(0)==' ') c = c.substring(1);\n\t\tif (c.indexOf(cname) == 0) return c.substring(cname.length, c.length);\n\t}\n\t\n\treturn \"\";\n}\n\nfunction getInfo() {\n\tconsole.log(\"Trying to get info\");\n\tloc = getCookie(\"location\");\n\tconsole.log(loc);\n\t\n\tif (loc == \"USER\")\n\t{\n\t\tloc = \"Denton, Texas\";\n\t\tdefaultMode = true;\n\t}\n}\n\nfunction getWeather()\n{\n\tsetInterval(getWeather, 300000);\n\n$.simpleWeather({\n\t\tlocation:loc,\n\t\tunit: 'f',\n\t\tsuccess:function(weather){\n\t\t\t\"use strict\";\n\t\t\tvar currentTemp = weather.temp + '&deg;' + weather.units.temp;\n\t\t\tvar code = weather.code;\n\t\t\tconsole.log(\"Weather code: \" + code);\n\t\t\t$(\"#weatherCurrentTemp\").html(currentTemp);\n\t\t\t\n\t\t\tvar weather0 = '<font color=\"#FFAAAA\" size=\"5\">' + weather.forecast[0].high + '</font><br><font color=\"#AAAAFF\" size=\"5\">' + weather.forecast[0].low +'</font>';\n\t\t\tvar weather1 = '<font color=\"#FFAAAA\"><br><br>' + weather.forecast[1].high + '</font><br><font color=\"#AAAAFF\">' + weather.forecast[1].low +'</font>';\n\t\t\tvar weather2 = '<font color=\"#FFAAAA\"><br><br>' + weather.forecast[2].high + '</font><br><font color=\"#AAAAFF\">' + weather.forecast[2].low +'</font>';\n\t\t\tvar weather3 = '<font color=\"#FFAAAA\"><br><br>' + weather.forecast[3].high + '</font><br><font color=\"#AAAAFF\">' + weather.forecast[3].low +'</font>';\n\t\t\tvar weather4 = '<font color=\"#FFAAAA\"><br><br>' + weather.forecast[4].high + '</font><br><font color=\"#AAAAFF\">' + weather.forecast[4].low +'</font>';\n\t\t\t\n\t\t\t$(\"#firstImage\").html(weather0);\n\t\t\t$(\"#secondImage\").html(weather1);\n\t\t\t$(\"#thirdImage\").html(weather2);\n\t\t\t$(\"#fourthImage\").html(weather3);\n\t\t\t$(\"#fifthImage\").html(weather4);\n\t\t\t\n\t\t\tvar weatherImage0 = \"url('\" + weather.image + \"')\";\n\t\t\tvar weatherImage1 = \"url('\" + weather.forecast[1].image + \"')\";\n\t\t\tvar weatherImage2 = \"url('\" + weather.forecast[2].image + \"')\";\n\t\t\tvar weatherImage3 = \"url('\" + weather.forecast[3].image + \"')\";\n\t\t\tvar weatherImage4 = \"url('\" + weather.forecast[4].image + \"')\";\n\t\t\t\n\t\t\tdocument.getElementById(\"firstImage\").style.backgroundImage = weatherImage0;\n\t\t\tdocument.getElementById(\"secondImage\").style.backgroundImage = weatherImage1;\n\t\t\tdocument.getElementById(\"thirdImage\").style.backgroundImage = weatherImage2;\n\t\t\tdocument.getElementById(\"fourthImage\").style.backgroundImage = weatherImage3;\n\t\t\tdocument.getElementById(\"fifthImage\").style.backgroundImage = weatherImage4;\n\t\t\t$(\"#weatherLocation\").html(loc);\n\t\t\t\n\t\t\tif (code == 0 || code == 1 || code == 2 || code == 3 || code == 4 || code == 17 || code == 25 || code == 37 || code == 38 || code == 39 || code == 45 || code == 47)\n\t\t\t{\n\t\t\t\t//17 35 37 38 39 45 47\n\t\t\t\t// thunderstorm video\n\t\t\t\tconsole.log(\"Weather: Thunderstorm\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/thunderstorm_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 5 || code == 6 || code == 7 || code == 8 || code == 10 || code == 18)\n\t\t\t{\n\t\t\t\t//18\n\t\t\t\t// sleet video\n\t\t\t\tconsole.log(\"Weather: Sleet\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/sleet_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 9 || code == 11 || code == 12 || code == 40)\n\t\t\t{\n\t\t\t\t//40\n\t\t\t\t// rain video\n\t\t\t\tconsole.log(\"Weather: Rain\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/rain_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 13 || code == 14 || code == 15 || code == 16 || code == 41 || code == 42 || code == 43 || code == 46)\n\t\t\t{\n\t\t\t\t//13 14 15 16 41(heavy) 42 43(heavy) 46\n\t\t\t\t// snow video\n\t\t\t\tconsole.log(\"Weather: Snow\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/snow_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 30 || code == 44)\n\t\t\t{\n\t\t\t\t// partly cloudy\n\t\t\t\t//30(day) 29(night) 44\n\t\t\t\tconsole.log(\"Weather: Partly Cloudy\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/partlycloudy_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 29)\n\t\t\t{\n\t\t\t\t// partly cloudy night\n\t\t\t\t//29\n\t\t\t\tconsole.log(\"Weather: Partly Cloudy - Night\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/partlycloudy_night_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 28)\n\t\t\t{\n\t\t\t\t// mostly cloudy\n\t\t\t\t//28 (day) 27(night)\n\t\t\t\tconsole.log(\"Weather: Mostly Cloudy\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/mostlycloudy_vid.png\">';\n\t\t\t\t\n\t\t\t}\n\t\t\telse if (code == 27)\n\t\t\t{\n\t\t\t\t// mostly cloudy night\n\t\t\t\tconsole.log(\"Weather: Mostly Cloudy - Night\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/mostlycloudy_night_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 19 || code == 21 || code == 22)\n\t\t\t{\n\t\t\t\t// Dust, haze, smoke\n\t\t\t\t//19 21 22\n\t\t\t\tconsole.log(\"Weather: Visual Obstructions\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/haze_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 23 || code == 24)\n\t\t\t{\n\t\t\t\t// Wind\n\t\t\t\t//23 24\n\t\t\t\tconsole.log(\"Weather: Wind\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/windy_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 31 || code == 33)\n\t\t\t{\n\t\t\t\t// Clear Night\n\t\t\t\t//31 33\n\t\t\t\tconsole.log(\"Weather: Clear Night\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/moon_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 32 || code == 34)\n\t\t\t{\n\t\t\t\t// Clear Day\n\t\t\t\t//32 34 36(hot)\n\t\t\t\tconsole.log(\"Weather: Clear Day\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/sun_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 20 || code == 26)\n\t\t\t{\n\t\t\t\t// Cloudy / foggy\n\t\t\t\t//20 26\n\t\t\t\tconsole.log(\"Weather: Cloudy / Foggy\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/cloudy_vid.png\">';\n\t\t\t}\n\t\t\telse if (code = 36)\n\t\t\t{\n\t\t\t\t// Hot\n\t\t\t\t// 36\n\t\t\t\tconsole.log(\"Weather: Hot\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/hot_vid.png\">';\n\t\t\t}\n\t\t\telse if (code == 25)\n\t\t\t{\n\t\t\t\t// Cold\n\t\t\t\t//25\n\t\t\t\tconsole.log(\"Weather: Cold\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/cold_vid.png\">';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Code not found, basic video.\n\t\t\t\tconsole.log(\"Weather: Code not found - switching to basic video\");\n\t\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/base_vid.png\">';\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif (defaultMode == false)\n\t\t\t{\n\t\t\t\tdocument.getElementById('error').innerHTML = '';\n\t\t\t\tconsole.log('Weather: Updated!');\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdocument.getElementById('error').innerHTML = 'WEATHER ERROR: No Location Data Found, Defaulting To Denton, Texas. Please check configuration.';\n\t\t\t\tconsole.log('Weather: Updated, but in default mode');\n\t\t\t}\n\t\t\t\n\t\t},\n\t\terror:function(error){\n\t\t\t\"use strict\";\n\t\t\tconsole.log(\"Weather: Bad things happened...\");\n\t\t\tconsole.log(\"Weather: Displaying basic video...\");\n\t\t\tconsole.log(\"Weather: \" + error);\n\t\t\tdocument.getElementById('fullscreen_bg').innerHTML = '<img src=\"weather_images/900p/base_vid.png\">';\n\t\t\tdocument.getElementById('error').innerHTML = 'WEATHER ERROR: There was a problem retrieving the latest weather information.';\n\t\t}\t\t\n\t});\n}" }, { "alpha_fraction": 0.5839694738388062, "alphanum_fraction": 0.5977098941802979, "avg_line_length": 19.793651580810547, "blob_id": "e5ac182bbb936ee2d60ab3bf48f32b0416336dd2", "content_id": "c740de4a12fa334909813b3b3447b598c1ebe8e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1310, "license_type": "no_license", "max_line_length": 93, "num_lines": 63, "path": "/Code/Web/greeting.js", "repo_name": "irpepper/Smart-Mirror", "src_encoding": "UTF-8", "text": "var user = \"USER\";\n\nfunction getCookie(name) {\n\tvar cname = name + \"=\";\n\tvar ca = document.cookie.split(';');\n\t\n\tfor (var i = 0; i < ca.length; i++) {\n\t\tvar c = ca[i];\n\t\twhile (c.charAt(0)==' ') c = c.substring(1);\n\t\tif (c.indexOf(cname) == 0) return c.substring(cname.length, c.length);\n\t}\n\t\n\treturn \"USER\";\n}\n\nfunction greetings()\n{\n\t\"use strict\";\n\tvar today = new Date();\n\tvar h = today.getHours();\n\t\n\tuser = getCookie(\"username\");\n\t\n\tif (user == \"debug\")\n\t{\n\t\tdocument.getElementById('greeting').innerHTML = \"NOW ENTERING DEBUG MODE\";\n\t\tsetTimeout(function(){\n\t\twindow.location = \"debug.html\";\n\t\t},1000);\n\t}\n\t\n\tif (h > 11)\n\t{\n\t\tif ( h > 17)\n\t\t{\n\t\t\tdocument.getElementById('greeting').innerHTML = \"Good Evening, \" + user;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdocument.getElementById('greeting').innerHTML = \"Good Afternoon, \" + user;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif ( h > 7)\n\t\t{\n\t\t\tdocument.getElementById('greeting').innerHTML = \"Good Morning, \" + user;\n\t\t}\n\t\telse if (h > 4)\n\t\t{\n\t\t\tdocument.getElementById('greeting').innerHTML = \"Early start, \" + user + \"?\";\n\t\t}\n\t\telse if (h < 3)\n\t\t{\n\t\t\tdocument.getElementById('greeting').innerHTML = \"Burning the midnight oil, \" + user + \"?\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdocument.getElementById('greeting').innerHTML = \"Why are you still awake, \" + user + \"?\";\t\n\t\t}\n\t}\n\tvar t = setTimeout(greetings, 500);\n}\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 20.66666603088379, "blob_id": "88c9d3af6523e2c6b4874b088f4827f881bc1a99", "content_id": "4cc00d9e8007a3242b1caf77911ff5af192fc09c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 65, "license_type": "no_license", "max_line_length": 51, "num_lines": 3, "path": "/Code/OS/home/pi/.xsession", "repo_name": "irpepper/Smart-Mirror", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nkweb -KJEHCUA+-zbhrqfpoklgtjnedwxy http://localhost\n" }, { "alpha_fraction": 0.7220588326454163, "alphanum_fraction": 0.7343137264251709, "avg_line_length": 33.016666412353516, "blob_id": "a0966e4516692ea18bb246e283e9e5562b31564f", "content_id": "e15236d4baf2e3aecb42c6ed55c365bf6c9c0fe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2040, "license_type": "no_license", "max_line_length": 90, "num_lines": 60, "path": "/Code/README.md", "repo_name": "irpepper/Smart-Mirror", "src_encoding": "UTF-8", "text": "# Setup information (so far)\n\n* Download Raspbian Image\n* Flash SD Card with Disk Imager\n\t- Buy new SD Card\n* Flash NEW SD Card with Disk Imager\n\t- Needs to be > 4gb\n* Added information to /boot/config.txt\n\t- See config.txt in repo\n* Upon boot, allocate more memory to GPU and expand filesystem\n\t- sudo raspi-config\n\t- > Advanced options\n\t- > Memory Split\n\t- Change from 0 to 128\n\t- expand filesystem\n* Restart\n* Make sure RPi is connected to internet\n* Install LAMP\n\t- sudo su\n\t- apt-get update && apt-get upgrade\n\t- apt-get install apache2 php5 mysql-client mysql-server vsftpd\n\t\t- set root password for mysql\n\t- cd /var/www\n\t- nano index.html\n* Power down RPi\n\t- Put SD card back in computer\n\t- Edit last line of config.txt to change orientation\n* Start completely over because you failed to eject SD card properly and corrupted the OS\n* Install Chromium\n\t- Chromium not available - switch to iceweasel\n* FTP Everything over to /var/www/html\n* Kweb???\n\t- Seems to be working\n\t- kweb -KJEHCUA+-zbhrqfpoklgtjneduwxy http://localhost\n\t- Can put that in a script\n\t- Need to fix CSS for frontend\n* Create new file in /home/pi\n\t- .xsession\n\t- #!/bin/bash\n\t- kweb -KJEHCUA+-zbhrqfpoklgtjneduwxy http://localhost\n\t- This disables just about everything that isn't kweb. Use ctrl-alt-F1 to get to terminal\n\t- Use ctrl-alt-f7 to get back to X\n* Install fbi\n\t- sudo apt-get install fbi\n\t- chmod 0777 /etc\n\t- chmod 0777 /etc/init.d\n* FTP asplashscreen to /etc/init.d\n\t- sudo chmod a+x /etc/init.d/asplashscreen\n\t- sudo insserv /etc/init.d/asplashscreen\n\t- sudo reboot\n\t- NOTE: This file should only be edited in NANO because formatting issues kill it.\n* Phone keyboard / mouse support\n\t- Download RemotePi from Apple or Google app store\n\t- sudo wget http://remotepi.io/drivers/remotepi_1.0.15_armhf.deb\n\t- sudo dpkg -i remotepi_1.0.15_armhf.deb\n\t- sudo /etc/init.d/remotepi start\n* Switching to Midori (again)\n\t- Install matchbox\n\t- Change .xsession to matchbox-window-manager & midori -e Fullscreen -a http://localhost\n\t- This works in profile! Yay!" } ]
8
waterAddicted/radical-din-x-in-pyton
https://github.com/waterAddicted/radical-din-x-in-pyton
4077e7479f256288e6f5dc9512301b519a219a17
ac5a4af68e292dddf0d29ae470800695c052e027
e6bb35aa8cb58280247855a72cc507ddc303c3a3
refs/heads/main
2023-07-18T02:28:21.708949
2021-08-29T01:23:42
2021-08-29T01:23:42
400,924,557
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3887043297290802, "alphanum_fraction": 0.41528239846229553, "avg_line_length": 18.066667556762695, "blob_id": "15452aa0bba18e1703a73adb94d8a39763350729", "content_id": "af320e9920aac413062051600de6d142f0644d7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 301, "license_type": "no_license", "max_line_length": 35, "num_lines": 15, "path": "/main.py", "repo_name": "waterAddicted/radical-din-x-in-pyton", "src_encoding": "UTF-8", "text": "\r\ndef radical(x):\r\n st = float(0)\r\n dr = float(x)\r\n mij = (st + dr) / 2\r\n while abs(mij * mij - x) > eps:\r\n if mij * mij < x:\r\n st = mij\r\n else:\r\n dr = mij\r\n mij = (st + dr)/2\r\n return mij\r\n\r\nx = float(input())\r\neps = 0.0001\r\nprint(radical(x))" } ]
1
orpheus/multi-tab-search
https://github.com/orpheus/multi-tab-search
8d90c5c5858adde2c6a4da333a214dc1f27cf89d
17a7aa4f6290ca350ad98d9d30396b4af449275b
f2e6af5fbd5ca85a6f4381fedff96eefec07c211
refs/heads/master
2021-06-25T21:17:18.977663
2017-09-12T23:42:32
2017-09-12T23:42:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6261799931526184, "alphanum_fraction": 0.6261799931526184, "avg_line_length": 30.156862258911133, "blob_id": "5dabb06539ee023165f151545a1d0b446e220ad1", "content_id": "6d8916d11ea5609bea1f3a39b6a0b8ebd5fb5963", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1589, "license_type": "no_license", "max_line_length": 112, "num_lines": 51, "path": "/main.py", "repo_name": "orpheus/multi-tab-search", "src_encoding": "UTF-8", "text": "from multiprocessing import Pool\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom functools import partial\n\ndef main(hosts, inp):\n\n driver = webdriver.Chrome(executable_path='./chromedriver')\n driver.get(hosts)\n if 'ebay' in driver.current_url:\n print 'opened ebay'\n search_box = driver.find_element_by_id('gh-ac')\n search_box.clear()\n search_box.send_keys(inp)\n search_box.send_keys(Keys.RETURN)\n\n elif 'google' in driver.current_url:\n print 'opened google'\n search_box = driver.find_element_by_id('gbqfq')\n search_box.clear()\n search_box.send_keys(inp)\n search_box.send_keys(Keys.RETURN)\n\n elif 'etsy' in driver.current_url:\n print 'opened etsy'\n search_box = driver.find_element_by_id('search-query')\n search_box.clear()\n search_box.send_keys(inp)\n search_box.send_keys(Keys.RETURN)\n\n elif 'amazon' in driver.current_url:\n print 'opened amazon'\n search_box = driver.find_element_by_id('twotabsearchtextbox')\n search_box.clear()\n search_box.send_keys(inp)\n search_box.send_keys(Keys.RETURN)\n\n else:\n print \"--NONE--\"\n\n # driver.close()\n\nif __name__ == '__main__':\n hosts = [\"http://ebay.com\", \"https://www.google.com/shopping?hl=en\", \"http://etsy.com\", \"http://amazon.com\"]\n num_hosts = len(hosts)\n inp = raw_input(\"What do you want to search?: \")\n p = Pool(num_hosts)\n partial_main = partial(main, inp=inp)\n p.map(partial_main, hosts)\n p.close()\n p.join()\n" }, { "alpha_fraction": 0.8032786846160889, "alphanum_fraction": 0.8032786846160889, "avg_line_length": 44.75, "blob_id": "85fff953dd32e54b3750cf576bd4078a0fdcfdf2", "content_id": "93da37eed39ec5fad5712fedf2489416610a9bf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 183, "license_type": "no_license", "max_line_length": 81, "num_lines": 4, "path": "/README.md", "repo_name": "orpheus/multi-tab-search", "src_encoding": "UTF-8", "text": "# multi-tab-search\nOpens multiple web tabs and searches for a common query across various websites.\n\n>Currently searches amazon, google shopping, ebay, and etsy for the entered query\n" } ]
2
guoming-long/fast-bert
https://github.com/guoming-long/fast-bert
da87a72392652d6db24e4c3a1568008953b0f753
20d0eb084a687e99afc0617dc7026bd1e8101720
1f2b58ce3f362d1ed1cdb7edbdef7c69f836f4d2
refs/heads/master
2021-02-09T03:26:24.546984
2020-03-05T10:54:37
2020-03-05T10:54:37
244,233,689
0
0
Apache-2.0
2020-03-01T22:27:38
2020-02-29T11:12:25
2020-01-29T15:56:26
null
[ { "alpha_fraction": 0.8316831588745117, "alphanum_fraction": 0.8613861203193665, "avg_line_length": 10.333333015441895, "blob_id": "5aadc40ea751bbb5348356c043f1f01d9b01b8ca", "content_id": "6e34937502ceefd71b5caf9eada0b99ec0d7f2cc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 101, "license_type": "permissive", "max_line_length": 19, "num_lines": 9, "path": "/requirements.txt", "repo_name": "guoming-long/fast-bert", "src_encoding": "UTF-8", "text": "pytorch-lamb\ntensorboardX\nfastprogress\nsklearn\nspacy\ntransformers>=2.3.0\npandas\npython-box\ntokenizers" }, { "alpha_fraction": 0.5520392656326294, "alphanum_fraction": 0.5630882382392883, "avg_line_length": 28.68016242980957, "blob_id": "50927e21047a49e1c903ecd534fd454cef4106df", "content_id": "5281bfe5a90e26eccb61e6c0fbf631c0c2e6fad7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7331, "license_type": "permissive", "max_line_length": 128, "num_lines": 247, "path": "/fast_bert/metrics.py", "repo_name": "guoming-long/fast-bert", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom torch import Tensor\nfrom sklearn.metrics import roc_curve, auc, hamming_loss, accuracy_score, recall_score, precision_score, f1_score, roc_auc_score\nimport pdb\n\nCLASSIFICATION_THRESHOLD: float = 0.5 # Best keep it in [0.0, 1.0] range\n \nlabels_list = ['P1','P2','P3','P4','P5']\n\n\n# def accuracy(out, labels):\n# outputs = np.argmax(out, axis=1)\n# return np.sum(outputs == labels)\n\n\ndef recall_macro(y_pred: Tensor, y_true: Tensor):\n y_pred = y_pred.cpu()\n y_pred = np.argmax(y_pred, axis=1)\n print(y_pred)\n y_true = y_true.cpu()\n y_true = np.argmax(y_true, axis=1)\n print(y_true)\n return recall_score(y_pred, y_true, average='macro')\n\ndef recall_by_class(y_pred: Tensor, y_true: Tensor, labels: list = labels_list):\n y_pred = y_pred.cpu()\n y_pred = np.argmax(y_pred, axis=1)\n print(y_pred)\n y_true = y_true.cpu()\n y_true = np.argmax(y_true, axis=1)\n d = []\n for i in range(len(labels)): \n out_pred = []\n out_true = []\n num1 = 0\n num2 = 0\n for j in y_pred:\n if j == i:\n out_pred.append(1)\n num1 += 1\n else:\n out_pred.append(0)\n for j in y_true:\n if j == i:\n out_true.append(1)\n num2 += 1\n else:\n out_true.append(0)\n print(num1,num2)\n d.append(recall_score(out_pred, out_true, average='binary'))\n return d\n\ndef recall_micro(y_pred: Tensor, y_true: Tensor):\n y_pred = y_pred.sigmoid()\n y_pred = (y_pred > 0.5).cpu()\n y_true = y_true.cpu()\n return recall_score(y_pred, y_true, average='micro')\n\ndef precision_macro(y_pred: Tensor, y_true: Tensor):\n y_pred = y_pred.sigmoid()\n y_pred = (y_pred > 0.5).cpu()\n y_true = y_true.cpu()\n return precision_score(y_pred, y_true, average='macro')\n\ndef precision_micro(y_pred: Tensor, y_true: Tensor):\n y_pred = y_pred.sigmoid()\n y_pred = (y_pred > 0.5).cpu()\n y_true = y_true.cpu()\n return precision_score(y_pred, y_true, average='micro')\n\ndef precision_by_class(y_pred: Tensor, y_true: Tensor, labels: list = labels_list):\n y_pred = y_pred.cpu()\n y_pred = np.argmax(y_pred, axis=1)\n print(y_pred)\n y_true = y_true.cpu()\n y_true = np.argmax(y_true, axis=1)\n d = []\n for i in range(len(labels)): \n out_pred = []\n out_true = []\n for j in y_pred:\n if j == i:\n out_pred.append(1)\n else:\n out_pred.append(0)\n for j in y_true:\n if j == i:\n out_true.append(1)\n else:\n out_true.append(0)\n d.append(precision_score(out_pred, out_true, average='binary'))\n return d\n\ndef f1_macro(y_pred: Tensor, y_true: Tensor):\n y_pred = y_pred.sigmoid()\n y_pred = (y_pred > 0.5).cpu()\n y_true = y_true.cpu()\n return f1_score(y_pred, y_true, average='macro')\n\ndef f1_micro(y_pred: Tensor, y_true: Tensor):\n y_pred = y_pred.sigmoid()\n y_pred = (y_pred > 0.5).cpu()\n y_true = y_true.cpu()\n return f1_score(y_pred, y_true, average='micro')\n\ndef f1_by_class(y_pred: Tensor, y_true: Tensor, labels: list = labels_list):\n y_pred = y_pred.cpu()\n y_pred = np.argmax(y_pred, axis=1)\n print(y_pred)\n y_true = y_true.cpu()\n y_true = np.argmax(y_true, axis=1)\n d = []\n for i in range(len(labels)): \n out_pred = []\n out_true = []\n for j in y_pred:\n if j == i:\n out_pred.append(1)\n else:\n out_pred.append(0)\n for j in y_true:\n if j == i:\n out_true.append(1)\n else:\n out_true.append(0)\n d.append(f1_score(out_pred, out_true, average='binary'))\n return d\n\n\ndef accuracy(y_pred: Tensor, y_true: Tensor):\n y_pred = y_pred.cpu()\n outputs = np.argmax(y_pred, axis=1)\n return np.mean(outputs.numpy() == y_true.detach().cpu().numpy())\n\n\ndef accuracy_multilabel(y_pred: Tensor, y_true: Tensor, sigmoid: bool = True):\n if sigmoid:\n y_pred = y_pred.sigmoid()\n y_pred = y_pred.cpu()\n y_true = y_true.cpu()\n outputs = np.argmax(y_pred, axis=1)\n real_vals = np.argmax(y_true, axis=1)\n return np.mean(outputs.numpy() == real_vals.numpy())\n\n\ndef accuracy_thresh(\n y_pred: Tensor,\n y_true: Tensor,\n thresh: float = CLASSIFICATION_THRESHOLD,\n sigmoid: bool = True,\n):\n \"Compute accuracy when `y_pred` and `y_true` are the same size.\"\n if sigmoid:\n y_pred = y_pred.sigmoid()\n return ((y_pred > thresh) == y_true.bool()).float().mean().item()\n\n\n# return np.mean(((y_pred>thresh)==y_true.byte()).float().cpu().numpy(), axis=1).sum()\n\n\ndef fbeta(\n y_pred: Tensor,\n y_true: Tensor,\n thresh: float = 0.3,\n beta: float = 2,\n eps: float = 1e-9,\n sigmoid: bool = True,\n):\n \"Computes the f_beta between `preds` and `targets`\"\n beta2 = beta ** 2\n if sigmoid:\n y_pred = y_pred.sigmoid()\n y_pred = (y_pred > thresh).float()\n y_true = y_true.float()\n TP = (y_pred * y_true).sum(dim=1)\n prec = TP / (y_pred.sum(dim=1) + eps)\n rec = TP / (y_true.sum(dim=1) + eps)\n res = (prec * rec) / (prec * beta2 + rec + eps) * (1 + beta2)\n return res.mean().item()\n\n\ndef roc_auc(y_pred: Tensor, y_true: Tensor):\n # ROC-AUC calcualation\n # Compute ROC curve and ROC area for each class\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n\n y_true = y_true.detach().cpu().numpy()\n y_pred = y_pred.detach().cpu().numpy()\n\n # Compute micro-average ROC curve and ROC area\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_true.ravel(), y_pred.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n return roc_auc[\"micro\"]\n\n\ndef Hamming_loss(\n y_pred: Tensor,\n y_true: Tensor,\n sigmoid: bool = True,\n thresh: float = CLASSIFICATION_THRESHOLD,\n sample_weight=None,\n):\n if sigmoid:\n y_pred = y_pred.sigmoid()\n y_pred = (y_pred > thresh).cpu()\n y_true = y_true.cpu()\n return hamming_loss(y_true, y_pred, sample_weight=sample_weight)\n\n\ndef Exact_Match_Ratio(\n y_pred: Tensor,\n y_true: Tensor,\n sigmoid: bool = True,\n thresh: float = CLASSIFICATION_THRESHOLD,\n normalize: bool = True,\n sample_weight=None,\n):\n if sigmoid:\n y_pred = y_pred.sigmoid()\n y_pred = (y_pred > thresh).float()\n return accuracy_score(\n y_true, y_pred, normalize=normalize, sample_weight=sample_weight\n )\n\n\ndef F1(y_pred: Tensor, y_true: Tensor, threshold: float = CLASSIFICATION_THRESHOLD):\n return fbeta(y_pred, y_true, thresh=threshold, beta=1)\n\ndef roc_auc_score_by_class(y_pred:Tensor, y_true:Tensor, labels:list = labels_list):\n y_pred = y_pred.cpu()\n y_pred = np.argmax(y_pred, axis = 1).numpy()\n y_true = y_true.cpu()\n y_true = y_true.detach().cpu().numpy()\n roc_auc_score_d = {}\n for i in range(len(labels)):\n lb = LabelBinarizer()\n y_true_i = y_true.copy()\n y_true_i[y_true != i] = len(labels) + 1\n y_true_i = lb.fit_transform(y_true_i)\n y_pred_i = y_pred.copy()\n y_pred_i[y_pred != i] = len(labels) + 1\n y_pred_i = lb.transform(y_pred_i)\n roc_auc_score_d[labels[i]] = roc_auc_score(y_true_i, y_pred_i, average = 'micro')\n return roc_auc_score_d\n" } ]
2
nhancv/nc-mysql-db-install-gen
https://github.com/nhancv/nc-mysql-db-install-gen
fbcd5fbbb5ad44f4481889c67a91c1cd948084ad
76019711937b0b4334b95941f27079e91caf87db
c99b13599c2ebe40c525165a16d3a50497ad3c83
refs/heads/master
2021-01-19T21:50:55.854545
2017-05-03T11:16:24
2017-05-03T11:16:24
88,713,684
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6301843523979187, "alphanum_fraction": 0.6370967626571655, "avg_line_length": 28.79310417175293, "blob_id": "fa665e35fcc18f75958447cbcc6f8c5fbf9bf368", "content_id": "dae336f0177179e68802b45d74498648add9e972", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "no_license", "max_line_length": 64, "num_lines": 29, "path": "/install.py", "repo_name": "nhancv/nc-mysql-db-install-gen", "src_encoding": "UTF-8", "text": "# 2017 Apr 17\n# --Nhan Cao--\n# \nimport os\nimport json\nimport fileinput\nfrom pprint import pprint\n\nwith open('install.conf.json') as data_file: \n\tdata = json.load(data_file)\n\n##########################################################\nfor line in fileinput.input(\"./install.sql\", inplace=True): \n\tprint line.rstrip().replace('DB_NAME', data['DB_NAME'])\n\nfor line in fileinput.input(\"./install.sql\", inplace=True): \n\tprint line.rstrip().replace('DB_USER', data['DB_USER'])\n\nfor line in fileinput.input(\"./install.sql\", inplace=True): \n\tprint line.rstrip().replace('DB_PASSWORD', data['DB_PASSWORD'])\n\nfor line in fileinput.input(\"./install.sql\", inplace=True): \n\tprint line.rstrip().replace('DB_HOST', data['DB_HOST'])\n\nos.rename(\"DB_NAME.sql\", data['DB_NAME'] + \".sql\") \n\nprint(\"Finish Generate\")\nos.system(\"mysql -u root -p < install.sql\")\nprint(\"Finish Install\")\n\n\n\n\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 30, "blob_id": "2d347094c1d725e89a34a0a304873d1976e88852", "content_id": "6245e2cbac9822f8fb9d671520557b02e8a2dd8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 30, "license_type": "no_license", "max_line_length": 30, "num_lines": 1, "path": "/importdb.sh", "repo_name": "nhancv/nc-mysql-db-install-gen", "src_encoding": "UTF-8", "text": "mysql -u root -p < install.sql" }, { "alpha_fraction": 0.7441860437393188, "alphanum_fraction": 0.7574750781059265, "avg_line_length": 42.14285659790039, "blob_id": "6df6a8348ff1fa8590103f769f2624e88a55a893", "content_id": "291761aebaae6174fdbefdf369793d3dbf2eab25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 301, "license_type": "no_license", "max_line_length": 87, "num_lines": 7, "path": "/install.sql", "repo_name": "nhancv/nc-mysql-db-install-gen", "src_encoding": "UTF-8", "text": "CREATE USER IF NOT EXISTS 'DB_USER'@'DB_HOST' IDENTIFIED BY 'DB_PASSWORD';\nDROP DATABASE IF EXISTS DB_NAME;\nCREATE DATABASE IF NOT EXISTS DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;\nUSE DB_NAME;\nGRANT ALL PRIVILEGES ON DB_NAME.* TO 'DB_USER'@'DB_HOST';\nSOURCE ./DB_NAME.sql;\nSHOW TABLES;" } ]
3
UkaszSierak/nobel_prize_finder
https://github.com/UkaszSierak/nobel_prize_finder
ecb1b25dc9e3b37e482a6628bba9e9cb9a884243
dfd528397275299976255a96dafc289d851ff1a3
dc0782dde0edd82699cec9efa3b121c61f6e3c0d
refs/heads/master
2020-04-23T08:56:28.329115
2019-02-19T18:14:02
2019-02-19T18:14:02
171,053,280
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4673013389110565, "alphanum_fraction": 0.4710264801979065, "avg_line_length": 35.42424392700195, "blob_id": "99419d1038a451f1a453a1a4d3df1a4f185e9d10", "content_id": "2d3d3b7d4830f50d94c6a81ce32971e5824add45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2416, "license_type": "no_license", "max_line_length": 120, "num_lines": 66, "path": "/main.py", "repo_name": "UkaszSierak/nobel_prize_finder", "src_encoding": "UTF-8", "text": "\"\"\"\n Data structures of 2 jayson data sets:\n prizes:\n - year\n - category:\n - physics\n - economics\n - medicine\n - chemistry\n - literature\n - peace\n - overall motivation (optionally)\n - laureates [...] (the same as laureates data set but additional\n one attribute is |share|: which means how many\n people share the Nobel Prize in certain category)\n laureates:\n - id\n - first name\n - surname\n - born(date)\n - died(date)\n - bornCountry\n - bornCountryCode\n - diedCity\n - gender\n - prizes []\nNobel Prizes can be displayed by certain:\n - year/ years and certain category\n - laureate\n------------------------------------------------------------------------------------------------------------------------\n Note in Python we can pack and unpack argument parameters with * for tuple list, or ** for dictionary\n\"\"\"\nimport json\n\ndataset = {**json.load(open('prize.json', 'r')), **json.load(open('laureate.json', 'r'))}\n\ndef checkvalue(item: str, data: list):\n item = item.lower()\n if item not in data:\n new_item = input(\"There is no such name.\\n\"\n \"Please type it again: \")\n checkvalue(new_item, data)\n else:\n pass\n\ndef printCategories(data):\n categories = []\n\n for item in data:\n if item['category'] not in categories:\n categories.append(item['category'])\n return categories\n\ncategories = printCategories(dataset['prizes'])\n\nprint(\"Nobel Prize Finder finds for you information about nobel prizes :)\\n\\n\\n\"\n \"Type in correct order prize category and year that u interested in\\n\"\n \"Tip: press 'Enter' after each parameter you type\\n\\n\")\n\nprint(\"Chose category from the following:%s\"%'\\n\\t - '.join(categories))\n\ncategory = input(\"Enter category name: \")\n\ncheckvalue(category, categories)\n\nyear = input(\"Chose year from 1901 till 2018: \")\n\n\n\n\n\n\n\n\n\n\n\n\n" } ]
1
crysisfarcry222/reflection_experiments
https://github.com/crysisfarcry222/reflection_experiments
42225a2215849102ba81ce64fbca1e892dc1e915
263dca2f857068d1610ccc16c432d3dbfc1e920f
b07ee1755e7e3aa7af9ca15c1930e5619ce9a5a2
refs/heads/master
2021-01-01T15:49:04.600224
2017-05-18T20:11:02
2017-05-18T20:11:02
97,711,298
1
0
null
2017-07-19T12:00:31
2017-07-19T12:00:11
2017-05-18T20:10:39
null
[ { "alpha_fraction": 0.7140350937843323, "alphanum_fraction": 0.722806990146637, "avg_line_length": 27.5, "blob_id": "59321ee91fdcbfdaf8221c2f3e5ae509ceb7a5cd", "content_id": "505225a7d22c938e15b5f0acd243730592fa0401", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1140, "license_type": "permissive", "max_line_length": 113, "num_lines": 40, "path": "/benchmarks/generate_benchmark.py", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport argparse\nimport em\nimport os\nimport os.path\nimport random\nimport string\nimport sys\n\nparser = argparse.ArgumentParser(\"generate benchmarks for reflopt\")\n\nparser.add_argument('N', type=int, nargs=1, help='The number of arguments to generate')\nparser.add_argument('M', type=int, nargs=1, help='The maximum length of argument names.')\nparser.add_argument('--in_filename', dest='in_filename', type=str, nargs=1, help='Filename to save output to.')\nparser.add_argument('--out_filename', dest='out_filename', type=str, nargs=1, help='Filename to save output to.')\n\nargs = parser.parse_args(sys.argv[1:])\n\nN = args.N[0]\nM = args.M[0]\nin_filename = args.in_filename[0]\nout_filename = args.out_filename[0]\n\narguments = set()\n\nalpha = string.ascii_lowercase\nfor i in range(N):\n arguments.add(''.join([alpha[(i + j) % len(alpha)] for j in range(M)]))\n\nout_dir = os.path.dirname(out_filename)\nif not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\ninterpreter = em.Interpreter(output=open(out_filename, 'w+'))\n\ninterpreter.globals['arguments'] = arguments\n\ninterpreter.file(open(in_filename))\ninterpreter.shutdown()\n" }, { "alpha_fraction": 0.5570710897445679, "alphanum_fraction": 0.576453685760498, "avg_line_length": 23.017240524291992, "blob_id": "dfb5fc2b469c4f6077f60dbc3e7f044688c816b7", "content_id": "8f3c01a18fb88a85f67290130e4169cf546baa80", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1393, "license_type": "permissive", "max_line_length": 103, "num_lines": 58, "path": "/test/reflopt.cpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#include \"reflopt.hpp\"\n\n#include <cassert>\n\n#ifndef BOOST_HANA_CONFIG_ENABLE_STRING_UDL\nstatic_assert(false, \"reflopt example won't work without Hana string literals enabled\");\n#endif\n\nstruct ProgramOptions {\n std::string filename;\n int iterations;\n bool help;\n};\n\nint main() {\n {\n static const char* argv[] = {\"exename\", \"--filename\", \"test\", \"--iterations\", \"50\", \"--help\", \"1\"};\n int argc = 7;\n const auto args = reflopt::parse<ProgramOptions>(argc, argv);\n if (!args) {\n return 255;\n }\n\n assert(args->filename == \"test\");\n assert(args->iterations == 50);\n assert(args->help == true);\n }\n\n // Short flags\n {\n static const char* argv[] = {\"exename\", \"--filename\", \"test\", \"-i\", \"60\", \"-h\", \"1\"};\n int argc = 7;\n const auto args = reflopt::parse<ProgramOptions>(argc, argv);\n if (!args) {\n return 255;\n }\n\n assert(args->filename == \"test\");\n assert(args->iterations == 60);\n assert(args->help == true);\n }\n\n // Failures\n {\n static const char* argv[] = {\"exename\", \"--asdf\", \"test\", \"-i\", \"60\", \"-h\", \"1\"};\n int argc = 7;\n const auto args = reflopt::parse<ProgramOptions>(argc, argv);\n assert(!args);\n }\n {\n static const char* argv[] = {\"exename\", \"--filename\", \"-i\", \"60\", \"-h\", \"1\"};\n int argc = 7;\n const auto args = reflopt::parse<ProgramOptions>(argc, argv);\n assert(!args);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6133056282997131, "alphanum_fraction": 0.6237006187438965, "avg_line_length": 19.04166603088379, "blob_id": "c9d31266ecebb0c69d641157acdb9f7e890eb1d0", "content_id": "e17bfd12a9e049a984044597b1bfc3c0a8391959", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 481, "license_type": "permissive", "max_line_length": 57, "num_lines": 24, "path": "/src/reflopt.cpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "/* Demo: Specify a struct for command line arguments\n * */\n\n#include \"reflopt.hpp\"\n#include <iostream>\n\nstruct ProgramOptions {\n std::string filename;\n int iterations = 100;\n bool help = false;\n};\n\nint main(int argc, char** argv) {\n auto args = reflopt::parse<ProgramOptions>(argc, argv);\n if (!args) {\n std::cerr << \"Argument parsing failed.\" << std::endl;\n return -1;\n }\n\n std::cout << args->filename << \"\\n\";\n std::cout << args->iterations << \"\\n\";\n\n return 0;\n}\n" }, { "alpha_fraction": 0.752525269985199, "alphanum_fraction": 0.7676767706871033, "avg_line_length": 35, "blob_id": "c9ac32b18d2ed8f692ac8b548d0e38168bd4668a", "content_id": "f58a82adf677914db1e2bc2535c7ed02f068bf85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 396, "license_type": "permissive", "max_line_length": 106, "num_lines": 11, "path": "/benchmarks/CMakeLists.txt", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "if(DEFINED REFLEXPR_PATH)\n\ninclude(../cmake/refl_experiments_add_benchmark.cmake)\nfind_package(Boost REQUIRED COMPONENTS program_options)\n\nforeach(N RANGE 5 50 5)\n refl_experiments_add_benchmark(reflopt ${N} 7 ${CMAKE_BINARY_DIR}/generated/reflopt_benchmark \"refl\")\n refl_experiments_add_benchmark(boost_po ${N} 7 ${CMAKE_BINARY_DIR}/generated/boost_po_benchmark \"boost\")\nendforeach()\n\nendif()\n" }, { "alpha_fraction": 0.7527472376823425, "alphanum_fraction": 0.7596153616905212, "avg_line_length": 33.66666793823242, "blob_id": "c19c48d5e04a3482001502d7686d4d7de0eadcaf", "content_id": "71a75af3c2df67949ab4b5f8d4fe7f5c050ce479", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 730, "license_type": "permissive", "max_line_length": 235, "num_lines": 21, "path": "/README.md", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "# Experiments with reflection\n\n## reflexpr\nTo compile the example, compile the \"reflexpr\" fork of Clang by following the instructions on [Matúš's website](http://matus-chochlik.github.io/mirror/doc/html/implement/clang.html). Then pass `REFLEXPR_PATH` to CMake for this project.\n\n```\nmkdir build\ncd build\ncmake .. -DREFLEXPR_PATH=<path to the reflexpr fork>/reflection -DCMAKE_CXX_COMPILER=<reflexpr clang executable>\nmake\n```\n\n## cpp3k\nCompile Andrew Sutton's [`clang-reflect`](https://github.com/asutton/clang-reflect) fork and pass `CPP3K_PATH` to CMake for this project.\n\n```\nmkdir build\ncd build\ncmake .. -DCPP3K_PATH=<path to the cpp3k fork>/tools/libcpp3k/include -DCMAKE_CXX_COMPILER=<clang-reflect executable>\nmake\n```\n" }, { "alpha_fraction": 0.6762936115264893, "alphanum_fraction": 0.6799037456512451, "avg_line_length": 23.441177368164062, "blob_id": "91bbdb598bce8c2f42af8583ecb0ab235c3f5edb", "content_id": "8a49c86901f1752d6edf09b36b53d17605544336", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 831, "license_type": "permissive", "max_line_length": 85, "num_lines": 34, "path": "/include/reflection_experiments/cpp3k/adapt_hana.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <boost/hana/tuple.hpp>\n#include <cpp3k/meta>\n\nnamespace jk {\nnamespace refl_utilities {\nnamespace hana = boost::hana;\n\ntemplate<typename T, size_t ...I>\nconstexpr auto adapt_to_hana_helper(const T& t, std::index_sequence<I...>&&) {\n return hana::make_tuple(\n cpp3k::meta::v1::cget<I>(t)...\n );\n}\n\ntemplate<typename T>\nconstexpr auto adapt_to_hana(T&& t) {\n // return std::apply(hana::make_tuple, std::forward<T>(t));\n return adapt_to_hana_helper(t, std::make_index_sequence<T::size()>{});\n}\n\ntemplate<size_t ...I>\nconstexpr static auto make_index_sequence_tuple_helper(std::index_sequence<I...>&&) {\n return hana::make_tuple(hana::int_c<I>...);\n}\n\ntemplate<size_t N>\nconstexpr static auto make_index_sequence_tuple() {\n return make_index_sequence_tuple_helper(std::make_index_sequence<N>{});\n}\n\n}\n}\n" }, { "alpha_fraction": 0.6039671897888184, "alphanum_fraction": 0.6067031621932983, "avg_line_length": 24.64912223815918, "blob_id": "ad03a1e27b80b32ff3ce75bfb5bae79c91502a2a", "content_id": "6f6f7430d42208d1e9d8a265ed2497a8f0d77dfd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1462, "license_type": "permissive", "max_line_length": 75, "num_lines": 57, "path": "/include/reflection_experiments/comparisons.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"meta_utilities.hpp\"\n#include \"refl_utilities.hpp\"\n\n\nnamespace reflcompare {\n\nnamespace refl = jk::refl_utilities;\nnamespace metap = jk::metaprogramming;\n#if USING_REFLEXPR\nnamespace meta = std::meta;\n#elif USING_CPP3K\nnamespace meta = cpp3k::meta;\n#endif\n\ntemplate<typename T>\nbool equal(const T& a, const T& b) {\n if constexpr (metap::is_detected<metap::equality_comparable, T>{}) {\n return a == b;\n } else if constexpr (metap::is_detected<metap::iterable, T>{}) {\n if (a.size() != b.size()) {\n return false;\n }\n for (int i = 0; i < a.size(); ++i) {\n if (!equal(a[i], b[i])) {\n return false;\n }\n }\n return true;\n } else {\n#if USING_REFLEXPR\n using MetaT = reflexpr(T);\n static_assert(meta::Record<MetaT>,\n \"Type contained a member which has no comparison operator defined.\");\n bool result = true;\n meta::for_each<meta::get_data_members_m<MetaT>>(\n [&a, &b, &result](auto&& member) {\n using MetaMember = typename std::decay_t<decltype(member)>;\n constexpr auto p = meta::get_pointer<MetaMember>::value;\n result = result && equal(a.*p, b.*p);\n }\n );\n return result;\n#elif USING_CPP3K\n bool result = true;\n meta::for_each($T.member_variables(),\n [&a, &b, &result](auto&& member){\n result = result && equal(a.*member.pointer(), b.*member.pointer());\n }\n );\n return result;\n#endif\n }\n}\n\n} // namespace reflcompare\n" }, { "alpha_fraction": 0.686337411403656, "alphanum_fraction": 0.6882616877555847, "avg_line_length": 43.514286041259766, "blob_id": "3d0437a980c017519945d1995706ac7d71379e51", "content_id": "6117940c984ec25ff13be6996ffeeceea6c62b38", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1559, "license_type": "permissive", "max_line_length": 179, "num_lines": 35, "path": "/cmake/refl_experiments_add_benchmark.cmake", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "function(refl_experiments_add_benchmark benchmark_name N M output_prefix)\n set(output \"${output_prefix}_${N}.cpp\")\n set(full_name \"${benchmark_name}_${N}\")\n add_custom_command(\n OUTPUT ${full_name}_generated_ ${output}\n COMMAND python3 ${CMAKE_SOURCE_DIR}/benchmarks/generate_benchmark.py ${N} ${M} --in_filename ${CMAKE_SOURCE_DIR}/benchmarks/${benchmark_name}.cpp.empy --out_filename ${output}\n COMMAND ${CMAKE_COMMAND} -E touch ${full_name}_generated_\n DEPENDS\n ${CMAKE_SOURCE_DIR}/benchmarks/generate_benchmark.py\n ${CMAKE_SOURCE_DIR}/benchmarks/${benchmark_name}.cpp.empy\n )\n add_custom_target(${full_name}_generated DEPENDS ${full_name}_generated_)\n\n #list(GET build_type ${ARGN} 0)\n\n if(\"${ARGN}\" STREQUAL \"refl\")\n # TODO Target name!\n add_executable(${full_name} ${output})\n target_include_directories(\n ${full_name} PUBLIC ${CMAKE_SOURCE_DIR}/include/reflection_experiments ${Hana_INCLUDE_DIRS})\n target_compile_options(${full_name} PUBLIC \"-std=c++1z;-Xclang;-freflection;-DBOOST_HANA_CONFIG_ENABLE_STRING_UDL\")\n\n elseif(\"${ARGN}\" STREQUAL \"boost\")\n if(Boost_FOUND)\n add_executable(${full_name} ${output})\n target_include_directories(${full_name} PUBLIC ${Boost_INCLUDE_DIRS})\n target_link_libraries(${full_name} PUBLIC ${Boost_LIBRARIES})\n else()\n message(WARNING \"Boost program_options not found, comparison will not be built\")\n endif()\n else()\n message(FATAL_ERROR \"build type was wrong\")\n endif()\n add_dependencies(${full_name} ${full_name}_generated)\nendfunction()\n\n" }, { "alpha_fraction": 0.7014027833938599, "alphanum_fraction": 0.7014027833938599, "avg_line_length": 37.38461685180664, "blob_id": "7e34e6c9fe9b1cbc2ba0707b2c45ff5abe8ac233", "content_id": "275d4f66d0a543931c0cee555dc354d970d6a456", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 499, "license_type": "permissive", "max_line_length": 74, "num_lines": 13, "path": "/cmake/refl_experiments_include_dirs.cmake", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "function(refl_experiments_include_dirs target_name)\n set(full_target ${target_name}_${refl_keyword})\n if(TARGET ${full_target})\n target_include_directories(${full_target} PUBLIC ${ARGN})\n endif()\n\n set(full_target ${target_name}_${refl_keyword}_test)\n if(TARGET ${full_target})\n target_include_directories(${full_target} PUBLIC ${ARGN})\n elseif(NOT TARGET ${target_name}_${refl_keyword})\n message(FATAL_ERROR \"No valid target ${target_name} found. Aborting.\")\n endif()\nendfunction()\n" }, { "alpha_fraction": 0.7603305578231812, "alphanum_fraction": 0.7685950398445129, "avg_line_length": 16.285715103149414, "blob_id": "674bd3b148e05726655c514d653aa47c9b71dc7e", "content_id": "b82a1710a64091731fe45bd941d9c4d55dc47481", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 121, "license_type": "permissive", "max_line_length": 38, "num_lines": 7, "path": "/include/reflection_experiments/refl_utilities.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n\n#if USING_REFLEXPR\n#include \"reflexpr/refl_utilities.hpp\"\n#else\n#include \"cpp3k/refl_utilities.hpp\"\n#endif\n" }, { "alpha_fraction": 0.7521126866340637, "alphanum_fraction": 0.7549296021461487, "avg_line_length": 58.16666793823242, "blob_id": "4f6cef57fd7e9048268e4ecb312f9cfa8b2071bf", "content_id": "7611a99bb4531bbfe26e959933d07041c8c3f822", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 355, "license_type": "permissive", "max_line_length": 102, "num_lines": 6, "path": "/cmake/refl_experiments_add_executable.cmake", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "function(refl_experiments_add_executable target_name)\n set(full_target ${target_name}_${refl_keyword})\n add_executable(${full_target} ${target_name}.cpp)\n target_include_directories(${full_target} PUBLIC ${CMAKE_SOURCE_DIR}/include/reflection_experiments)\n target_compile_options(${full_target} PUBLIC \"-std=c++1z;-Xclang;-freflection\")\nendfunction()\n" }, { "alpha_fraction": 0.580777108669281, "alphanum_fraction": 0.6441717743873596, "avg_line_length": 18.559999465942383, "blob_id": "924422f8283a0839115f0e57fc9c64c2eac83d94", "content_id": "68634e1c50f33bf8fba18969b41c983371301c28", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 489, "license_type": "permissive", "max_line_length": 52, "num_lines": 25, "path": "/src/comparisons.cpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#include \"comparisons.hpp\"\n\n#include <cassert>\n\nstruct primitives {\n int int_member;\n unsigned uint_member;\n\n long long_member;\n unsigned long ulong_member;\n\n float float_member;\n double double_member;\n\n std::string string_member;\n};\n\nint main() {\n primitives a{1, 2, 3, 4, 5.6, 7.8, \"hello world\"};\n primitives b{1, 2, 3, 4, 5.6, 7.8, \"hello world\"};\n primitives c{9, 10, 11, 12, 13.14, 15.16, \"foo\"};\n\n assert(reflcompare::equal(a, b));\n assert(!reflcompare::equal(a, c));\n}\n" }, { "alpha_fraction": 0.5892131328582764, "alphanum_fraction": 0.594875156879425, "avg_line_length": 29.013071060180664, "blob_id": "a87c5f233197d5a9abd620e5d9232913ca50e3a6", "content_id": "fe243601b49306f0077c267dd04f0110dd17705a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13776, "license_type": "permissive", "max_line_length": 119, "num_lines": 459, "path": "/include/reflection_experiments/reflser.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <algorithm>\n#include <string>\n#include <string_view>\n\n#include <boost/lexical_cast.hpp>\n\n#include \"macros.hpp\"\n#include \"meta_utilities.hpp\"\n#include \"refl_utilities.hpp\"\n\n#if USING_REFLEXPR\n#include <reflexpr>\n#elif USING_CPP3K\n#else\nNO_REFLECTION_IMPLEMENTATION_FOUND()\n#endif\n\nnamespace reflser {\n\n#if USING_REFLEXPR\nnamespace meta = std::meta;\n#elif USING_CPP3K\nnamespace meta = cpp3k::meta;\n#endif\nnamespace refl = jk::refl_utilities;\nnamespace metap = jk::metaprogramming;\n\nenum struct scan_result {\n continue_scanning,\n stop_scanning,\n error\n};\n\n// strip the surrounding whitespace\n// TODO: other characters besides ' '\nstd::string_view strip_whitespace(const std::string_view& src) {\n unsigned i1 = 0;\n if (src[i1] == ' ') {\n for (; i1 < src.size() - 1; i1++) {\n if (src[i1] != ' ' || src[i1 + 1] != ' ') {\n i1 += 1;\n break;\n }\n }\n }\n\n unsigned i2 = src.size();\n if (src[i2 - 1] == ' ') {\n for (i2 = src.size() - 2; i2 > 0; i2--) {\n if (src[i2] != ' ') {\n i2 += 1;\n break;\n }\n }\n }\n\n return src.substr(i1, i2 - i1);\n}\n\n// returns the substring \n// needs to be able to propagate an error\ntemplate<typename T>\nauto get_token_of_type(const std::string_view& src) {\n unsigned count = 0;\n\n auto condition = [](const std::string_view& str, unsigned i) {\n if constexpr (std::is_floating_point<T>{}) {\n char token = str[i];\n if (token == '-') {\n if (i != 0) {\n return scan_result::error;\n }\n }\n\n if (!std::isdigit(token) && token != '.') {\n return scan_result::stop_scanning;\n }\n return scan_result::continue_scanning;\n\n } else if constexpr (std::is_integral<T>{}) {\n char token = str[i];\n if (token == '-') {\n if constexpr (!std::is_signed<T>{}) {\n return scan_result::error;\n } else if (i != 0) {\n return scan_result::error;\n }\n }\n if (!std::isdigit(token)) {\n return scan_result::stop_scanning;\n }\n return scan_result::continue_scanning;\n } else {\n return scan_result::error;\n }\n };\n\n scan_result result;\n while ((result = condition(src, count++)) == scan_result::continue_scanning && count < src.size()) { }\n if (result == scan_result::error) {\n return std::string_view();\n }\n\n auto token = src.substr(0, count);\n\n if constexpr (std::is_floating_point<T>{}) {\n if (std::count(token.begin(), token.end(), '.') > 1) {\n return std::string_view();\n }\n }\n return token;\n}\n\ntemplate<typename TokenT, typename T>\nauto scan_for_end_token(TokenT open, TokenT close, const T& src) {\n // Scan src\n unsigned token_depth = 0;\n unsigned count = 0;\n do {\n if (src[count] == open) {\n ++token_depth;\n } else if (src[count] == close) {\n if (token_depth > 0) {\n --token_depth;\n } else {\n // we're done\n return count;\n }\n }\n } while (count++ < src.size());\n // better error indication?\n return count;\n}\n\n// Assumes that the first open token is already passed\ntemplate<typename TokenT, typename T>\nauto count_outer_element_until_end(TokenT token,\n const std::string_view& open_tokens, const std::string_view& close_tokens,\n const T& src) {\n unsigned token_depth = 0;\n unsigned count = 0;\n unsigned token_count = 0;\n do {\n if (src[count] == token && token_depth == 0) {\n ++token_count;\n } else if (open_tokens.find(src[count]) != std::string::npos) {\n ++token_depth;\n } else if (close_tokens.find(src[count]) != std::string::npos) {\n if (token_depth > 0) {\n --token_depth;\n } else {\n return token_count;\n }\n }\n } while (count++ < src.size());\n // may want to indicate an error here\n return token_count;\n}\n\ntemplate<typename TokenT, typename T>\nauto scan_outer_element_until(TokenT token,\n const std::string_view& open_tokens, const std::string_view& close_tokens,\n const T& src) {\n // scan until token found\n unsigned token_depth = 0;\n unsigned count = 0;\n do {\n if (src[count] == token && token_depth == 0) {\n return src.substr(0, count);\n } else if (open_tokens.find(src[count]) != std::string::npos) {\n ++token_depth;\n } else if (close_tokens.find(src[count]) != std::string::npos) {\n if (token_depth > 0) {\n --token_depth;\n } else {\n return src.substr(0, count);\n }\n }\n } while (count++ < src.size());\n\n // better error indication?\n return std::string_view();\n}\n\nenum struct serialize_result {\n success,\n unknown_type\n};\n\nstd::string serialize_result_message(serialize_result result) {\n switch(result) {\n case serialize_result::success:\n return \"Success\";\n case serialize_result::unknown_type:\n return \"Don't know how to serialize to output type\";\n }\n}\n\n// generic json serialization\ntemplate<typename T>\nauto serialize(const T& src, std::string& dst) {\n if constexpr (std::is_same<T, std::string>{}) {\n dst += \"\\\"\" + src + \"\\\"\";\n return serialize_result::success;\n } else if constexpr (std::is_same<T, bool>{}) {\n dst += src ? \"true\" : \"false\";\n return serialize_result::success;\n } else if constexpr (metap::is_detected<metap::stringable, T>{}) {\n dst += std::to_string(src);\n return serialize_result::success;\n } else if constexpr (metap::is_detected<metap::iterable, T>{}) {\n // This structure has an array-like layout.\n dst += \"[ \";\n for (auto it = src.begin(); it != src.end(); ++it) {\n auto entry = *it;\n auto result = serialize(entry, dst);\n if (result != serialize_result::success) {\n return result;\n }\n if (it != (src.end() - 1)) {\n dst += \", \";\n }\n }\n dst += \" ]\";\n return serialize_result::success;\n#if USING_REFLEXPR\n } else if constexpr (meta::Record<reflexpr(T)>) {\n#elif USING_CPP3K\n } else if constexpr (refl::is_member_type<T>()) {\n#endif\n dst += \"{ \";\n\n serialize_result result = serialize_result::success;\n\n#if USING_REFLEXPR\n using MetaT = reflexpr(T);\n meta::for_each<meta::get_data_members_m<MetaT>>(\n [&src, &dst, &result](auto&& member_info){\n using MetaInfo = std::decay_t<decltype(member_info)>;\n dst += std::string(\"\\\"\") + meta::get_base_name_v<MetaInfo> + \"\\\"\" + \" : \";\n if (result = serialize(src.*meta::get_pointer<MetaInfo>::value, dst);\n result != serialize_result::success) {\n return;\n }\n dst += \", \";\n });\n#elif USING_CPP3K\n meta::for_each($T.member_variables(),\n [&src, &dst, &result](auto&& member) {\n dst += std::string(\"\\\"\") + member.name() + \"\\\"\" + \" : \";\n if (result = serialize(src.*member.pointer(), dst);\n result != serialize_result::success) {\n return;\n }\n dst += \", \";\n }\n );\n#endif\n // take off the last character\n if (result == serialize_result::success) {\n dst.replace(dst.size() - 2, 2, \" }\");\n }\n return result;\n }\n return serialize_result::unknown_type;\n}\n\n// generic json deserialization\nenum struct deserialize_result {\n success,\n empty_input,\n malformed_input,\n mismatched_token,\n mismatched_type,\n unknown_type\n};\n\nstd::string deserialize_result_message(deserialize_result result) {\n switch(result) {\n case deserialize_result::success:\n return \"Success\";\n case deserialize_result::empty_input:\n return \"Input string to deserialize was empty\";\n case deserialize_result::malformed_input:\n return \"Input string to deserialize was malformed\";\n case deserialize_result::mismatched_token:\n return \"A token was mismatched (e.g. missing open or close brace)\";\n case deserialize_result::mismatched_type:\n return \"Type of output didn't match input schema (e.g. wrong number of fields)\";\n case deserialize_result::unknown_type:\n return \"Don't know how to deserialize to output type\";\n }\n}\n\n// TODO: better error code\ntemplate<typename T>\nauto deserialize(std::string_view& src, T& dst) {\n if (src.empty()) {\n return deserialize_result::empty_input;\n }\n if constexpr (std::is_same<T, std::string>{}) {\n // Scan until the first quote\n auto quote_index = std::find(src.begin(), src.end(), '\"');\n\n if (quote_index == src.end()) {\n return deserialize_result::malformed_input;\n }\n src.remove_prefix(quote_index - src.begin() + 1);\n\n if (auto it = std::find(src.begin(), src.end(), '\"'); it != src.end()) {\n auto index = it - src.begin();\n dst = src.substr(0, index);\n return deserialize_result::success;\n }\n return deserialize_result::malformed_input;\n } else if constexpr (std::is_same<T, bool>{}) {\n if (strip_whitespace(src).substr(0, 4) == \"true\") {\n dst = true;\n return deserialize_result::success;\n } else if (strip_whitespace(src).substr(0, 5) == \"false\") {\n dst = false;\n return deserialize_result::success;\n }\n return deserialize_result::malformed_input;\n } else if constexpr (std::is_arithmetic<T>{}) {\n auto token = get_token_of_type<T>(strip_whitespace(src));\n auto token_count = token.size();\n if (token_count == 0) {\n return deserialize_result::malformed_input;\n }\n\n dst = boost::lexical_cast<T>(token);\n return deserialize_result::success;\n } else if constexpr (metap::is_detected<metap::iterable, T>{}) {\n // TODO src is wrong\n // TODO strip_whitespace is too aggressive\n auto stripped = strip_whitespace(src);\n if (stripped[0] != '[') {\n return deserialize_result::malformed_input;\n }\n stripped.remove_prefix(1);\n auto array_end = scan_for_end_token('[', ']', stripped);\n if (array_end <= 1) {\n return deserialize_result::mismatched_token;\n }\n\n auto array_token = stripped.substr(0, array_end);\n\n auto n_elements = count_outer_element_until_end(',', \"[{\", \"]}\", array_token) + 1;\n\n if constexpr (metap::is_detected<metap::resizable, T>{}) {\n dst.resize(n_elements);\n // TODO case where the container has dynamic size and is not default-constructible\n } else if constexpr (metap::is_detected<metap::has_tuple_size, T>{}) {\n if (std::tuple_size<T>{} != n_elements) {\n return deserialize_result::mismatched_type;\n }\n }\n assert(n_elements == dst.size());\n\n for (unsigned index = 0; index < n_elements; index++) {\n auto token = scan_outer_element_until(',', \"[{\", \"]}\", array_token);\n array_token.remove_prefix(token.size());\n if (auto result = deserialize(token, dst[index]); result != deserialize_result::success) {\n return result;\n }\n if (array_token[0] == ',') {\n array_token.remove_prefix(1);\n }\n }\n\n src.remove_prefix(array_token.size());\n return deserialize_result::success;\n#if USING_REFLEXPR\n } else if constexpr (meta::Record<reflexpr(T)>) {\n using MetaT = reflexpr(T);\n#elif USING_CPP3K\n } else if constexpr (refl::is_member_type<T>()) {\n#endif\n auto stripped = strip_whitespace(src);\n if (stripped[0] != '{') {\n return deserialize_result::malformed_input;\n }\n auto object_end = scan_for_end_token('{', '}', stripped);\n if (object_end == stripped.size()) {\n return deserialize_result::mismatched_token;\n }\n auto object_token = stripped.substr(1, object_end);\n\n auto n_colons = count_outer_element_until_end(':', \"{[\", \"}]\", object_token);\n auto n_commas = count_outer_element_until_end(',', \"{[\", \"}]\", object_token);\n\n if (n_colons != n_commas + 1) {\n return deserialize_result::malformed_input;\n }\n\n // TODO: switch for cpp3k\n#if USING_REFLEXPR\n if (n_colons != meta::get_size<meta::get_data_members_m<MetaT>>{}) {\n#elif USING_CPP3K\n if (n_colons != $T.member_variables().size()) {\n#endif\n return deserialize_result::mismatched_type;\n }\n\n deserialize_result result = deserialize_result::success;\n for (unsigned i = 0; i < n_colons; ++i) {\n auto key_index = std::find(object_token.begin(), object_token.end(), ':') - object_token.begin();\n\n auto quote_index = std::find(object_token.begin(), object_token.begin() + key_index, '\"') - object_token.begin();\n object_token.remove_prefix(quote_index + 1);\n quote_index = std::find(object_token.begin(), object_token.begin() + key_index, '\"') - object_token.begin();\n\n const auto key = object_token.substr(0, quote_index);\n key_index = std::find(object_token.begin(), object_token.end(), ':') - object_token.begin();\n object_token.remove_prefix(key_index + 1);\n\n auto value_token = scan_outer_element_until(',', \"{[\", \"}]\", object_token);\n auto value_index = value_token.size();\n object_token.remove_prefix(value_index);\n\n#if USING_REFLEXPR\n meta::for_each<meta::get_data_members_m<MetaT>>(\n [&dst, &key, &value_token, &result](auto&& metainfo) {\n using MetaInfo = std::decay_t<decltype(metainfo)>;\n constexpr auto name = meta::get_base_name_v<MetaInfo>;\n if (key == name) {\n constexpr auto p = refl::get_member_pointer<T, name>();\n if (result = deserialize(value_token, dst.*p);\n result != deserialize_result::success) {\n return;\n }\n }\n }\n );\n#elif USING_CPP3K\n meta::for_each($T.member_variables(),\n [&dst, &key, &value_token, &result](auto&& member) {\n if (key == member.name()) {\n if (result = deserialize(value_token, dst.*member.pointer());\n result != deserialize_result::success) {\n return;\n }\n }\n }\n );\n#endif\n if (result != deserialize_result::success) {\n return result;\n }\n }\n return deserialize_result::success;\n }\n return deserialize_result::unknown_type;\n}\n\n} // namespace reflser\n" }, { "alpha_fraction": 0.6304640769958496, "alphanum_fraction": 0.6331599950790405, "avg_line_length": 29.72780990600586, "blob_id": "65f99d33e92831ab92e08e5e50a012b7254a7643", "content_id": "9ac8ee3b6e56f1fb36cba636ae4496d7e29f6ec5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5193, "license_type": "permissive", "max_line_length": 87, "num_lines": 169, "path": "/include/reflection_experiments/reflopt.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <boost/hana/at_key.hpp>\n#include <boost/hana/fold.hpp>\n#include <boost/hana/for_each.hpp>\n#include <boost/hana/plus.hpp>\n#include <boost/hana/map.hpp>\n#include <boost/hana/string.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <boost/lexical_cast.hpp>\n\n#include <experimental/optional>\n\n#include \"refl_utilities.hpp\"\n#include \"meta_utilities.hpp\"\n\n#include <boost/hana/length.hpp>\n\n#if USING_REFLEXPR\n#elif USING_CPP3K\n#include \"cpp3k/adapt_hana.hpp\"\n#else\nNO_REFLECTION_IMPLEMENTATION_FOUND()\n#endif\n\nnamespace reflopt {\n static const size_t max_value_length = 128;\n\n namespace refl = jk::refl_utilities;\n namespace metap = jk::metaprogramming;\n namespace hana = boost::hana;\n using namespace hana::literals;\n\n template<typename T>\n using optional_t = std::experimental::optional<T>;\n\n // Compare a hana string to a const char*\n template<typename Str>\n bool runtime_string_compare(const Str&, const char* x) {\n return strcmp(hana::to<const char*>(Str{}), x) == 0;\n }\n\n#if USING_REFLEXPR\n namespace meta = std::meta;\n template<typename T, size_t... I>\n static constexpr auto get_name_helper(std::index_sequence<I...>) {\n return hana::string_c<meta::get_base_name_v<T>[I]...>;\n }\n\n template<typename T>\n static constexpr auto get_name() {\n constexpr auto L = metap::cstrlen(meta::get_base_name_v<T>);\n return get_name_helper<T>(std::make_index_sequence<L>{});\n }\n#elif USING_CPP3K\n namespace meta = cpp3k::meta;\n\n template<typename T, size_t... I>\n static constexpr auto get_name_helper(std::index_sequence<I...>) {\n return hana::string_c<T::name()[I]...>;\n }\n\n template<typename T>\n static constexpr auto get_name() {\n constexpr auto L = metap::cstrlen(T::name());\n return get_name_helper<T>(std::make_index_sequence<L>{});\n }\n#endif\n\n template<typename OptionsStruct>\n struct OptionsMap {\n static constexpr auto collect_flags = [](auto&& flag_map, auto&& field) {\n using T = std::decay_t<decltype(field)>;\n\n constexpr auto field_name = get_name<T>();\n using FlagMap = std::decay_t<decltype(flag_map)>;\n constexpr auto flag = \"--\"_s + field_name;\n constexpr auto result = hana::insert(FlagMap{}, hana::make_pair(flag, T{}));\n using Result = std::decay_t<decltype(result)>;\n\n constexpr auto prefix = hana::drop_while(field_name,\n [](auto elem) {\n return hana::contains(Result{}, \"-\"_s + hana::string_c<elem>);\n }\n );\n\n static_assert(!hana::is_empty(prefix), \"Couldn't find unique short flag.\");\n\n return hana::insert(result,\n hana::make_pair(\"-\"_s + hana::string_c<hana::front(prefix)>, T{}));\n };\n\n#if USING_REFLEXPR\n using MetaOptions = reflexpr(OptionsStruct);\n template<typename... MetaFields>\n struct make_prefix_map {\n static constexpr auto helper() {\n return hana::fold(\n hana::make_tuple(MetaFields{}...),\n hana::make_map(),\n collect_flags\n );\n }\n };\n\n static constexpr auto prefix_map = meta::unpack_sequence_t<\n meta::get_data_members_m<MetaOptions>, make_prefix_map>::helper();\n\n#elif USING_CPP3K\n static constexpr auto prefix_map = hana::fold(\n refl::adapt_to_hana($OptionsStruct.member_variables()),\n hana::make_map(),\n collect_flags\n );\n#endif\n\n static_assert(!hana::length(hana::keys(prefix_map)) == hana::size_c<0>);\n\n static bool contains(const char* prefix) {\n return hana::fold(hana::keys(prefix_map),\n false,\n [&prefix](bool x, auto&& key) {\n return x || runtime_string_compare(key, prefix);\n }\n );\n }\n\n static auto set(OptionsStruct& options, const char* prefix, const char* value) {\n hana::for_each(hana::keys(prefix_map),\n [&options, &prefix, &value](const auto& key) {\n if (runtime_string_compare(key, prefix)) {\n constexpr auto info = hana::at_key(prefix_map, decltype(key){});\n#if USING_REFLEXPR\n using MetaInfo = std::decay_t<decltype(info)>;\n constexpr auto member_pointer = meta::get_pointer<MetaInfo>::value;\n using MemberType = meta::get_reflected_type_t<meta::get_type_m<MetaInfo>>;\n#elif USING_CPP3K\n constexpr auto member_pointer = info.pointer();\n using MemberType = refl::unreflect_member_t<OptionsStruct, decltype(info)>;\n#endif\n options.*member_pointer = boost::lexical_cast<MemberType>(\n value, strnlen(value, max_value_length));\n }\n }\n );\n }\n };\n\n // ArgVT boilerplate is to enable both char** and const char*[]'s for testing\n template<typename OptionsStruct, typename ArgVT,\n typename std::enable_if_t<\n std::is_same<ArgVT, char**>{} || std::is_same<ArgVT, const char**>{}>* = nullptr\n >\n optional_t<OptionsStruct> parse(int argc, ArgVT const argv) {\n OptionsStruct options;\n for (int i = 1; i < argc; i += 2) {\n if (OptionsMap<OptionsStruct>::contains(argv[i])) {\n OptionsMap<OptionsStruct>::set(options, argv[i], argv[i + 1]);\n } else {\n // unknown prefix found\n return std::experimental::nullopt;\n }\n }\n\n return options;\n }\n\n} // namespace reflopt\n" }, { "alpha_fraction": 0.5747523903846741, "alphanum_fraction": 0.6123012900352478, "avg_line_length": 29.14583396911621, "blob_id": "8dc04c860730e4ed49d4beee7c4643ce635dd26a", "content_id": "bfb108ac95f5f4a7e9e57b0580c715d07f463ef0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4341, "license_type": "permissive", "max_line_length": 327, "num_lines": 144, "path": "/test/serialization.cpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#include \"comparisons.hpp\"\n#include \"reflser.hpp\"\n\n#include <array>\n#include <iostream>\n#include <vector>\n\nstruct primitives {\n int int_member;\n unsigned uint_member;\n\n long long_member;\n unsigned long ulong_member;\n\n float float_member;\n double double_member;\n\n std::string string_member;\n\n bool bool_member;\n};\n\ntemplate<auto N>\nstruct arrays_of_primitives {\n std::array<int, N> int_member;\n std::array<unsigned, N> uint_member;\n\n std::array<long, N> long_member;\n std::array<unsigned long, N> ulong_member;\n\n std::array<float, N> float_member;\n std::array<double, N> double_member;\n\n std::array<std::string, N> string_member;\n};\n\nstruct vectors_of_primitives {\n std::vector<int> int_member;\n std::vector<unsigned> uint_member;\n\n std::vector<long> long_member;\n std::vector<unsigned long> ulong_member;\n\n std::vector<float> float_member;\n std::vector<double> double_member;\n\n std::vector<std::string> string_member;\n};\n\nstruct nested {\n primitives primitives_member;\n vectors_of_primitives vector_member;\n};\n\ntemplate<typename T>\nint test(const T& reference, const std::string& test_string) {\n std::string dst = \"\";\n if (auto result = reflser::serialize(reference, dst);\n result != reflser::serialize_result::success) {\n std::cout << reflser::serialize_result_message(result) << \"\\n\";\n return 255;\n }\n std::cout << dst << \"\\n\";\n std::cout << test_string << \"\\n\";\n assert(dst == test_string);\n\n T deserialized;\n std::string_view dst_view = dst;\n if (auto result = reflser::deserialize(dst_view, deserialized);\n result != reflser::deserialize_result::success) {\n std::cout << reflser::deserialize_result_message(result) << \"\\n\";\n return 255;\n }\n\n dst = \"\";\n\n if (auto result = reflser::serialize(deserialized, dst);\n result != reflser::serialize_result::success) {\n std::cout << reflser::serialize_result_message(result) << \"\\n\";\n return 255;\n }\n std::cout << dst << \"\\n\";\n std::cout << test_string << \"\\n\";\n assert(dst == test_string);\n\n assert(reflcompare::equal(reference, deserialized));\n return 0;\n};\n\nint main(int argc, char** argv) {\n const primitives primitives_test{1, 2, 3, 4, 5.6, 7.8, \"hello world\", true};\n const arrays_of_primitives<2> aop_test{\n {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9.1, 10.2}, {11.3, 12.4}, {\"hello\", \"world\"}};\n\n const int vop_size = 3;\n vectors_of_primitives vop_test;\n for (int i = 0; i < vop_size; ++i) {\n vop_test.int_member.push_back(i);\n vop_test.uint_member.push_back(i + 1);\n\n vop_test.long_member.push_back(i + 2);\n vop_test.ulong_member.push_back(i + 3);\n\n vop_test.float_member.push_back(i + 4.1);\n vop_test.double_member.push_back(i + 5.1);\n }\n vop_test.string_member = {\"hello\", \"world\", \"!\"};\n\n const nested nested_test{primitives_test, vop_test};\n\n // Primitives\n const std::string primitives_test_string = \"{ \\\"int_member\\\" : 1, \\\"uint_member\\\" : 2, \\\"long_member\\\" : 3, \\\"ulong_member\\\" : 4, \\\"float_member\\\" : 5.600000, \\\"double_member\\\" : 7.800000, \\\"string_member\\\" : \\\"hello world\\\", \\\"bool_member\\\" : true }\";\n {\n if (int retcode = test(primitives_test, primitives_test_string); retcode != 0) {\n return retcode;\n }\n }\n\n // Array of primitives\n {\n const std::string test_string = \"{ \\\"int_member\\\" : [ 1, 2 ], \\\"uint_member\\\" : [ 3, 4 ], \\\"long_member\\\" : [ 5, 6 ], \\\"ulong_member\\\" : [ 7, 8 ], \\\"float_member\\\" : [ 9.100000, 10.200000 ], \\\"double_member\\\" : [ 11.300000, 12.400000 ], \\\"string_member\\\" : [ \\\"hello\\\", \\\"world\\\" ] }\";\n if (int retcode = test(aop_test, test_string); retcode != 0) {\n return retcode;\n }\n }\n\n const std::string vop_test_string = \"{ \\\"int_member\\\" : [ 0, 1, 2 ], \\\"uint_member\\\" : [ 1, 2, 3 ], \\\"long_member\\\" : [ 2, 3, 4 ], \\\"ulong_member\\\" : [ 3, 4, 5 ], \\\"float_member\\\" : [ 4.100000, 5.100000, 6.100000 ], \\\"double_member\\\" : [ 5.100000, 6.100000, 7.100000 ], \\\"string_member\\\" : [ \\\"hello\\\", \\\"world\\\", \\\"!\\\" ] }\";\n // Vector of primitives\n {\n if (int retcode = test(vop_test, vop_test_string); retcode != 0) {\n return retcode;\n }\n }\n\n {\n const std::string test_string = \"{ \\\"primitives_member\\\" : \" + primitives_test_string\n + \", \\\"vector_member\\\" : \" + vop_test_string + \" }\";\n if (int retcode = test(nested_test, test_string); retcode != 0) {\n return retcode;\n }\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.7627118825912476, "alphanum_fraction": 0.7699757814407349, "avg_line_length": 30.769229888916016, "blob_id": "d7ad8521503911a3fc25ab1d81b1c8fbbf611dc8", "content_id": "7aff315f11be40e3e25fcff2dc055a21d69effd7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1239, "license_type": "permissive", "max_line_length": 100, "num_lines": 39, "path": "/CMakeLists.txt", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.5)\n\nproject(reflection_experiments VERSION 0.0.1 LANGUAGES CXX)\ninclude(ExternalProject)\n\ninclude(cmake/refl_experiments_add_executable.cmake)\ninclude(cmake/refl_experiments_include_dirs.cmake)\n\nunset(refl_keyword)\nif(DEFINED REFLEXPR_PATH)\n set(refl_keyword \"reflexpr\" CACHE STRING \"key for reflection facility headers\")\n add_definitions(-DUSING_REFLEXPR)\n include_directories(${REFLEXPR_PATH})\nelseif(DEFINED CPP3K_PATH)\n set(refl_keyword \"cpp3k\" CACHE STRING \"key for reflection facility headers\")\n add_definitions(-DUSING_CPP3K)\n include_directories(${CPP3K_PATH})\n set(CMAKE_CXX_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} -stdlib=libc++\")\n set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} -lc++abi\")\nelse()\n message(FATAL_ERROR \"No reflection fork was specified. Unable to build targets using reflection.\")\nendif()\n\nlist(APPEND CMAKE_MODULE_PATH \"${CMAKE_SOURCE_DIR}/extlibs/hana/cmake/\")\nset(Hana_ROOT \"${CMAKE_SOURCE_DIR}/extlibs/hana\")\nfind_package(Hana)\n\n# Build example executables\nadd_subdirectory(src)\n\nif(ENABLE_TESTING)\n include(cmake/refl_experiments_add_test.cmake)\n include(CTest)\n add_subdirectory(test)\nendif()\n\nif(DEFINED BUILD_BENCHMARKS)\n add_subdirectory(benchmarks)\nendif()\n" }, { "alpha_fraction": 0.6297681331634521, "alphanum_fraction": 0.6297681331634521, "avg_line_length": 29.386363983154297, "blob_id": "7f534a9166209b1ee9e89d11287c7ccfcf9fc15a", "content_id": "13ffc904b21b8a56feebccfc53811d806be4f5fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1337, "license_type": "permissive", "max_line_length": 89, "num_lines": 44, "path": "/src/type_synthesis.cpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "/* Type synthesis with reflexpr proof of concept\n *\n * This example assumes default-constructible parameters.\n * */\n\n#include <iostream>\n\n#include \"type_synthesis.hpp\"\n\nstruct old_type {\n int foo;\n float baz;\n};\n\nint main() {\n using namespace type_synthesis;\n /*\n using new_type =\n synthesize_type<old_type, add_member<std::string, decltype(\"bar\"_s)>,\n remove_member<decltype(\"baz\"_s)>>::result;\n */\n using new_type = synthesize_type<old_type>(add_member<std::string>(\"bar\"),\n remove_member(\"baz\"))::result;\n\n // Does not compile: cannot remove qux because it is not a member of the original type.\n // using new_type = synthesize_type<old_type>(remove_member(\"qux\"_s));\n\n // Does not compile: foo is already a member of the original type, we can't add it.\n // using new_type = synthesize_type<old_type(add_member<char>(\"foo\"));\n\n new_type x;\n\n auto foo_v = access(x, \"foo\"_s);\n static_assert(std::is_same<std::decay_t<decltype(foo_v)>, int>{});\n\n auto bar_v = access(x, \"bar\"_s);\n static_assert(std::is_same<std::decay_t<decltype(bar_v)>, std::string>{});\n\n // Does not compile: baz was removed from the synthesized type\n // access(x, \"baz\"_s);\n\n // Does not compile: qux is not a member of the synthesized type\n // access(x, \"qux\"_s);\n}\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 18.25, "blob_id": "45c1bd190cf685fc06b19d78d64accbf8bd4f72f", "content_id": "9c14f27f7bc0afa2d7d43228315213e39473f4a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 77, "license_type": "permissive", "max_line_length": 31, "num_lines": 4, "path": "/cmake/get_refl_keyword.cmake", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "macro(get_refl_keyword)\n if (NOT DEFINED refl_keyword)\n endif()\nendmacro()\n" }, { "alpha_fraction": 0.6549019813537598, "alphanum_fraction": 0.6558431386947632, "avg_line_length": 31.525510787963867, "blob_id": "9e4982583bb5c0d5475cc366975556771b9f32e1", "content_id": "c0539efedd13cf1f6ab31bc7d7e1e5ed08e90927", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6375, "license_type": "permissive", "max_line_length": 86, "num_lines": 196, "path": "/include/reflection_experiments/reflexpr/type_synthesis.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <reflexpr>\n#include <tuple>\n\n#include \"refl_utilities.hpp\"\n#include \"string_literal.hpp\"\n\nnamespace type_synthesis {\n\nnamespace refl = jk::refl_utilities;\nnamespace sl = jk::string_literal;\n\ntemplate <typename KeyT, typename Name>\nstruct associative_access {\n template <size_t... i>\n constexpr static std::size_t access_helper(std::index_sequence<i...> &&) {\n static_assert((sl::compare<Name>(std::get<i>(KeyT::value)) || ...),\n \"Key index not found in synthesized type\");\n return ((sl::compare<Name>(std::get<i>(KeyT::value)) ? i : 0) + ...);\n }\n\n constexpr static std::size_t value = access_helper(\n std::make_index_sequence<std::tuple_size_v<typename KeyT::type>>());\n};\n\ntemplate <typename T, typename I> struct get_element_until;\n\ntemplate <typename T, size_t... i>\nstruct get_element_until<T, std::index_sequence<i...>> {\n using type = std::tuple<std::tuple_element_t<i, T>...>;\n\n constexpr static auto slice(const T &sliced) {\n return std::make_tuple(std::get<i>(sliced)...);\n }\n};\n\ntemplate <typename T, size_t Skip, typename I> struct get_element_after;\n\ntemplate <typename T, size_t Skip, size_t... i>\nstruct get_element_after<T, Skip, std::index_sequence<i...>> {\n using type = std::tuple<std::tuple_element_t<i + Skip + 1, T>...>;\n\n constexpr static auto slice(const T &sliced) {\n return std::make_tuple(std::get<i + Skip + 1>(sliced)...);\n }\n};\n\ntemplate <typename OriginalKeyT, size_t RemoveIndex> struct remove_key_wrapper {\n using TupleT = typename OriginalKeyT::type;\n constexpr static std::size_t N = std::tuple_size_v<TupleT>;\n\n constexpr static auto value = std::tuple_cat(\n get_element_until<TupleT, std::make_index_sequence<RemoveIndex>>::slice(\n OriginalKeyT::value),\n get_element_after<TupleT, RemoveIndex,\n std::make_index_sequence<N - RemoveIndex - 1>>::\n slice(OriginalKeyT::value));\n using type = std::decay_t<decltype(value)>;\n};\n\ntemplate <typename T, typename Name>\nstruct remove_at_key {\n constexpr static auto removed_index =\n associative_access<typename T::key_type, Name>::value;\n constexpr static auto N = std::tuple_size_v<typename T::tuple_type>;\n\n using values = std::decay_t<decltype(\n std::tuple_cat(std::declval<typename get_element_until<\n typename T::tuple_type,\n std::make_index_sequence<removed_index>>::type>(),\n std::declval<typename get_element_after<\n typename T::tuple_type, removed_index,\n std::make_index_sequence<N - removed_index - 1>>::type>()))>;\n\n using keys = remove_key_wrapper<typename T::key_type, removed_index>;\n};\n\ntemplate <typename MetaObj> struct object_keys {\n template <typename... MetaArgs> struct keys_helper {\n constexpr static auto keys =\n std::make_tuple(std::meta::get_base_name_v<MetaArgs>...);\n };\n\n constexpr static auto value =\n std::meta::unpack_sequence_t<std::meta::get_data_members_m<MetaObj>,\n keys_helper>::keys;\n using type = std::decay_t<decltype(value)>;\n};\n\ntemplate <typename T, typename ObjKeys> struct key_wrapper {\n // Unpack the first member of T\n template <typename P, typename I> struct check_helper;\n\n template <typename Name, size_t... i>\n struct check_helper<Name, std::index_sequence<i...>> {\n static_assert(!(sl::compare<Name>(std::get<i>(ObjKeys::value)) ||\n ...),\n \"Cannot add member which is already in type.\");\n };\n\n constexpr static auto check = check_helper<\n std::tuple_element_t<0, T>,\n std::make_index_sequence<std::tuple_size_v<typename ObjKeys::type>>>{};\n\n constexpr static auto value = std::tuple_cat(T{}, ObjKeys::value);\n using type = std::decay_t<decltype(value)>;\n};\n\ntemplate <typename KeyT, typename ValueT>\nstruct labeled_container {\n template <typename Name>\n auto &get(Name &&) {\n return std::get<associative_access<KeyT, Name>::value>(values);\n }\n\n constexpr static auto keys = KeyT::value;\n ValueT values;\n\n using key_type = KeyT;\n using value_type = ValueT;\n};\n\n/* Type synthesis utilities\n * */\n\n// base case\ntemplate <typename T> struct synthesized_type {\n using MetaObj = reflexpr(T);\n using tuple_type =\n std::meta::unpack_sequence_t<std::meta::get_data_members_m<MetaObj>,\n refl::member_pack_as_tuple>;\n\n template <char... Pack> auto &get(sl::string_literal<Pack...> &&p) {\n // delegate\n return members.get(std::forward<sl::string_literal<Pack...>>(p));\n }\n\n // Now, we must operate on the members.\n labeled_container<object_keys<MetaObj>, tuple_type> members;\n\n using key_type = typename decltype(members)::key_type;\n using value_type = tuple_type;\n};\n\ntemplate <typename T, typename... Operations> struct synthesize_type;\n\n// TODO: recursion is bad for compile time performance\ntemplate <typename T, typename Operator, typename... Operations>\nstruct synthesize_type<T, Operator, Operations...> {\n using result = typename Operator::template apply<\n typename synthesize_type<T, Operations...>::result>;\n\n constexpr synthesize_type(Operator&&, Operations&&...) { }\n};\n\ntemplate <typename T> struct synthesize_type<T> {\n using result = synthesized_type<T>;\n};\n\n/* Operations for synthesizing types\n * */\n// Add a member of type T and name Name\ntemplate <typename FieldType> struct add_member {\n constexpr add_member(const string_literal& name) {\n // TODO\n };\n\n template <typename T, typename TupleT> struct meta_tuple_cat;\n\n template <typename T, typename... TupleArgs>\n struct meta_tuple_cat<T, std::tuple<TupleArgs...>> {\n using type = std::tuple<T, TupleArgs...>;\n };\n\n template <typename T>\n using apply = labeled_container<\n key_wrapper<std::tuple<PackIndex>, typename T::key_type>,\n typename meta_tuple_cat<Field, typename T::value_type>::type>;\n};\n\ntemplate <typename PackIndex> struct remove_member {\n template <typename T> using removed = remove_at_key<T, PackIndex>;\n\n // compile time error if field is not in T\n template <typename T>\n using apply =\n labeled_container<typename removed<T>::keys, typename removed<T>::values>;\n};\n\ntemplate <typename T, typename S> decltype(auto) access(T &&t, S &&s) {\n return t.get(std::forward<S>(s));\n}\n\n\n} // namespace type_synthesis\n" }, { "alpha_fraction": 0.6901057958602905, "alphanum_fraction": 0.6969508528709412, "avg_line_length": 29.903846740722656, "blob_id": "0bf86baa6e4210c1a35d8899549e58ed21b9e52e", "content_id": "437269605b12aae20ff792f6990d2383d2f1727b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1607, "license_type": "permissive", "max_line_length": 106, "num_lines": 52, "path": "/include/reflection_experiments/meta_utilities.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <experimental/type_traits>\n#include <string>\n#include <type_traits>\n#include <tuple>\n\nnamespace jk {\nnamespace metaprogramming {\n\n// from http://stackoverflow.com/questions/16337610/how-to-know-if-a-type-is-a-specialization-of-stdvector\ntemplate<typename Test, template<typename...> class Ref>\nstruct is_specialization : std::false_type {};\n\ntemplate<template<typename...> class Ref, typename... Args>\nstruct is_specialization<Ref<Args...>, Ref>: std::true_type {};\n\ntemplate<typename T>\nusing stringable = decltype(std::to_string(std::declval<T>()));\n\ntemplate<typename T>\nusing iterable = std::void_t<\n decltype(std::declval<T>().begin()), decltype(std::declval<T>().end())>;\n\ntemplate<typename T>\nusing resizable = decltype(std::declval<T>().resize(std::declval<size_t>()));\n// ???\n// using resizable = decltype(std::declval<T>().resize(std::declval<T::size_type>()));\n\ntemplate<typename T>\nusing has_tuple_size = decltype(std::tuple_size<T>::value);\n// TODO I want this to be like this but I think it might be a bug\n// using has_tuple_size = std::tuple_size<T>;\n\ntemplate<typename T>\nusing equality_comparable = decltype(std::declval<T>() == std::declval<T>());\n\ntemplate<template<typename ...> typename Op, typename... Args>\nusing is_detected = std::experimental::is_detected<Op, Args...>;\n\nstatic constexpr unsigned cstrlen(const char* str) {\n return *str ? 1 + cstrlen(str + 1) : 0;\n}\n\n// thx superv\n#define CONSTEXPR_ERROR(Message) \\\n [](auto x) { \\\n static_assert(decltype(x){}, Message); \\\n }(std::false_type{}); \\\n\n} // namespace metaprogramming\n} // namespace jk\n" }, { "alpha_fraction": 0.6828321814537048, "alphanum_fraction": 0.6857420206069946, "avg_line_length": 23.547618865966797, "blob_id": "9187a8e35e62e09ea92afd14eb3a77ad6407a87b", "content_id": "f1b2fc3378f8a1feeb3cf5d947cf518a696a0a75", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1031, "license_type": "permissive", "max_line_length": 74, "num_lines": 42, "path": "/include/reflection_experiments/cpp3k/refl_utilities.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"../meta_utilities.hpp\"\n#include \"../string_literal.hpp\"\n#include <cpp3k/meta>\n\n#include <cpp3k/detail/tuple.hpp>\n\nnamespace jk {\nnamespace refl_utilities {\n\nnamespace meta = cpp3k::meta;\nnamespace metap = jk::metaprogramming;\nnamespace sl = jk::string_literal;\n\ntemplate<typename T>\nusing has_member_variables = std::void_t<decltype($T.member_variables())>;\n\ntemplate<typename T>\nstatic constexpr bool is_member_type() {\n return metap::is_detected<has_member_variables, T>{};\n}\n\ntemplate<typename T, typename StrT>\nstatic constexpr bool has_member(StrT&& key) {\n bool has_member = false;\n meta::for_each($T.member_variables(),\n [&key, &has_member](auto&& member) {\n if constexpr (sl::equal(key, member.type_name())) {\n has_member = true;\n }\n }\n );\n return has_member;\n}\n\ntemplate<typename S, typename Member>\nusing unreflect_member_t = typename std::decay_t<\n decltype(std::declval<S>().*(std::decay_t<Member>::pointer()))>;\n\n} // namespace refl_utilities\n} // namespace jk\n" }, { "alpha_fraction": 0.8059071898460388, "alphanum_fraction": 0.8059071898460388, "avg_line_length": 46.400001525878906, "blob_id": "3500dada2d3ca74338b94013271e723c02d67468", "content_id": "9b7c005a51519efcc992f2eff907c9663b5218ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 237, "license_type": "permissive", "max_line_length": 99, "num_lines": 5, "path": "/test/CMakeLists.txt", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "refl_experiments_add_test(reflopt)\nrefl_experiments_include_dirs(reflopt ${Hana_INCLUDE_DIRS})\ntarget_compile_options(reflopt_${refl_keyword}_test PUBLIC \"-DBOOST_HANA_CONFIG_ENABLE_STRING_UDL\")\n\nrefl_experiments_add_test(serialization)\n" }, { "alpha_fraction": 0.7664233446121216, "alphanum_fraction": 0.7664233446121216, "avg_line_length": 33.25, "blob_id": "1c2f500a157e139203b65342f3763cdc13c6845b", "content_id": "6e09a260480077faecba2a636c5e65b355b6c751", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 137, "license_type": "permissive", "max_line_length": 75, "num_lines": 4, "path": "/include/reflection_experiments/macros.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n\n#define NO_REFLECTION_IMPLEMENTATION_FOUND() \\\n static_assert(false, \"No reflection implementation found, bailing out!\");\n" }, { "alpha_fraction": 0.6481732130050659, "alphanum_fraction": 0.6513306498527527, "avg_line_length": 24.482759475708008, "blob_id": "43c00384cd18756ef794e116dc0a762d89076ab4", "content_id": "64a32f3198cb8f28cf7f12cb2723233c972d60ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2217, "license_type": "permissive", "max_line_length": 89, "num_lines": 87, "path": "/include/reflection_experiments/string_literal.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <array>\n#include <string>\n\n#include <cstring>\n\nnamespace jk {\nnamespace string_literal {\n\n// Heavily inspired by mpark and ubsan\n// For some reason, auto and decltype(auto) crash Clang\n#define CONSTANT(...) \\\n struct { \\\n static constexpr jk::string_literal::string_literal value() { return __VA_ARGS__; } \\\n } \\\n\nstruct string_literal {\n constexpr string_literal(const char* v, unsigned x) : value(v), s(x) { }\n constexpr auto size() const { return s; };\n constexpr auto data() const { return value; };\n constexpr auto char_at(unsigned i) const { return value[i]; };\nprivate:\n const char* value;\n const unsigned s;\n};\n\nstatic constexpr unsigned length(const char* str) {\n return *str ? 1 + length(str + 1) : 0;\n}\n\ntemplate<auto V>\nstruct string_constant {\n static constexpr auto value() {\n return string_literal(V, length(V));\n };\n};\n\n// what if this just was the string literal struct\n#define STRING_TYPE_DECL(StructName, ...) \\\n struct StructName { \\\n static constexpr jk::string_literal::string_literal value() { \\\n return jk::string_literal::string_literal(__VA_ARGS__, sizeof(__VA_ARGS__) - 1); \\\n } \\\n };\n\n#define STRING_LITERAL(value) \\\n []() { \\\n using Str = CONSTANT(jk::string_literal::string_literal{value, sizeof(value) - 1}); \\\n return Str{}; \\\n }() \\\n\n#define STRING_LITERAL_VALUE(value) \\\n jk::string_literal::string_literal{value, sizeof(value) - 1}\n\ntemplate<typename Str>\nstruct compare_helper {\n template<size_t... I>\n static constexpr bool apply(const char* v, std::index_sequence<I...>) {\n return ((Str::value().char_at(I) == v[I]) && ...);\n }\n};\n\ntemplate<typename Str>\nstatic constexpr bool empty(const Str&) {\n return Str::value().size() == 0;\n}\n\ntemplate<typename Str>\nstatic constexpr bool equal(const Str&, const Str& b) {\n return Str::value().data() == b.value().data();\n}\n\ntemplate<typename Str>\nstatic constexpr bool equal(const Str&, const char* b) {\n if (length(b) != Str::value().size()) {\n return false;\n } else {\n return compare_helper<Str>::apply(\n b, std::make_index_sequence<Str::value().size()>{});\n }\n}\n\nSTRING_TYPE_DECL(empty_string_t, \"\")\n\n} // namespace string_literal\n} // namespace jk\n" }, { "alpha_fraction": 0.7634069323539734, "alphanum_fraction": 0.7634069323539734, "avg_line_length": 34.22222137451172, "blob_id": "e2f283a083be01db9b44d5f3e70b919e77a37b2d", "content_id": "df508df66e539bdda7f6dfe87206fe2e9bf70ade", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 634, "license_type": "permissive", "max_line_length": 96, "num_lines": 18, "path": "/src/CMakeLists.txt", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "refl_experiments_add_executable(comparisons)\n\nif (Hana_FOUND)\n refl_experiments_add_executable(reflopt)\n refl_experiments_include_dirs(reflopt ${Hana_INCLUDE_DIRS})\n target_compile_options(reflopt_${refl_keyword} PUBLIC \"-DBOOST_HANA_CONFIG_ENABLE_STRING_UDL\")\nelse()\n message(WARNING \"Hana was not found, reflopt example will not be built.\")\nendif()\n\nrefl_experiments_add_executable(serialization)\n\nset(Boost_USE_STATIC_LIBS ON)\nset(Boost_USE_MULTITHREADED OFF)\nset(Boost_USE_STATIC_RUNTIME OFF)\n\n# need to revisit if this is worth working on...\n# refl_experiments_add_executable(type_synthesis type_synthesis.cpp)\n" }, { "alpha_fraction": 0.7381489872932434, "alphanum_fraction": 0.740406334400177, "avg_line_length": 43.29999923706055, "blob_id": "803dbfdd6070039f925e4592ea8615137664128f", "content_id": "849d28032c928e327659bd0d9be15c46568a8df5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 443, "license_type": "permissive", "max_line_length": 102, "num_lines": 10, "path": "/cmake/refl_experiments_add_test.cmake", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "# test options...\nfunction(refl_experiments_add_test target_name)\n set(full_target ${target_name}_${refl_keyword}_test)\n add_executable(${full_target} ${target_name}.cpp)\n target_include_directories(${full_target} PUBLIC ${CMAKE_SOURCE_DIR}/include/reflection_experiments)\n\n target_compile_options(${full_target} PUBLIC \"-std=c++1z;-Xclang;-freflection\")\n\n add_test(${full_target}_ctest ${full_target} CONFIGURATIONS Debug)\nendfunction()\n" }, { "alpha_fraction": 0.6380181908607483, "alphanum_fraction": 0.6491405367851257, "avg_line_length": 21.477272033691406, "blob_id": "c80f20aef3eaa97104896307ddd0508b8972c292", "content_id": "f3a3716e27882ac3a1df1754fdb04a41972d1036", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 989, "license_type": "permissive", "max_line_length": 117, "num_lines": 44, "path": "/src/serialization.cpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#include \"comparisons.hpp\"\n#include \"reflser.hpp\"\n\n#include <array>\n#include <iostream>\n#include <vector>\n\nstruct primitives {\n int int_member;\n unsigned uint_member;\n\n long long_member;\n unsigned long ulong_member;\n\n float float_member;\n double double_member;\n\n std::string string_member;\n\n bool bool_member;\n};\n\nint main(int argc, char** argv) {\n primitives primitives_test{1, 2, 3, 4, 5.6, 7.8, \"hello world\", true};\n {\n std::string dst = \"\";\n auto result = reflser::serialize(primitives_test, dst);\n std::cout << dst << \"\\n\";\n\n primitives deserialized;\n std::string_view dst_view = dst;\n if (auto result = reflser::deserialize(dst_view, deserialized); result != reflser::deserialize_result::success) {\n std::cout << reflser::deserialize_result_message(result) << \"\\n\";\n return 255;\n }\n\n dst = \"\";\n\n reflser::serialize(deserialized, dst);\n std::cout << dst << \"\\n\";\n\n assert(reflcompare::equal(primitives_test, deserialized));\n }\n}\n" }, { "alpha_fraction": 0.6605427861213684, "alphanum_fraction": 0.66096031665802, "avg_line_length": 25.032608032226562, "blob_id": "a992858b54ef097d2098126d803669cfda0b0f90", "content_id": "8e5917b9533859829d5f81a167da2ebee27a15e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2395, "license_type": "permissive", "max_line_length": 75, "num_lines": 92, "path": "/include/reflection_experiments/reflexpr/refl_utilities.hpp", "repo_name": "crysisfarcry222/reflection_experiments", "src_encoding": "UTF-8", "text": "#pragma once\n#include \"../string_literal.hpp\"\n#include <reflexpr>\n\n#include <experimental/type_traits>\n#include <variant>\n\nnamespace jk {\nnamespace refl_utilities {\n\nnamespace sl = string_literal;\nnamespace meta = std::meta;\n\ntemplate<typename MetaT>\nusing unreflect_type = meta::get_reflected_type_t<meta::get_type_m<MetaT>>;\n\ntemplate<typename ...Types>\nstruct reduce_pack {\n // Find the type in the pack which is non-void\n\n template <typename Tn, void* ...v>\n static Tn f(decltype(v)..., Tn, ...);\n\n using type = decltype(f(std::declval<Types>()...));\n};\n\ntemplate <typename... Members>\nusing member_pack_as_tuple = std::tuple<\n meta::get_reflected_type_t<meta::get_type_m<Members>>...>;\n\ntemplate<typename T>\nstruct n_fields : meta::get_size<meta::get_data_members_m<reflexpr(T)>> {};\n\n// generic meta-object fold\ntemplate<typename ...Object>\nstruct runtime_fold_helper {\n template<typename T, typename Init, typename Func>\n static inline auto apply(T&& t, Init&& init, Func&& func) {\n return fold(func, init, t.*meta::get_pointer<Object>::value ...);\n }\n};\n\ntemplate<typename ...MetaField>\nstruct has_member_pack {\n template<typename StrT>\n static constexpr bool apply(const StrT& name) {\n return (sl::equal(name, meta::get_base_name_v<MetaField>) || ...);\n }\n};\n\ntemplate<typename T, typename StrT>\nconstexpr bool has_member(const StrT& member_name) {\n return meta::unpack_sequence_t<\n meta::get_member_types_m<reflexpr(T)>, has_member_pack\n >::apply(member_name);\n}\n\ntemplate<typename T, auto Str, std::size_t ...I>\nstatic constexpr auto index_helper(std::index_sequence<I...>) {\n return ((Str ==\n meta::get_base_name_v<\n meta::get_element_m<\n meta::get_data_members_m<reflexpr(T)>, I>\n > ? I : 0\n ) + ...);\n}\n\ntemplate<typename T, auto Str>\nstatic constexpr auto index_of_member() {\n return index_helper<T, Str>(std::make_index_sequence<n_fields<T>{}>{});\n}\n\ntemplate<typename T, auto Str>\nconstexpr auto get_member_pointer() {\n return meta::get_pointer<\n meta::get_element_m<\n meta::get_data_members_m<reflexpr(T)>,\n index_of_member<T, Str>()\n >\n >::value;\n}\n\n// free metafunctions for metaobjects\nstruct get_name {\n template<typename MetaT>\n constexpr auto operator()(MetaT&& t) {\n return meta::get_base_name<MetaT>{};\n }\n};\n\n} // namespace refl_utilities\n} // namespace jk\n" } ]
28
sichiiii/shareVideoHosting
https://github.com/sichiiii/shareVideoHosting
884b8e6ea7fbe3d87fba4ab042bfd32868413f4e
33281282ce0f10c8abb380e782e951fcc93c8a28
dff0d8dafe3fa1f8d54602d26f1e3e250ba9daf8
refs/heads/main
2023-08-18T05:26:29.293046
2021-09-19T10:30:15
2021-09-19T10:30:15
402,761,496
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.7732997536659241, "alphanum_fraction": 0.7884131073951721, "avg_line_length": 43.11111068725586, "blob_id": "e99a1b2443119679251e4bc43dea1d2af8c8d02c", "content_id": "36cb03bb1f33199a908cef2f4e74e73925084912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 397, "license_type": "no_license", "max_line_length": 85, "num_lines": 9, "path": "/README.md", "repo_name": "sichiiii/shareVideoHosting", "src_encoding": "UTF-8", "text": "# shareVideoHosting\n\nShare yt video right in web-browser.\nBuild on Fastapi(actually first project on fastapi). Inline styles yeeeeaaahhh\n![1](https://github.com/sichiiii/shareVideoHosting/blob/main/pictures/1.gif?raw=true)\n\n![2](https://github.com/sichiiii/shareVideoHosting/blob/main/pictures/2.png?raw=true)\n\n![3](https://github.com/sichiiii/shareVideoHosting/blob/main/pictures/3.png?raw=true)\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7345911860466003, "avg_line_length": 33.565216064453125, "blob_id": "dafe681ce0514edbc06fa613aa21ebca91a81ec7", "content_id": "e271845fc1135146f005d14523ef6b3ebd374956", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1590, "license_type": "no_license", "max_line_length": 92, "num_lines": 46, "path": "/main.py", "repo_name": "sichiiii/shareVideoHosting", "src_encoding": "UTF-8", "text": "import re\nfrom fastapi import FastAPI, Request, Form, WebSocket\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect\nfrom fastapi.responses import HTMLResponse\n\nfrom pydantic import BaseModel\nfrom pathlib import Path\nfrom connection_manager import ConnectionManager\n\nimport url_checker\n\nshareVideoHostingApi = FastAPI()\nmanager = ConnectionManager()\n\nshareVideoHostingApi.mount(\n \"/static\",\n StaticFiles(directory=Path(__file__).parent.parent.absolute() / \"static\"),\n name=\"static\",\n)\ntemplates = Jinja2Templates(directory=\"templates\")\n\ndirectory=Path(__file__).parent.parent.absolute() \n\[email protected](\"/\")\nasync def root(request: Request):\n return templates.TemplateResponse(\"index.html\", {\"request\": request})\n\[email protected](\"/watch\")\nasync def watch(request: Request, url: str = Form(...)):\n urlCheckerObject = url_checker.Url_Checker(url)\n final_url = urlCheckerObject.get_url()\n return templates.TemplateResponse(\"watch.html\", {\"request\": request, \"url\" : final_url})\n \[email protected](\"/ws/{client_id}\")\nasync def websocket_endpoint(websocket: WebSocket, client_id: int):\n await manager.connect(websocket)\n try:\n while True:\n data = await websocket.receive_text()\n print(data)\n await manager.broadcast(f\"Client #{client_id}: {data}\")\n except WebSocketDisconnect:\n manager.disconnect(websocket)\n await manager.broadcast(f\"Client #{client_id} left the chat\")\n" }, { "alpha_fraction": 0.3940066695213318, "alphanum_fraction": 0.41065484285354614, "avg_line_length": 39.681819915771484, "blob_id": "188b7bcacec1d6b570c4069ff6722e3510d4cd4e", "content_id": "1179a27a9854da1bab8089d36c1d1d917317a313", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 911, "license_type": "no_license", "max_line_length": 201, "num_lines": 22, "path": "/url_checker.py", "repo_name": "sichiiii/shareVideoHosting", "src_encoding": "UTF-8", "text": "import re\nimport urllib.parse as up \n\nclass Url_Checker():\n def __init__(self, url):\n self.url = url \n\n def get_url(self):\n regex = r\"(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\\\".,<>?«»“”‘’]))\"\n url = re.findall(regex, self.url)\n query = up.urlparse(url[0][0])\n if query.hostname == 'youtu.be':\n return query.path[1:]\n if query.hostname in ('www.youtube.com', 'youtube.com'):\n if query.path == '/watch':\n p = up.parse_qs(query.query)\n return p['v'][0]\n if query.path[:7] == '/embed/':\n return query.path.split('/')[2]\n if query.path[:3] == '/v/':\n return query.path.split('/')[2] \n return [x[0] for x in url]\n " } ]
3
peterlebrun/sc
https://github.com/peterlebrun/sc
c81275d99ab758003e82c028da2d9c132222c7de
08568b6188300cef2be0a75b4da4e290861e0077
9360c65976a01ebcf77a618f14a58a2c01e6f3e6
refs/heads/master
2021-01-10T21:39:37.704128
2015-08-08T12:12:36
2015-08-08T12:12:36
40,417,871
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6182648539543152, "alphanum_fraction": 0.6255707740783691, "avg_line_length": 25.707317352294922, "blob_id": "994b597978f2b7abfae37daaa6d5365b18055870", "content_id": "38df43af7d05c1e4eb8bfb95edc3ce12353491bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1095, "license_type": "no_license", "max_line_length": 77, "num_lines": 41, "path": "/sc/se/urls.py", "repo_name": "peterlebrun/sc", "src_encoding": "UTF-8", "text": "\"\"\"se URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom . import views\n\nurlpatterns = [\n # Home page\n url(r'^$',\n views.home,\n name='home'\n ),\n\n url(r'^multi-prompt/$',\n views.multi_prompt,\n name='multi_promt'\n ),\n\n url(r'^respond-multi/$',\n views.respond_multi,\n name='respond_multi',\n ),\n\n # Endpoint to create a new response\n url(r'^write-response/$',\n views.write_response,\n name='write_response'\n ),\n]\n" }, { "alpha_fraction": 0.6277742385864258, "alphanum_fraction": 0.6284083724021912, "avg_line_length": 25.72881317138672, "blob_id": "f5a64cc036f6dc76ba9f82677a93eff0868545ac", "content_id": "aab087374bb50506f246970792708d5a4c627317", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1577, "license_type": "no_license", "max_line_length": 71, "num_lines": 59, "path": "/sc/se/views.py", "repo_name": "peterlebrun/sc", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import Prompt, Response\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport datetime\n\n# Create your views here.\n\ndef home(request):\n context = {\n 'prompt': Prompt.objects.filter().order_by('?').first(),\n }\n\n return render(request, 'se/index.html', context)\n\n@csrf_exempt\ndef write_response(request):\n context = { 'success': True }\n\n r = Response.objects.create(\n content = request.POST['response_content'],\n prompt = Prompt.objects.get(id = request.POST['prompt_id']),\n date = datetime.datetime.now()\n )\n\n r.save()\n\n if request.POST['new_prompt_id']:\n p = Prompt.objects.get(id = request.POST['new_prompt_id'])\n context['prompt_content'] = p.content\n context['prompt_id'] = p.id\n\n return JsonResponse(context)\n\ndef multi_prompt(request):\n return render(request, 'se/multi_prompt.html')\n\ndef respond_multi(request):\n prompts = [s.split() for s in request.POST['prompts'].splitlines()]\n\n prompt_ids = []\n\n for prompt in prompts:\n p = Prompt.objects.create(\n content = prompt,\n date = datetime.datetime.now()\n )\n p.save()\n prompt_ids.append(p.id)\n\n initial_prompt = Prompt.objects.get(id = prompt_ids[0])\n\n context = {\n 'prompt_ids' : prompt_ids,\n 'initial_prompt_id' : initial_prompt.id,\n 'initial_prompt_content' : initial_prompt.content,\n }\n\n return render(request, 'se/respond_multi.html', context)\n" }, { "alpha_fraction": 0.7170923352241516, "alphanum_fraction": 0.7170923352241516, "avg_line_length": 27.27777862548828, "blob_id": "c694f51601d9f330da4c2390f5d60dc056066d36", "content_id": "45796a2cb3567baf80f20f72b1192294d0c6779c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 509, "license_type": "no_license", "max_line_length": 58, "num_lines": 18, "path": "/sc/se/models.py", "repo_name": "peterlebrun/sc", "src_encoding": "UTF-8", "text": "from django.db import models\nimport datetime\n\n# Create your models here.\n\nclass Pillar(models.Model):\n content = models.TextField()\n\nclass Prompt(models.Model):\n content = models.TextField()\n pillar = models.ForeignKey(Pillar, null=True)\n week = models.IntegerField(default=None, null=True)\n date = models.DateTimeField(default=None)\n\nclass Response(models.Model):\n content = models.TextField()\n prompt = models.ForeignKey(Prompt)\n date = models.DateTimeField(default=None)\n" }, { "alpha_fraction": 0.5540362000465393, "alphanum_fraction": 0.5779265761375427, "avg_line_length": 90.94219970703125, "blob_id": "a772d7424a753366541d7bf887f9121ee14f546c", "content_id": "1a703330a369e90f08c4d09ae017129e8596eddf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31812, "license_type": "no_license", "max_line_length": 165, "num_lines": 346, "path": "/sc/populate_prompts.py", "repo_name": "peterlebrun/sc", "src_encoding": "UTF-8", "text": "import os, sys\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"sc.settings\")\n\nfrom se.models import Pillar, Prompt\nimport datetime\n\ndef create_pillars():\n pillars = [\n \"Living Consciously\",\n \"Self-Acceptance\",\n \"Self-Responsibility\",\n \"Self-Assertiveness\",\n \"Living Purposefully\",\n \"Personal Integrity\",\n \"31 Week Program\",\n ]\n\n for pillar in pillars:\n p = Pillar.objects.create(content = pillar)\n p.save()\n print(str(p.id) + \": \" + p.content)\n\ndef create_prompts():\n prompts = [\n #{ 'pillar': , 'week': , 'content': '', },\n { 'pillar': 1, 'week': 1, 'content': 'Living consciously to me means', },\n { 'pillar': 1, 'week': 1, 'content': 'If I bring 5 percent more awareness to my activities today,', },\n { 'pillar': 1, 'week': 1, 'content': 'If I pay more attention to how I deal with people today,', },\n { 'pillar': 1, 'week': 1, 'content': 'If I bring 5 percent more awareness to my most important relationships,', },\n { 'pillar': 1, 'week': 1, 'content': 'When I reflect on how I would feel if I lived more consciously, ', },\n { 'pillar': 1, 'week': 1, 'content': 'When I reflect on what happens when I bring 5 percent more awareness to my activities, ', },\n { 'pillar': 1, 'week': 1, 'content': 'When I reflect on what happens when I pay more attention to how I deal with people, ', },\n { 'pillar': 1, 'week': 1, 'content': 'When I reflect on what happens when I bring 5 percent more awareness to my most important relationships, ', },\n { 'pillar': 1, 'week': 2, 'content': 'If I bring 5 percent more awareness to when I am mentally active and when I am mentally passive, I might see that ', },\n { 'pillar': 1, 'week': 2, 'content': 'If I bring 5 percent more awareness to my relationship with my employees, ', },\n { 'pillar': 1, 'week': 2, 'content': 'If I bring 5 percent more awareness to my insecurities, ', },\n { 'pillar': 1, 'week': 2, 'content': 'If I bring 5 percent more awareness to my depression, ', },\n { 'pillar': 1, 'week': 3, 'content': 'If I bring 5 percent more awareness to my anxiety, ', },\n { 'pillar': 1, 'week': 3, 'content': 'If I bring 5 percent more awareness to my concern about my security, ', },\n { 'pillar': 1, 'week': 3, 'content': 'If I bring 5 percent more awareness to my security, ', },\n { 'pillar': 1, 'week': 3, 'content': 'If I bring 5 percent more awareness to my impulses to avoid unpleasant facts, ', },\n { 'pillar': 1, 'week': 4, 'content': 'If I bring 5 percent more awareness to my needs and wants, ', },\n { 'pillar': 1, 'week': 4, 'content': 'If I bring 5 percent more awareness to my deepest values and goals, ', },\n { 'pillar': 1, 'week': 4, 'content': 'If I bring 5 percent more awareness to my emotions, ', },\n { 'pillar': 1, 'week': 4, 'content': 'If I bring 5 percent more awareness to my priorities, ', },\n { 'pillar': 1, 'week': 5, 'content': 'If I bring 5 percent more awareness to how I sometimes stand in my own way, ', },\n { 'pillar': 1, 'week': 5, 'content': 'If I bring 5 percent more awareness to the outcomes of my actions, ', },\n { 'pillar': 1, 'week': 5, 'content': 'If I bring 5 percent more awareness to how I sometimes make it difficult for people to give me what I want, ', },\n { 'pillar': 1, 'week': 5, 'content': 'If I bring 5 percent more awareness to what my job requires of me, ', },\n { 'pillar': 1, 'week': 6, 'content': 'If I bring 5 percent more awareness to what I know about being an effective manager, ', },\n { 'pillar': 1, 'week': 6, 'content': 'If I bring 5 percent more awareness to what I know about building consensus, ', },\n { 'pillar': 1, 'week': 6, 'content': 'If I bring 5 percent more awareness to what I know about appropriate delegating, ', },\n { 'pillar': 1, 'week': 6, 'content': 'If I bring 5 percent more awareness to my fear of operating more consciously, ', },\n { 'pillar': 1, 'week': 2, 'content': 'If I imagine bringing more consciousness into my life, ', },\n { 'pillar': 1, 'week': 2, 'content': 'The scary thing about being more conscious might be ', },\n { 'pillar': 1, 'week': 7, 'content': 'The hard thing about staying fully conscious is ', },\n { 'pillar': 1, 'week': 7, 'content': 'The good thing about being fully conscious is ', },\n { 'pillar': 1, 'week': 7, 'content': 'If I were to stay more conscious, ', },\n { 'pillar': 1, 'week': 7, 'content': 'If I were to experiment with raising my consciousness 5 percent about ', },\n { 'pillar': 2, 'week': 1, 'content': 'Self-acceptance to me means ', },\n { 'pillar': 2, 'week': 1, 'content': 'If I am more accepting of my body, ', },\n { 'pillar': 2, 'week': 1, 'content': 'When I deny and disown my body, ', },\n { 'pillar': 2, 'week': 1, 'content': 'If I am more accepting of my conflicts, ', },\n { 'pillar': 2, 'week': 1, 'content': 'When I deny and disown my conflicts, ', },\n { 'pillar': 2, 'week': 2, 'content': 'If I am more accepting of my feelings, ', },\n { 'pillar': 2, 'week': 2, 'content': 'When I deny and disown my feelings, ', },\n { 'pillar': 2, 'week': 2, 'content': 'If I am more accepting of my thoughts, ', },\n { 'pillar': 2, 'week': 2, 'content': 'When I deny and disown my thoughts, ', },\n { 'pillar': 2, 'week': 3, 'content': 'If I am more accepting of my actions, ', },\n { 'pillar': 2, 'week': 3, 'content': 'When I deny and disown my actions, ', },\n { 'pillar': 2, 'week': 3, 'content': 'I am becoming aware ', },\n { 'pillar': 2, 'week': 3, 'content': 'If I am willing to be realistic about my assets and shortcomings, ', },\n { 'pillar': 2, 'week': 4, 'content': 'If I am more accepting of my fears, ', },\n { 'pillar': 2, 'week': 4, 'content': 'When I deny and disown my fears, ', },\n { 'pillar': 2, 'week': 4, 'content': 'If I am more accepting of my anger, ', },\n { 'pillar': 2, 'week': 4, 'content': 'When I deny and disown my anger, ', },\n { 'pillar': 2, 'week': 2, 'content': 'If I am more accepting of my sexuality, ', },\n { 'pillar': 2, 'week': 2, 'content': 'When I deny and disown my sexuality, ', },\n { 'pillar': 2, 'week': 5, 'content': 'If I am more accepting of my excitement, ', },\n { 'pillar': 2, 'week': 5, 'content': 'When I deny and disown my excitement, ', },\n { 'pillar': 2, 'week': 5, 'content': 'If I am more accepting of my joy, ', },\n { 'pillar': 2, 'week': 5, 'content': 'When I deny and disown my joy, ', },\n { 'pillar': 2, 'week': 6, 'content': 'If I am willing to see what I see and know what I know, ', },\n { 'pillar': 2, 'week': 6, 'content': 'If I bring a high level of consciousness to my fears, ', },\n { 'pillar': 2, 'week': 6, 'content': 'If I bring a high level of consciousness to my pain, ', },\n { 'pillar': 2, 'week': 6, 'content': 'If I bring a high level of consciousness to my sexuality, ', },\n { 'pillar': 2, 'week': 6, 'content': 'If I bring a high level of consciousness to my excitement, ', },\n { 'pillar': 2, 'week': 6, 'content': 'If I bring a high level of consciousness to my joy, ', },\n { 'pillar': 2, 'week': 7, 'content': 'When I think of the consequences of not accepting myself, ', },\n { 'pillar': 2, 'week': 7, 'content': 'If I accept the fact that what is, is, regardless of whether I admit it, ', },\n { 'pillar': 2, 'week': 7, 'content': 'I am beginning to see that ', },\n { 'pillar': 3, 'week': 1, 'content': 'Self-responsibility to me means ', },\n { 'pillar': 3, 'week': 1, 'content': 'At the thought of being responsible for my own existence, ', },\n { 'pillar': 3, 'week': 1, 'content': 'If I accepted responsibility for my own existence, that would mean ', },\n { 'pillar': 3, 'week': 1, 'content': 'When I avoid responsibility for my own existence, ', },\n { 'pillar': 3, 'week': 2, 'content': 'If I accept 5 percent more responsibility for the attainment of my own goals, ', },\n { 'pillar': 3, 'week': 2, 'content': 'When I avoid responsibility for the attainment of my goals, ', },\n { 'pillar': 3, 'week': 2, 'content': 'If I took more responsibility for the success of my relationships, ', },\n { 'pillar': 3, 'week': 2, 'content': 'Sometimes I keep myself passive by ', },\n { 'pillar': 3, 'week': 3, 'content': 'If I take responsibility for what I do about the messages I received from my mother, ', },\n { 'pillar': 3, 'week': 3, 'content': 'If I take responsibility for what I do about the messages I received from my father, ', },\n { 'pillar': 3, 'week': 3, 'content': 'If I take responsibility for the ideas I accept or reject, ', },\n { 'pillar': 3, 'week': 3, 'content': 'If I bring greater awareness to the ideas that motivate me, ', },\n { 'pillar': 3, 'week': 4, 'content': 'If I accept 5 percent more responsibilty for my personal happiness, ', },\n { 'pillar': 3, 'week': 4, 'content': 'If I avoid responsibility for my personal happiness, ', },\n { 'pillar': 3, 'week': 4, 'content': 'If I accept 5 percent more responsibility for my choice of companions, ', },\n { 'pillar': 3, 'week': 4, 'content': 'When I avoid responsibility for my choice of companions, ', },\n { 'pillar': 3, 'week': 5, 'content': 'If I accept 5 percent more responsibility for the words that come out of my mouth, ', },\n { 'pillar': 3, 'week': 5, 'content': 'When I avoid responsibilty for the words that come out of my mouth, ', },\n { 'pillar': 3, 'week': 5, 'content': 'If I bring greater awareness to the things I tell myself, ', },\n { 'pillar': 3, 'week': 5, 'content': 'If I take responsibility for the things I tell myself, ', },\n { 'pillar': 3, 'week': 6, 'content': 'I make myself feel helpless when I ', },\n { 'pillar': 3, 'week': 6, 'content': 'I make myself feel depress when I ', },\n { 'pillar': 3, 'week': 6, 'content': 'I make myself anxious when I ', },\n { 'pillar': 3, 'week': 6, 'content': 'If I take responsibilty for making myself helpless, ', },\n { 'pillar': 3, 'week': 6, 'content': 'If I take responsibilty for making myself depressed, ', },\n { 'pillar': 3, 'week': 6, 'content': 'If I take responsibilty for making myself anxious, ', },\n { 'pillar': 3, 'week': 7, 'content': 'When I am ready to understand what I have been writing, ', },\n { 'pillar': 3, 'week': 7, 'content': 'It is not easy for me to admit that ', },\n { 'pillar': 3, 'week': 7, 'content': 'If I take responsibility for my present standard of living, ', },\n { 'pillar': 3, 'week': 8, 'content': 'I feel most self-responsible when I ', },\n { 'pillar': 3, 'week': 8, 'content': 'I feel least self-responsible when I ', },\n { 'pillar': 3, 'week': 8, 'content': 'If I am not here on earth to live up to anyone\\'s expectations, ', },\n { 'pillar': 3, 'week': 8, 'content': 'If my life belongs to me, ', },\n { 'pillar': 3, 'week': 9, 'content': 'If I give up the lie of being unable to change, ', },\n { 'pillar': 3, 'week': 9, 'content': 'If I take responsibility for what I make of my life from this point on, ', },\n { 'pillar': 3, 'week': 9, 'content': 'If no one is coming to rescue me, ', },\n { 'pillar': 3, 'week': 9, 'content': 'I am becoming aware ', },\n { 'pillar': 4, 'week': 1, 'content': 'Self-assertiveness to me means ', },\n { 'pillar': 4, 'week': 1, 'content': 'If I lived 5 percent more self-assertively today, ', },\n { 'pillar': 4, 'week': 1, 'content': 'If someone had told me my wants were important, ', },\n { 'pillar': 4, 'week': 1, 'content': 'If I had the courage to treat my wants as important, ', },\n { 'pillar': 4, 'week': 2, 'content': 'If I brought more awareness to my deepest needs and wants, ', },\n { 'pillar': 4, 'week': 2, 'content': 'When I ignore my deepest yearnings, ', },\n { 'pillar': 4, 'week': 2, 'content': 'If I were willing to say yes when I want to say yes and no when I want to say no, ', },\n { 'pillar': 4, 'week': 2, 'content': 'If I were willing to voice my thoughts and opinions more often, ', },\n { 'pillar': 4, 'week': 3, 'content': 'When I suppress my thoughts and opinions, ', },\n { 'pillar': 4, 'week': 3, 'content': 'If I am willing to ask for what I want, ', },\n { 'pillar': 4, 'week': 3, 'content': 'When I remain silent about what I want, ', },\n { 'pillar': 4, 'week': 4, 'content': 'If I am willing to let people hear the music inside me, ', },\n { 'pillar': 4, 'week': 4, 'content': 'If I am willing to let myself hear the music inside me, ', },\n { 'pillar': 4, 'week': 4, 'content': 'If I am to express 5 percent more of myself today, ', },\n { 'pillar': 4, 'week': 4, 'content': 'When I hide who I really am, ', },\n { 'pillar': 4, 'week': 4, 'content': 'If I want to live more completely, ', },\n { 'pillar': 5, 'week': 1, 'content': 'Living purposefully to me means ', },\n { 'pillar': 5, 'week': 1, 'content': 'If I bring 5 percent more purposefulness to my life today, ', },\n { 'pillar': 5, 'week': 1, 'content': 'If I operate with 5 percent more purposefulness at work, ', },\n { 'pillar': 5, 'week': 2, 'content': 'If I am 5 percent more purposeful in my communications, ', },\n { 'pillar': 5, 'week': 2, 'content': 'If I bring 5 percent more purposefulness to my relationships at work, ', },\n { 'pillar': 5, 'week': 2, 'content': 'If I operate 5 percent more purposefully in my intimate relationships, ', },\n { 'pillar': 5, 'week': 3, 'content': 'If I operate 5 percent more purposefully with my family, ', },\n { 'pillar': 5, 'week': 3, 'content': 'If I operate 5 percent more purposefully with my friends, ', },\n { 'pillar': 5, 'week': 4, 'content': 'If I am 5 percent more purposeful about my deepest yearnings, ', },\n { 'pillar': 5, 'week': 4, 'content': 'If I am 5 percent more purposeful about taking care of my needs, ', },\n { 'pillar': 5, 'week': 4, 'content': 'If I took more responsibility for fulfulling my wants, ', },\n { 'pillar': 6, 'week': 1, 'content': 'If I bring 5 percent more integrity into my life, ', },\n { 'pillar': 6, 'week': 1, 'content': 'At the thought of going against my parents\\' values, ', },\n { 'pillar': 6, 'week': 1, 'content': 'If I were to think for myself about the values I want to live by, ', },\n { 'pillar': 6, 'week': 1, 'content': 'Integrity to me means ', },\n { 'pillar': 6, 'week': 2, 'content': 'If I think about the areas where I find it difficult to practice full integrity, ', },\n { 'pillar': 6, 'week': 2, 'content': 'If I bring a higher level of consciousness to the areas where I find it difficult to practice full integrity, ', },\n { 'pillar': 6, 'week': 2, 'content': 'If I bring 5 percent more integrity into my life, ', },\n { 'pillar': 6, 'week': 2, 'content': 'If I bring 5 percent more integrity into my work, ', },\n { 'pillar': 6, 'week': 3, 'content': 'If I bring 5 percent more integrity into my relationships, ', },\n { 'pillar': 6, 'week': 3, 'content': 'If I remain loyal to the values I truly believe are right, ', },\n { 'pillar': 6, 'week': 3, 'content': 'If I refuse to live by values I do not respect, ', },\n { 'pillar': 6, 'week': 3, 'content': 'If I treat my self-esteem as a high priority, ', },\n { 'content': 'When my mother saw me making a mistake, ', },\n { 'content': 'When my father saw me making a mistake, ', },\n { 'content': 'When I catch myself making a mistake, ', },\n { 'content': 'If someone had told me it\\'s alright to make mistakes, ', },\n { 'content': 'What I hear myself saying is ', },\n { 'content': 'If I had the courage to allow myself mistakes, ', },\n { 'content': 'If I were more compassionate about my mistakes, ', },\n { 'content': 'As I learn a better attitude toward making mistakes, ', },\n { 'pillar': 7, 'week': 1, 'content': 'If I bring more awareness to my life today, ', },\n { 'pillar': 7, 'week': 1, 'content': 'If I take more responsibility for my choices and actions today, ', },\n { 'pillar': 7, 'week': 1, 'content': 'If I pay more attention to how I deal with people today, ', },\n { 'pillar': 7, 'week': 1, 'content': 'If I boost my energy level by 5 percent today, ', },\n { 'pillar': 7, 'week': 2, 'content': 'If I bring 5 percent more awareness to my most important relationships, ', },\n { 'pillar': 7, 'week': 2, 'content': 'If I bring 5 percent more awareness to my insecurities, ', },\n { 'pillar': 7, 'week': 2, 'content': 'If I bring 5 percent more awareness to my deepest needs and wants, ', },\n { 'pillar': 7, 'week': 2, 'content': 'If I bring 5 percent more awareness to my emotions, ', },\n { 'pillar': 7, 'week': 3, 'content': 'If I treat listening as a creative act, ', },\n { 'pillar': 7, 'week': 3, 'content': 'If I notice how people are affected by the quality of my listening, ', },\n { 'pillar': 7, 'week': 3, 'content': 'If I bring more awareness to my dealings with people today, ', },\n { 'pillar': 7, 'week': 3, 'content': 'If I commit to dealing with people fairly and benevolently, ', },\n { 'pillar': 7, 'week': 4, 'content': 'If I bring a higher level of self-esteem to my activities today, ', },\n { 'pillar': 7, 'week': 4, 'content': 'If I bring a higher level of self-esteem to my dealings with people today, ', },\n { 'pillar': 7, 'week': 4, 'content': 'If I am 5 percent more self accepting today, ', },\n { 'pillar': 7, 'week': 4, 'content': 'If I am self accepting even when I make mistakes, ', },\n { 'pillar': 7, 'week': 4, 'content': 'If I am self accepting even when I feel confused and overwhelmed, ', },\n { 'pillar': 7, 'week': 5, 'content': 'If I am more accepting of my own body, ', },\n { 'pillar': 7, 'week': 5, 'content': 'If I deny and disown my body, ', },\n { 'pillar': 7, 'week': 5, 'content': 'If I deny or disown my conflicts, ', },\n { 'pillar': 7, 'week': 5, 'content': 'If I am more accepting of all the parts of me, ', },\n { 'pillar': 7, 'week': 6, 'content': 'If I wanted to raise my self-esteem today, I could ', },\n { 'pillar': 7, 'week': 6, 'content': 'If I am more acceptin of my feelings, ', },\n { 'pillar': 7, 'week': 6, 'content': 'If I deny and disown my feelings, ', },\n { 'pillar': 7, 'week': 6, 'content': 'If I am more accepting of my thoughts, ', },\n { 'pillar': 7, 'week': 6, 'content': 'If I deny and disown my thoughts, ', },\n { 'pillar': 7, 'week': 7, 'content': 'If I am more accepting of my fears, ', },\n { 'pillar': 7, 'week': 7, 'content': 'If I deny and disown my fears, ', },\n { 'pillar': 7, 'week': 7, 'content': 'If I were more accepting of my pain, ', },\n { 'pillar': 7, 'week': 7, 'content': 'If I deny and disown my pain, ', },\n { 'pillar': 7, 'week': 8, 'content': 'If I am more accepting of my anger, ', },\n { 'pillar': 7, 'week': 8, 'content': 'If I deny and disown my anger, ', },\n { 'pillar': 7, 'week': 8, 'content': 'If I am more accepting of my sexuality, ', },\n { 'pillar': 7, 'week': 8, 'content': 'If I deny and disown my sexuality, ', },\n { 'pillar': 7, 'week': 9, 'content': 'If I am more accepting of my excitement, ', },\n { 'pillar': 7, 'week': 9, 'content': 'If I deny and disown my excitement, ', },\n { 'pillar': 7, 'week': 9, 'content': 'If I am more accepting of my intelligence, ', },\n { 'pillar': 7, 'week': 9, 'content': 'If I deny and disown my intelligence, ', },\n { 'pillar': 7, 'week': 10, 'content': 'If I am more accepting of my joy, ', },\n { 'pillar': 7, 'week': 10, 'content': 'If I deny and disown my joy, ', },\n { 'pillar': 7, 'week': 10, 'content': 'If I bring more awareness to all parts of me, ', },\n { 'pillar': 7, 'week': 10, 'content': 'As I learn to accept all of who I am, ', },\n { 'pillar': 7, 'week': 11, 'content': 'Self-responsibility to me means ', },\n { 'pillar': 7, 'week': 11, 'content': 'If I take 5 percent more responsibility for my life and well-being, ', },\n { 'pillar': 7, 'week': 11, 'content': 'If I avoid responsibility for my life and well-being, ', },\n { 'pillar': 7, 'week': 11, 'content': 'If I take 5 percent more responsibility for the attainment of my goals, ', },\n { 'pillar': 7, 'week': 11, 'content': 'If I avoid responsibility for the attainment of my goals, ', },\n { 'pillar': 7, 'week': 12,'content': 'If I take 5 percent more responsibility for the success of my relationships, ', },\n { 'pillar': 7, 'week': 12, 'content': 'Sometimes I keep myself passive when I ', },\n { 'pillar': 7, 'week': 12, 'content': 'Sometimes I make myself helples when I ', },\n { 'pillar': 7, 'week': 12, 'content': 'I am becoming aware ', },\n { 'pillar': 7, 'week': 13, 'content': 'If I take 5 percent more responsibility for my standard of living, ', },\n { 'pillar': 7, 'week': 13, 'content': 'If I take 5 percent more responsibility for my choice of companions, ', },\n { 'pillar': 7, 'week': 13, 'content': 'If I take 5 percent more responsibility for my personal happiness, ', },\n { 'pillar': 7, 'week': 13, 'content': 'If I take 5 percent more responsibility for the level of my self-esteem, ', },\n { 'pillar': 7, 'week': 14, 'content': 'Self-assertiveness to me means ', },\n { 'pillar': 7, 'week': 14, 'content': 'If I lived 5 percent more assertively today, ', },\n { 'pillar': 7, 'week': 14, 'content': 'If I treated my thoughts and feelings with respect today, ', },\n { 'pillar': 7, 'week': 14, 'content': 'If I treat my wants with respect today, ', },\n { 'pillar': 7, 'week': 15, 'content': 'If, when I was young, someone told me that my thoughts really mattered, ', },\n { 'pillar': 7, 'week': 15, 'content': 'If, when I was young, I had been taught to honor my own life, ', },\n { 'pillar': 7, 'week': 15, 'content': 'If I treat my life as unimportant, ', },\n { 'pillar': 7, 'week': 15, 'content': 'If I were willing to say yes when I mean yes and no when I mean no, ', },\n { 'pillar': 7, 'week': 15, 'content': 'If I were willing to let people hear the music inside of me, ', },\n { 'pillar': 7, 'week': 15, 'content': 'If I were to express 5 percent more of who I am, ', },\n { 'pillar': 7, 'week': 16, 'content': 'Living purposefully to me means ', },\n { 'pillar': 7, 'week': 16, 'content': 'If I bring 5 percent more purposefullness into my life, ', },\n { 'pillar': 7, 'week': 16, 'content': 'If I operate 5 percent more purposefully at work, ', },\n { 'pillar': 7, 'week': 16, 'content': 'If I operate 5 percent more purposefully in my relationships, ', },\n { 'pillar': 7, 'week': 16, 'content': 'If I operate 5 percent more purposefully with my family, ', },\n { 'pillar': 7, 'week': 17, 'content': 'If I were 5 percent more purposeful about my deepest yearnings, ', },\n { 'pillar': 7, 'week': 17, 'content': 'If I take more responsibility for fulfilling my wants, ', },\n { 'pillar': 7, 'week': 17, 'content': 'If I make my happiness a conscious goal, ', },\n { 'pillar': 7, 'week': 18, 'content': 'Integrity to me means ', },\n { 'pillar': 7, 'week': 18, 'content': 'If I look at instances where I find full integrity difficult, ', },\n { 'pillar': 7, 'week': 18, 'content': 'If I bring 5 percent more integrity into my life, ', },\n { 'pillar': 7, 'week': 18, 'content': 'If I bring 5 percent more integrity into my work, ', },\n { 'pillar': 7, 'week': 19, 'content': 'If I bring 5 percent more integrity into my relationships, ', },\n { 'pillar': 7, 'week': 19, 'content': 'If I remain loyal to the values I believe are right, ', },\n { 'pillar': 7, 'week': 19, 'content': 'If I refuse to live by values I do not respect, ', },\n { 'pillar': 7, 'week': 19, 'content': 'If I treat my self respect as high priority, ', },\n { 'pillar': 7, 'week': 20, 'content': 'If the child in me could speak, he would say ', },\n { 'pillar': 7, 'week': 20, 'content': 'If the teenager I once was still exists inside of me, ', },\n { 'pillar': 7, 'week': 20, 'content': 'If my teenage self could speak he would say ', },\n { 'pillar': 7, 'week': 20, 'content': 'At the thought of reaching back to my child-self, ', },\n { 'pillar': 7, 'week': 20, 'content': 'At the thought of reaching back to my teenage-self ', },\n { 'pillar': 7, 'week': 20, 'content': 'If I could make friends with my younger selves, ', },\n { 'pillar': 7, 'week': 21, 'content': 'If my child-self felt accepted by me, ', },\n { 'pillar': 7, 'week': 21, 'content': 'If my teenage-self felt I was on his side, ', },\n { 'pillar': 7, 'week': 21, 'content': 'If my younger selves felt I had compassion for their struggles, ', },\n { 'pillar': 7, 'week': 21, 'content': 'If I could hold my child-self in my arms, ', },\n { 'pillar': 7, 'week': 21, 'content': 'If I could hold my teenage-self in my arms, ', },\n { 'pillar': 7, 'week': 21, 'content': 'If I had the courage and compassion to embrace and love my younger selves, ', },\n { 'pillar': 7, 'week': 22, 'content': 'Sometimes my child-self feels rejected by me when I ', },\n { 'pillar': 7, 'week': 22, 'content': 'Sometimes my teenage-self feels rejected by me when I ', },\n { 'pillar': 7, 'week': 22, 'content': 'One of the things my child-self needs from me and rarely gets is ', },\n { 'pillar': 7, 'week': 22, 'content': 'One of the things my teenage-self needs from me and hasn\\'t gotten is ', },\n { 'pillar': 7, 'week': 22, 'content': 'One of the ways my child-self gets back at me for rejecting him is ', },\n { 'pillar': 7, 'week': 22, 'content': 'One of the ways my teenage-self gets back at me for rejecting him is ', },\n { 'pillar': 7, 'week': 23, 'content': 'At the thought of giving my child-self what he needs from me ', },\n { 'pillar': 7, 'week': 23, 'content': 'At the thought of giving my teenage-self what he needs from me ', },\n { 'pillar': 7, 'week': 23, 'content': 'If my child-self and I were to fall in love, ', },\n { 'pillar': 7, 'week': 23, 'content': 'If my teenage-self and I were to fall in love, ', },\n { 'pillar': 7, 'week': 24, 'content': 'If I accept that my child-self may need time to learn to trust me, ', },\n { 'pillar': 7, 'week': 24, 'content': 'If I accept that my teenage-self may need time to learn to trust me, ', },\n { 'pillar': 7, 'week': 24, 'content': 'As I come to understand that my child-self and my teenage-self are both part of me, ', },\n { 'pillar': 7, 'week': 24, 'content': 'I am becoming aware ', },\n { 'pillar': 7, 'week': 25, 'content': 'Sometimes when I am afraid I ', },\n { 'pillar': 7, 'week': 25, 'content': 'Sometimes when I am hurt I ', },\n { 'pillar': 7, 'week': 25, 'content': 'Sometimes when I am angry I ', },\n { 'pillar': 7, 'week': 25, 'content': 'An effective way to handle fear might be to ', },\n { 'pillar': 7, 'week': 25, 'content': 'An effective way to handle hurt might be to ', },\n { 'pillar': 7, 'week': 25, 'content': 'An effective way to handly anger might be to ', },\n { 'pillar': 7, 'week': 26, 'content': 'Sometimes when I am excited, I ', },\n { 'pillar': 7, 'week': 26, 'content': 'Sometimes when I am turned on sexually, I ', },\n { 'pillar': 7, 'week': 26, 'content': 'Sometimes when I experience strong feelings, I ', },\n { 'pillar': 7, 'week': 26, 'content': 'If I make friends with my excitement, ', },\n { 'pillar': 7, 'week': 26, 'content': 'If I make friends with my sexuality, ', },\n { 'pillar': 7, 'week': 26, 'content': 'As I grow more comfortable with the full range of my emotions, ', },\n { 'pillar': 7, 'week': 27, 'content': 'If I think about becoming better friends with my child-self, ', },\n { 'pillar': 7, 'week': 27, 'content': 'If I think about becoming better friends with my teenage-self, ', },\n { 'pillar': 7, 'week': 27, 'content': 'As my younger selves become more comfortable with me, ', },\n { 'pillar': 7, 'week': 27, 'content': 'As I create a safe space for my child-self, ', },\n { 'pillar': 7, 'week': 27, 'content': 'As I create a safe space for my teenage-self, ', },\n { 'pillar': 7, 'week': 28, 'content': 'Mother gave me a view of myself as ', },\n { 'pillar': 7, 'week': 28, 'content': 'Father gave me a view of myself as ', },\n { 'pillar': 7, 'week': 28, 'content': 'Mother speaks through my voice when I tell myself ', },\n { 'pillar': 7, 'week': 28, 'content': 'Father speaks through my voice when I tell myself ', },\n { 'pillar': 7, 'week': 29, 'content': 'If I bring 5 percent more awareness to my relationship with my mother, ', },\n { 'pillar': 7, 'week': 29, 'content': 'If I bring 5 percent more awareness to my relationship with my father, ', },\n { 'pillar': 7, 'week': 29, 'content': 'If I look at my mother and father realistically, ', },\n { 'pillar': 7, 'week': 29, 'content': 'If I reflect on the level of awareness I bring to my relationship with my mother, ', },\n { 'pillar': 7, 'week': 29, 'content': 'If I reflect on the level of awareness I bring to my relationship with my father, ', },\n { 'pillar': 7, 'week': 30, 'content': 'At the thought of being free of Mother psychologically, ', },\n { 'pillar': 7, 'week': 30, 'content': 'At the thought of being free of Father psychologically, ', },\n { 'pillar': 7, 'week': 30, 'content': 'At the thought of belonging fully to myself, ', },\n { 'pillar': 7, 'week': 30, 'content': 'If my life really does belong to me, ', },\n { 'pillar': 7, 'week': 30, 'content': 'If I really am capable of independent survival, ', },\n { 'pillar': 7, 'week': 31, 'content': 'If I bring 5 percent more awareness to my life, ', },\n { 'pillar': 7, 'week': 31, 'content': 'If I am 5 percent more self-accepting, ', },\n { 'pillar': 7, 'week': 31, 'content': 'If I bring 5 percent more self-responsibility into my life, ', },\n { 'pillar': 7, 'week': 31, 'content': 'If I operate 5 percent more self-assertively, ', },\n { 'pillar': 7, 'week': 31, 'content': 'If I life my life 5 percent more purposefully, ', },\n { 'pillar': 7, 'week': 31, 'content': 'If I bring 5 percent more integrity into my life, ', },\n { 'pillar': 7, 'week': 31, 'content': 'If I breathe deeply and allow myself to experience what self-esteem feels like, ', },\n ]\n\n for prompt in prompts:\n pillar = None\n week = None\n\n if 'pillar' in prompt:\n pillar = Pillar.objects.get(id = prompt['pillar'])\n\n if 'week' in prompt:\n week = prompt['week']\n\n p = Prompt.objects.create(\n content = prompt['content'],\n pillar = pillar,\n week = week,\n date = datetime.datetime.now()\n )\n p.save()\n\nif __name__ == '__main__':\n if len(Pillar.objects.all()) < 1:\n create_pillars()\n\n if len(Prompt.objects.all()) < 1:\n create_prompts()\n" } ]
4
aryner/numericalAnalysis
https://github.com/aryner/numericalAnalysis
050ec82ce55aaed34300d8c03bbf263d9d98cd20
1d7a0fd335b569ea68d5bd4499cc65d0c09dd5af
889202c406aa5c8df7295daa63ec24f15ee864fd
refs/heads/master
2020-05-28T07:45:03.667575
2014-05-23T22:28:19
2014-05-23T22:28:19
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.37288135290145874, "alphanum_fraction": 0.5338982939720154, "avg_line_length": 18.5, "blob_id": "0e8959b5306854a1f9676fe57621a548ea749708", "content_id": "2056554517f27ea1ba06b7e3694c7d2611996698", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 118, "license_type": "no_license", "max_line_length": 48, "num_lines": 6, "path": "/homework1/thing.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from gauss import *\n\nmatrix = [[1,-1,4,29],[3,-2,-1,-6],[2,-5,6,-55]]\n\nA = gaussSeidel(matrix, [0,0,0], 0.1)\nshow(A)\n\n" }, { "alpha_fraction": 0.6063551306724548, "alphanum_fraction": 0.6340187191963196, "avg_line_length": 16.019107818603516, "blob_id": "191460ec851d99a42a7ef6dfd029b77f3d41729a", "content_id": "d8dc461c3c34894131a002cd1b37de8b422a0fb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2675, "license_type": "no_license", "max_line_length": 81, "num_lines": 157, "path": "/hw1/matrixFunctions9.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "\"\"\"\nmatrixFunctions.py\n\n2/6/14 bic M400\n\nThis is a skeleton for the matrix part of first Math 400 assignment\n\n\"\"\"\n\n####### START Administrivia \nm400group = 9 # change this to your group number\n\nm400names = ['alex ryner', 'jared halpert', 'michael sims', 'kason soohoo'] # change this for your names\n\ndef printNames():\n print(\"matrixFunctions.py for group %s:\"%(m400group)),\n for name in m400names:\n print(\"%s, \"%(name)),\n print\n\nprintNames()\n\n####### END Administrivia\n\n\n\"\"\"\nVector Functions\n\ncopy these three functions from your finished vectorFunctions.py file\n\n\"\"\"\n\ndef scalarMult(s,V):\n \"return vector sV\"\n return [k*s for k in V] \n\n\ndef addVectors(S,T):\n \"return S+T\"\n result = range(len(S))\n for i in range(len(S)):\n result[i] = S[i] + T[i]\n return result\n\n\ndef dot(S,T):\n \"return dot product of two vectors\"\n temp = range(len(S))\n for i in range(len(S)):\n temp[i] = S[i] * T[i]\n result = 0\n for i in range(len(S)):\n result += temp[i]\n return result\n\n\n\"\"\"\n\nMatrix Functions\n\n\"\"\"\n\n\n\ndef showMatrix(mat):\n \"Print out matrix\"\n for row in mat:\n print(row)\n\n\ndef rows(mat):\n \"return number of rows\"\n return(len(mat))\n\ndef cols(mat):\n \"return number of cols\"\n return(len(mat[0]))\n \n\n#### Functions for you to finish\n\ndef getCol(mat, col):\n \"return column col from matrix mat\"\n result = range(len(mat))\n for i in result:\n result[i] = mat[i][col]\n return result\n\ndef transpose(mat):\n \"return transpose of mat\"\n result = range(len(mat[0]))\n for i in result:\n result[i] = getCol(mat,i)\n return result\n\ndef getRow(mat, row):\n \"return row row from matrix mat\"\n return mat[row]\n\ndef scalarMultMatrix(a,mat):\n \"multiply a scalar times a matrix\"\n return [scalarMult(a,k) for k in mat]\n\n\ndef addMatrices(A,B):\n \"add two matrices\"\n result = range(len(A))\n for i in result:\n result[i] = addVectors(A[i],B[i])\n return result\n\n\ndef multiplyMat(mat1,mat2):\n \"multiply two matrices\"\n result = range(len(mat1))\n for i in result:\n result[i] = [dot(getRow(mat1,i),getCol(mat2,k)) for k in range(len(mat2[0]))]\n return result\n\n\n###### Initial tests\n\nA= [[4,-2,1,11],\n [-2,4,-2,-16],\n [1,-2,4,17]]\n\nAe= [[4,-2,1],\n [-2,4,-2],\n [1,-2,4]]\n\n\nBv=[11,-16,17]\n\nBm=[[11,-16,17]]\n\nC=[2,3,5]\n\nprint(\"running matrixFunction.py file\")\n\ndef testMatrix():\n print(\"A\")\n showMatrix(A)\n print(\"Bm\")\n showMatrix(Bm)\n print(\"Ae\")\n showMatrix(Ae)\n print(\"multiplyMat(Ae,A)\")\n showMatrix(multiplyMat(Ae,A))\n print(\"scalarMultMatrix(2,A))\")\n showMatrix(scalarMultMatrix(2,A))\n print(\"addMatrices(A,A)\")\n showMatrix(addMatrices(A,A))\n print(\"transpose(A)\")\n showMatrix(transpose(A))\n\n### uncomment next line to run initial tests \ntestMatrix()\n \n" }, { "alpha_fraction": 0.5742971897125244, "alphanum_fraction": 0.6414993405342102, "avg_line_length": 23.728477478027344, "blob_id": "462cfae62ae561a2f2eb99fd213e3be8eff7816f", "content_id": "80dca934eca46216db0343438fa0dc42deccbc02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3735, "license_type": "no_license", "max_line_length": 90, "num_lines": 151, "path": "/homework4/prob4.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from newton import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\neqn1 = [[[3,2]],[[-1,2]]]\neqn2 = [[[-1,2]],[['3x',2],[-1,0]]]\n\ndef one(x):\n return (3.*x**2.)**(1./2)\ndef dOne(x):\n return ((3.**(1./2))*x)/((x**2.)**(1./2))\ndef two(x):\n return ((1.+x**2.)/(3.*x))**(1./2)\ndef dTwo(x):\n return -(x**2.+1.)/(2.+(3.**(1./2))*(((1./x)-x)**(1./2))*x**2.)\n\ndef oneMtwo(x):\n return one(x) - two(x)\ndef dOneMdTwo(x):\n return dOne(x) - dTwo(x)\n\nprint '***Solving using the two dimensional version of Newtons method***'\nprint '\\t\\tOur equations are:'\nprint2d(eqn1)\nprint ' = 0'\nprint2d(eqn2)\nprint ' = 0'\nprint\nprint 'The first iteration of Newtons methdo using a guess of [1,1] gives us:'\nX1 = newton2d(eqn1,eqn2, [1,1])\nprint X1\nprint\nprint 'using the infinity norm our error is:'\nprint infinTol([1,1],X1)\nprint '...'\nprint 'Iteration 2:'\nX2 = newton2d(eqn1,eqn2, X1)\nprint X2\nprint 'Error: ', infinTol(X1,X2)\nprint '...'\nprint 'Iteration 3:'\nX3 = newton2d(eqn1,eqn2, X2)\nprint X3\nprint 'Error: ', infinTol(X2,X3)\nprint '...'\nprint 'Iteration 4:'\nX4 = newton2d(eqn1,eqn2, X3)\nprint X4\nprint 'Error: ', infinTol(X3,X4)\nprint '...'\nprint 'Iteration 5:'\nX5 = newton2d(eqn1,eqn2, X4)\nprint X5\nprint 'Error: ', infinTol(X4,X5)\nprint '...'\nprint 'Iteration 6:'\nX6 = newton2d(eqn1,eqn2, X5)\nprint X6\nprint 'Error: ', infinTol(X5,X6)\nprint '...'\nprint 'Iteration 7:'\nX7 = newton2d(eqn1,eqn2, X6)\nprint X7\nprint 'Error: ', infinTol(X6,X7)\nprint '...'\nprint 'Iteration 8:'\nX8 = newton2d(eqn1,eqn2, X7)\nprint X8\nprint 'Error: ', infinTol(X7,X8)\nprint '...'\nprint 'Iteration 9:'\nX9 = newton2d(eqn1,eqn2, X8)\nprint X9\nprint 'Error: ', infinTol(X8,X9)\nprint\nprint '***Solving by using the one dimensional method***'\ny = oneMtwo(1)\nprint 'For this case f(x) is first equation minus the second equation'\nprint 'for the first iterations we will guess the x value is 1, which makes the f(1)= ', y\nx1 = newton(oneMtwo,dOneMdTwo,1)\nprint 'which gives us the x1: ', x1\nprint\nprint 'using the infinity norm our error is:'\nprint singleTol(1,x1)\nprint '...'\nprint 'Iteration 2:'\nprint 'f(x1) = ', oneMtwo(x1)\nx2 = newton(oneMtwo,dOneMdTwo,x1)\nprint 'x2 = ', x2\nprint 'Error: ', singleTol(x1,x2)\nprint '...'\nprint 'Iteration 3:'\nprint 'f(x2) = ', oneMtwo(x2)\nx3 = newton(oneMtwo,dOneMdTwo,x2)\nprint 'x3 = ', x3\nprint 'Error: ', singleTol(x2,x1)\nprint '...'\nprint 'Iteration 4:'\nprint 'f(x3) = ', oneMtwo(x3)\nx4 = newton(oneMtwo,dOneMdTwo,x3)\nprint 'x4 = ', x4\nprint 'Error: ', singleTol(x4,x3)\nprint '...'\nprint 'Iteration 5:'\nprint 'f(x4) = ', oneMtwo(x4)\nx5 = newton(oneMtwo,dOneMdTwo,x4)\nprint 'x5 = ', x5\nprint 'Error: ', singleTol(x5,x4)\nprint '...'\nprint 'Iteration 6:'\nprint 'f(x5) = ', oneMtwo(x5)\nx6 = newton(oneMtwo,dOneMdTwo,x5)\nprint 'x6 = ', x6\nprint 'Error: ', singleTol(x6,x5)\nprint '...'\nprint 'Iteration 7:'\nprint 'f(x6) = ', oneMtwo(x6)\nx7 = newton(oneMtwo,dOneMdTwo,x6)\nprint 'x7 = ', x7\nprint 'Error: ', singleTol(x7,x6)\nprint '...'\nprint 'Iteration 8:'\nprint 'f(x7) = ', oneMtwo(x7)\nx8 = newton(oneMtwo,dOneMdTwo,x7)\nprint 'x8 = ', x8\nprint 'Error: ', singleTol(x8,x7)\nprint '...'\nprint 'Iteration 9:'\nprint 'f(x8) = ', oneMtwo(x8)\nx9 = newton(oneMtwo,dOneMdTwo,x8)\nprint 'x9 = ', x9\nprint 'Error: ', singleTol(x9,x8)\n\nx = generateX(100,0.1,.8)\ny1 = [one(x[i]) for i in range(len(x))]\ny2 = [two(x[i]) for i in range(len(x))]\ny3 = [oneMtwo(x[i]) for i in range(len(x))]\n\nplt.figure(1)\nplt.title('eqn1-eqn2 and the single dimension approximation')\nplt.plot([x9,x9], [-.25,.25])\nplt.plot(x,[0 for i in range(len(x))])\nplt.plot(x,y3)\n\nplt.figure(2)\nplt.title('eqn1 and eqn2 with the two dimensional approximation')\nplt.plot(x,y1)\nplt.plot(x,y2)\nplt.plot([X9[0],X9[0]] , [.8,1])\nplt.plot([X9[0]-.05,X9[0]+.05], [X9[1],X9[1]] )\nplt.show()\n\n" }, { "alpha_fraction": 0.5516039133071899, "alphanum_fraction": 0.6645746231079102, "avg_line_length": 22.883333206176758, "blob_id": "2213d97c531b4c743a3f329b693c50e92f63efbf", "content_id": "956224ba004818cfd0200ee8d788796ff354875a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1434, "license_type": "no_license", "max_line_length": 55, "num_lines": 60, "path": "/homework3/prob2.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from numericalIntegrals import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sinPi(x):\n return np.sin(np.pi*x)\n\ndef eToSomeCrap(x):\n return np.e**((-(x)**2)/2)\n\ndef sinC(x):\n if x == 0:\n return 1\n else:\n return (np.sin(2*np.pi*x))/(2*np.pi*x)\n\nnumPoints = 5050000\nx = generateX(numPoints, 0, 0.5)\ny = [sinPi(x[i]) for i in range(0,numPoints)]\n\none = 1/np.pi\nprint 1/np.pi - trapezoidal(x,y)\nprint 1/np.pi - romberg(0, 0.5, 1675000, sinPi)\nprint 1/np.pi - gaussQuadrature(0, 0.5, sinPi, 4)\nprint \"\"\nplt.figure(1)\nplt.title('a')\nxp1 = generateX(100,0,0.5)\nyp1 = [sinPi(xp1[i]) for i in range(0,100)]\nplt.plot(xp1,yp1,'b')\n\nnumPoints2 = 1500000\nx2 = generateX(numPoints2, 1.,2.)\ny2 = [eToSomeCrap(x2[i]) for i in range(0, numPoints2)]\n\ntwo = 0.3406636214304\nprint two - trapezoidal(x2,y2)\nprint two - romberg(1.,2., 500000, eToSomeCrap)\nprint two - gaussQuadrature(1.,2.,eToSomeCrap, 4)\nprint \"\"\nplt.figure(2)\nplt.title('b')\nxp2 = generateX(100,1.,2.)\nyp2 = [eToSomeCrap(xp2[i]) for i in range(0,100)]\nplt.plot(xp2,yp2,'b')\n\nnumPoints3 = 7000\nx3 = generateX(numPoints3, -1.,1.)\ny3 = [sinC(x3[i]) for i in range(0, numPoints3)]\n\nthree = 0.45141166679014\nprint three - trapezoidal(x3,y3)\nprint three - romberg(-1.,1., 310, sinC)\nprint three - gaussQuadrature(-1.,1., sinC, 9)\nplt.figure(3)\nplt.title('c')\nxp3 = generateX(100,-1.,1.)\nyp3 = [eToSomeCrap(xp3[i]) for i in range(0,100)]\nplt.plot(xp3,yp3,'b')\nplt.show()\n\n" }, { "alpha_fraction": 0.45515695214271545, "alphanum_fraction": 0.49103137850761414, "avg_line_length": 22.46616554260254, "blob_id": "d1ac51d5f3d6e26fb957c593e75d6b55b57974cd", "content_id": "4126673a9beee204dbe371d1cee8c13076f69f2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3122, "license_type": "no_license", "max_line_length": 128, "num_lines": 133, "path": "/homework2/interpolation.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom operator import mul\n\ndef differenceFunction(f, g):\n def func(x):\n return f(x) - g(x)\n return func\n\ndef createLagrange(x, y):\n def lagrange(z):\n L = range(len(x))\n for i in range(len(x)):\n Li = createLi(x,i)\n L[i] = y[i] * Li(z)\n return sum(L)\n return lagrange\n\ndef createLi(xs, i):\n def Li(x):\n prods = [(x-xs[j])/(xs[i]-xs[j]) for j in range(i)] + [(x-xs[j])/(xs[i]-xs[j]) for j in range(i+1, len(xs))]\n return reduce(mul, prods, 1)\n return Li\n\ndef hermite(x, fx, dfx):\n Q = hermiteCoefficients(x, fx, dfx)\n return completeHermite(Q, x)\n\ndef hermiteCoefficients(x, fx, dfx):\n z = range(len(x)*2)\n Q = range(len(z))\n\n for i in range(len(z)):\n Q[i] = range(len(z))\n\n for i in range(len(x)):\n z[i*2] = x[i]\n z[i*2+1] = x[i]\n Q[i*2][0] = fx[i]\n Q[i*2+1][0] = fx[i]\n Q[i*2+1][1] = dfx[i]\n\n for i in range(1,len(x)):\n Q[2*i][1] = (Q[2*i][0] - Q[2*i-1][0]) / (z[2*i] - z[2*i-1])\n\n for i in range(2, len(z)):\n for j in range(2, i+1):\n Q[i][j] = (Q[i][j-1] - Q[i-1][j-1]) / (z[i] - z[i-j])\n\n return [Q[i][i] for i in range(len(z))]\n\ndef completeHermite(Q,xs):\n def func(x):\n H = range(len(Q))\n H[0] = Q[0]\n factors = range(len(xs))\n\n for i in range(len(xs)):\n factors[i] = (x - xs[i])\n \n for i in range(1,len(Q)):\n H[i] = Q[i]\n for j in range(i):\n H[i] = H[i] * factors[j/2]\n return sum(H)\n return func\n\ndef cubicSpline(xs, fx):\n a,b,c,d = cubicSplineUnknowns(xs, fx)\n def func(x):\n for i in range(len(a)-1):\n if x < xs[i+1]:\n return a[i] + b[i]*(x-xs[i]) + c[i]*(x-xs[i])**2 + d[i]*(x-xs[i])**3\n return a[len(xs)-2] + b[len(xs)-2]*(x-xs[len(xs)-2]) + c[len(xs)-2]*(x-xs[len(xs)-2])**2 + d[len(xs)-2]*(x-xs[len(xs)-2])**3\n return func\n\ndef cubicSplineUnknowns(x, fx):\n a = fx\n\n h = range(len(x)-1)\n for i in range(len(x)-1):\n h[i] = x[i+1] - x[i]\n\n alpha = range(len(x)-1)\n for i in range(1, len(x)-1):\n alpha[i] = (3/h[i])*(a[i+1]-a[i]) - (3/h[i-1])*(a[i]-a[i-1])\n\n l = range(len(x))\n u = range(len(x)-1)\n z = range(len(x))\n for i in range(1, len(x)-1):\n l[i] = 2*(x[i+1] - x[i-1]) - h[i-1] * u[i-1]\n u[i] = h[i] / l[i]\n z[i] = (alpha[i] - h[i-1] * z[i-1]) / l[i]\n\n l[len(x)-1] = 1\n z[len(x)-1] = 0\n\n b = range(len(x)-1)\n c = range(len(x))\n d = range(len(x)-1)\n c[len(c)-1] = 0\n L = range(len(x)-1)\n for i in L[::-1]:\n c[i] = z[i] - u[i] * c[i+1]\n b[i] = (a[i+1] - a[i]) / h[i] - h[i]*(c[i+1] + 2*c[i])/3\n d[i] = (c[i+1] - c[i]) / (3*h[i])\n\n return a[:len(x)-1], b, c[:len(x)-1], d\n\ndef linearSpline(xs, fx):\n def func(x):\n yPsi = range(len(fx))\n for i in range(len(fx)):\n yPsi[i] = fx[i] * psi(x, xs, i)\n return sum(yPsi)\n return func\n\ndef psi(x, xs, i):\n if i == 0:\n return theta1((x-xs[0])/(xs[1]-xs[0]))\n if i == len(xs)-1:\n return theta2((x-xs[len(xs)-1])/(xs[len(xs)-1]-xs[len(xs)-2]))\n return theta2((x-xs[i-1])/(xs[i]-xs[i-1])) + theta1((x-xs[i])/(xs[i+1]-xs[i]))\n\ndef theta1(x):\n if x >= 0 and x < 1:\n return 1-x\n return 0\n\ndef theta2(x):\n if x >= 0 and x < 1:\n return x\n return 0\n\n" }, { "alpha_fraction": 0.555717408657074, "alphanum_fraction": 0.6571983695030212, "avg_line_length": 36.78899002075195, "blob_id": "b3585249f685c4583dee2c1c37b36afc95603701", "content_id": "69d8fd60e344dc0011db17d5c776b0e14edce654", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4119, "license_type": "no_license", "max_line_length": 132, "num_lines": 109, "path": "/homework2/prob3.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from interpolation import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nlineX1 = np.arange(-0.025,1.085,0.001)\nlineX2 = np.arange(-0.11,1.15,0.001)\nlineY1 = [0 for i in lineX1]\nlineY2 = [0 for i in lineX2]\n\nx = [0.,1./6,1./3,1./2,7./12,2./3,3./4,5./6,11./12,1.]\nx1 = np.arange(-0.025,1.085,0.001)\nx2 = np.arange(-0.11,1.15,0.001)\n\ndef f(x):\n return 1.6*np.e**(-2*x)*np.sin(3*np.pi*x)\ndef df(x):\n return np.e**(-2*x)*(15.0796*np.cos(3*np.pi*x)-3.2*np.sin(3*np.pi*x))\n\ny = [f(i) for i in x]\ny1 = [f(i) for i in x1]\ny2 = [f(i) for i in x2]\ndy = [df(i) for i in x]\n\nlagrange = createLagrange(x,y)\nLy = [lagrange(i) for i in x2]\ndiff = differenceFunction(lagrange, f)\nLyDiff = [diff(i) for i in x2]\n\nhermiteF = hermite(x, y, dy)\nHy = [hermiteF(i) for i in x1]\ndiff = differenceFunction(hermiteF, f)\nHdiff = [diff(i) for i in x1]\n\ncubicSplineF = cubicSpline(x, y)\ncSy = [cubicSplineF(i) for i in x2]\ndiff = differenceFunction(cubicSplineF, f)\ncubicDiff = [diff(i) for i in x2]\n\nlinearSplineF = linearSpline(x,y)\nlSy = [linearSplineF(i) for i in x2]\ndiff = differenceFunction(linearSplineF, f)\nlinearDiff = [diff(i) for i in x2]\n\n\nplt.figure(1)\nplt.subplot(211)\nplt.title('Linear Spline vs. f(x)')\nplt.plot(x2,y2,'b')\nplt.plot(x2, lSy, 'g')\nplt.subplot(212)\nplt.title('Diffrence function')\nplt.plot(x2, linearDiff, 'g')\nplt.plot(lineX2, lineY2, 'b')\n\nplt.figure(2)\nplt.subplot(221)\nplt.title('Lagrange vs f(x)')\nplt.plot(x2,Ly,'b')\nplt.plot(x2,y2,'g')\nplt.subplot(223)\nplt.title('Left Quarter diffrenence')\nplt.plot(x2[(len(lineX2)/20)*2:(len(lineX2)/4)],LyDiff[(len(lineX2)/20)*2:(len(lineX2)/4)], 'g')\nplt.plot(lineX2[(len(lineX2)/20)*2:(len(lineX2)/4)],lineY2[(len(lineX2)/20)*2:(len(lineX2)/4)], 'b')\nplt.subplot(224)\nplt.title('Right Quarter difference')\nplt.plot(x2[3*(len(lineX2)/4):len(lineX2) - (len(lineX2)/20)*2],LyDiff[3*(len(lineX2)/4):len(lineX2) - (len(lineX2)/20)*2], 'g')\nplt.plot(lineX2[3*(len(lineX2)/4):len(lineX2) - (len(lineX2)/20)*2],lineY2[3*(len(lineX2)/4):len(lineX2) - (len(lineX2)/20)*2], 'b')\nplt.subplot(222)\nplt.title('Middle half difference')\nplt.plot(x2[len(lineX2)/4:3*(len(lineX2)/4)],LyDiff[(len(lineX2)/4):3*(len(lineX2)/4)], 'g')\nplt.plot(lineX2[len(lineX2)/4:3*(len(lineX2)/4)],lineY2[(len(lineX2)/4):3*(len(lineX2)/4)], 'b')\n\nplt.figure(3)\nplt.subplot(221)\nplt.title('Hermite vs f(x)')\nplt.plot(x1,Hy,'b')\nplt.plot(x1,y1,'g')\nplt.subplot(223)\nplt.title('Left Quarter diffrenence')\nplt.plot(x2[(len(lineX1)/20)*2:(len(lineX1)/4)],Hdiff[(len(lineX1)/20)*2:(len(lineX1)/4)], 'g')\nplt.plot(lineX1[(len(lineX1)/20)*2:(len(lineX1)/4)],lineY1[(len(lineX1)/20)*2:(len(lineX1)/4)], 'b')\nplt.subplot(224)\nplt.title('Right Quarter difference')\nplt.plot(x1[3*(len(lineX1)/4):len(lineX1) - (len(lineX1)/20)*2],Hdiff[3*(len(lineX1)/4):len(lineX1) - (len(lineX1)/20)*2], 'g')\nplt.plot(lineX1[3*(len(lineX1)/4):len(lineX1) - (len(lineX1)/20)*2],lineY1[3*(len(lineX1)/4):len(lineX1) - (len(lineX1)/20)*2], 'b')\nplt.subplot(222)\nplt.title('Middle half difference')\nplt.plot(x1[len(lineX1)/4:3*(len(lineX1)/4)],Hdiff[(len(lineX1)/4):3*(len(lineX1)/4)], 'g')\nplt.plot(lineX1[len(lineX1)/4:3*(len(lineX1)/4)],lineY1[(len(lineX1)/4):3*(len(lineX1)/4)], 'b')\n\nplt.figure(4)\nplt.subplot(221)\nplt.title('Cubic Spline vs f(x)')\nplt.plot(x2,Ly,'b')\nplt.plot(x2,y2,'g')\nplt.subplot(223)\nplt.title('Left Quarter diffrenence')\nplt.plot(x2[(len(lineX2)/20)*2:(len(lineX2)/4)],cubicDiff[(len(lineX2)/20)*2:(len(lineX2)/4)], 'g')\nplt.plot(lineX2[(len(lineX2)/20)*2:(len(lineX2)/4)],lineY2[(len(lineX2)/20)*2:(len(lineX2)/4)], 'b')\nplt.subplot(224)\nplt.title('Right Quarter difference')\nplt.plot(x2[3*(len(lineX2)/4):len(lineX2) - (len(lineX2)/20)*2],cubicDiff[3*(len(lineX2)/4):len(lineX2) - (len(lineX2)/20)*2], 'g')\nplt.plot(lineX2[3*(len(lineX2)/4):len(lineX2) - (len(lineX2)/20)*2],lineY2[3*(len(lineX2)/4):len(lineX2) - (len(lineX2)/20)*2], 'b')\nplt.subplot(222)\nplt.title('Middle half difference')\nplt.plot(x2[len(lineX2)/4:3*(len(lineX2)/4)],cubicDiff[(len(lineX2)/4):3*(len(lineX2)/4)], 'g')\nplt.plot(lineX2[len(lineX2)/4:3*(len(lineX2)/4)],lineY2[(len(lineX2)/4):3*(len(lineX2)/4)], 'b')\n\nplt.show()\n" }, { "alpha_fraction": 0.5209790468215942, "alphanum_fraction": 0.7167832255363464, "avg_line_length": 22.75, "blob_id": "85ee630d4af9e62a64d1a30ba0cb06131be66fe2", "content_id": "80ccf73b611655ef8192cbec7f2f88a60e2a7a46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 286, "license_type": "no_license", "max_line_length": 42, "num_lines": 12, "path": "/homework2/test.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from interpolation import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = [1.3, 1.6, 1.9]\nfx = [0.6200860, 0.4554022, 0.2818186]\ndfx = [-0.5220232, -0.5698959, -0.5811571]\n\nhermiteCo = hermiteCoefficients(x,fx,dfx)\nhermite = completeHermite(hermiteCo, x)\n\nprint hermite(1.5)\n\n" }, { "alpha_fraction": 0.6755555272102356, "alphanum_fraction": 0.7060317397117615, "avg_line_length": 32.46808624267578, "blob_id": "8912b112ebb26c4721799110e5302a8ad66cd2fd", "content_id": "993f91c2f7c4ccf0de077c9b8905084fadd6e5da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1575, "license_type": "no_license", "max_line_length": 79, "num_lines": 47, "path": "/homework1/prob2.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from gauss import *\n\nmatrix = [\n [10.,10.,10.,1e17,1e17],\n [1.,1e-3,1e-3,1e-3,1.],\n [1.,1.,1e-3,1e-3,2.],\n [1.,1.,1.,1e-3,3.]\n ]\n\nprint '***The matrix in question:***'\nshow(matrix)\na = rowReduce(matrix)\nA = a\na = backSub(a)\nprint '\\na) using basic Gaussian elemination we get:'\nshow(a)\n\nb = rowReducePartialPivots(matrix)\nb = backSub(b)\nprint '\\nb) using Gaussian elemination with partial pivoting we get:'\nshow(b)\n\nc = scaledPartialRowReduce(matrix)\nC = c\nc = backSub(c)\nprint '\\nc) using Gaussian elimination with partially scaled pivoting we get:' \nshow(c)\n\nprint '\\nwe get the same answer in part a and be because zeroing out'\nprint 'the first column below position 1,1 completely row reduces '\nprint 'the matrix so it makes no diffrence if we use partial pivots'\nprint '\\nKnowing this the resdual error vector for both a and b is:'\nshow(resErrorVector(matrix,b))\nprint '\\nand the residual error vector for part c is:'\nshow(resErrorVector(matrix,c))\n\nprint '\\nSo using partially scaled pivoting we get very close to the answer, '\nprint 'but with basic Gaussian elimination we do not get quite as close.'\nprint 'Now lets compare the reduced matrix from a and from c:\\n'\nshow(A)\nprint\nshow(C)\nprint '\\nWe can see that x4 should be about 1-3(10^(-16))'\nprint 'However, both algorithms round that to 1 which is not far off.'\nprint 'Except that in part a this error is multiplied by -10^16 when solving'\nprint 'for x3 which makes it a much more meaningful error as opposed to part'\nprint 'c where the error has almost no impact'\n\n\n" }, { "alpha_fraction": 0.7645502686500549, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 14.708333015441895, "blob_id": "c242a9b85ec0ac64059f8d6bab7539788222a0f9", "content_id": "6ee7135832af30e72ecb3eac81af397f5e28d57b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 378, "license_type": "no_license", "max_line_length": 26, "num_lines": 24, "path": "/homework1/test.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from gauss import *\n\nH = populateHilbert(2)\nshow(hilbertInverse(2))\nprint\nshow(invertScaledGauss(H))\nprint\nprint\nH = populateHilbert(3)\nshow(hilbertInverse(3))\nprint\nshow(invertScaledGauss(H))\nprint\nprint\nH = populateHilbert(4)\nshow(hilbertInverse(4))\nprint\nshow(invertScaledGauss(H))\nprint\nprint\nH = populateHilbert(5)\nshow(hilbertInverse(5))\nprint\nshow(invertScaledGauss(H))\n\n" }, { "alpha_fraction": 0.6575999855995178, "alphanum_fraction": 0.6762666702270508, "avg_line_length": 41.6136360168457, "blob_id": "ccb6f7d4561eb54f55268334994d8e18eb946a43", "content_id": "560de368874e1fd8697cb4b0d3f84c7ad35a3cba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1875, "license_type": "no_license", "max_line_length": 83, "num_lines": 44, "path": "/homework1/prob3.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from gauss import *\n\nnums = [3,5,10,15,20,25]\n\nH = [populateHilbert(i) for i in nums]\nVb = [bHilbert(i) for i in nums]\nHb = [augment(H[i],Vb[i]) for i in range(len(nums))]\n\na = [rowReduce(Hb[i]) for i in range(len(nums))]\nA = [backSub(a[i]) for i in range(len(nums))]\nAr = [resErrorVector(Hb[i],A[i]) for i in range(len(nums))]\n\nb = [scaledPartialRowReduce(Hb[i]) for i in range(len(nums))]\nB = [backSub(b[i]) for i in range(len(nums))]\nBr = [resErrorVector(Hb[i],B[i]) for i in range(len(nums))]\n\nL = [L(H[i]) for i in range(len(nums))]\nU = [U(H[i]) for i in range(len(nums))]\ny = [forwardSub(augment(L[i],Vb[i])) for i in range(len(nums))]\nx = [backSub(augment(U[i],y[i])) for i in range(len(nums))]\nxr = [resErrorVector(Hb[i],x[i]) for i in range(len(nums))]\n\ng = [gaussSeidel(Hb[i], [0 for j in range(nums[i])],0.1) for i in range(len(nums))]\ngr = [resErrorVector(Hb[i],g[i]) for i in range(len(nums))]\n\nprint 'Here we made 6 Hilbert matrices of sizes 3,5,10,15,20,25 and'\nprint 'solved them each using basic Gaussian elimination, '\nprint 'scaled partial pivoting, LU factorization, and Gauss-Seidel.'\nprint 'Below are the residual error vectors for each matrix size and'\nprint 'solution method combination:'\nprint\nfor i in range(len(nums)):\n print '\\t\\t\\t\\t\\t\\t\\tsize: %d'%nums[i]\n print '\\tbasic\\t\\t\\t\\tscaled\\t\\t\\t\\tLU\\t\\t\\t\\tG-S'\n for j in range(len(Ar[i])):\n print '%s\\t\\t%s\\t\\t%s\\t\\t%s'%(Ar[i][j],Br[i][j],xr[i][j],gr[i][j])\n print\n\nprint '\\nIt seems that throughout basic, scaled, and LU give consistently'\nprint 'not great answers. Most elements in these vectors fall between'\nprint 'about -4 and 4 with a few going higher, some almost reaching 10'\nprint 'or -10. Gauss-Seidel on the other hand is very consistently close'\nprint 'to the solution with the elements in its error vectors never leaving'\nprint 'a lower bound of -0.03 and upper bound of 0.6'\n" }, { "alpha_fraction": 0.568359375, "alphanum_fraction": 0.607421875, "avg_line_length": 18.673076629638672, "blob_id": "03fd2e6f9f1fe0a29506ed1380d3258088458b85", "content_id": "d1443161e69fa4226612a013104c68dbd8810419", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1024, "license_type": "no_license", "max_line_length": 77, "num_lines": 52, "path": "/homework5/legendre.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from scipy.integrate import quad\nimport numpy as np\n\ndef generateX(numPoints, start, finish):\n return [((finish-start)/(numPoints-1))*i + start for i in range(numPoints)]\n\ndef legendre0(x):\n return 1.\n\ndef legendre1(x):\n return x\n\ndef legendre2(x):\n return (x**2) - (1./3)\n\ndef legendre3(x):\n return x**3 - (3./5)*x\n\ndef legendre4(x):\n return x**4 - (6./7)*x**2 + 3./35\n\ndef Legendre(k, x):\n if k == 0:\n return legendre0(x)\n elif k == 1:\n return legendre1(x)\n elif k == 2:\n return legendre2(x)\n elif k == 3:\n return legendre3(x)\n elif k == 4:\n return legendre4(x)\n\ndef genC(func):\n def square(x):\n return func(x)**2\n return quad(square, -1, 1)[0]\n\ndef genAk(k, func):\n def legendre(x):\n return Legendre(k,x)\n def funcLegendre(x):\n return Legendre(k,x) * func(x)\n return (1./genC(legendre)) * quad(funcLegendre, -1, 1)[0]\n\ndef genP(k, func):\n def P(x):\n result = 0;\n for i in range(k+1):\n result = result + genAk(k-i,func)*Legendre(k-i,x)\n return result\n return P\n\n" }, { "alpha_fraction": 0.2579365074634552, "alphanum_fraction": 0.7279942035675049, "avg_line_length": 41.64615249633789, "blob_id": "29a041aa0d84d1ef67842bac4198643bfc894bad", "content_id": "c098cab20950023ba143ef6f3578dc46a89cac22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2772, "license_type": "no_license", "max_line_length": 183, "num_lines": 65, "path": "/homework3/numericalIntegrals.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "import numpy as np\n\ndef gaussPoints(n):\n if n == 2:\n return [0.57735029692, -0.5773502692]\n elif n == 3:\n return [0.7745966692, 0, -0.7745966692]\n elif n == 4:\n return [0.8611363116, 0.3399810436, -0.3399810436, -0.8611363116]\n elif n==5:\n return [0.9061798459, 0.5384693101, 0, -0.5384693101, -0.9061798459]\n elif n==6: \n return [0.6612093864662645, -0.6612093864662645, -0.2386191860831969,0.2386191860831969,-0.9324695142031521,0.9324695142031521]\n elif n==7:\n return [0, 0.4058451513773972, -0.4058451513773972,-0.7415311855993945,0.7415311855993945,-0.9491079123427585,0.9491079123427585]\n elif n==8:\n return [-0.1834346424956498,0.1834346424956498,-0.5255324099163290,0.5255324099163290,-0.7966664774136267,0.7966664774136267,-0.9602898564975363,0.9602898564975363]\n else:\n return [0,-0.8360311073266358,0.8360311073266358,-0.9681602395076261,0.9681602395076261,-0.3242534234038089,0.3242534234038089,-0.6133714327005904,0.6133714327005904]\n\ndef gaussWeights(n):\n if n == 2:\n return [1,1]\n elif n == 3:\n return [0.5555555556, 0.8888888889, 0.5555555556]\n elif n == 4:\n return [0.3478548451, 0.6521451549, 0.6521451549, 0.3478548451]\n elif n==5:\n return [0.2369268850, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268850]\n elif n==6:\n return [0.3607615730481386,0.3607615730481386,0.4679139345726910,0.4679139345726910,0.1713244923791704,0.1713244923791704]\n elif n==7:\n return [0.4179591836734694,0.3818300505051189,0.3818300505051189,0.2797053914892766,0.2797053914892766,0.1294849661688697,0.1294849661688697]\n elif n==8:\n return [0.3626837833783620,0.3626837833783620,0.3137066458778873,0.3137066458778873,0.2223810344533745,0.2223810344533745,0.1012285362903763,0.1012285362903763]\n else:\n return [0.3302393550012598,0.1806481606948574,0.1806481606948574,0.0812743883615744,0.0812743883615744,0.3123470770400029,0.3123470770400029,0.2606106964029354,0.2606106964029354]\n\ndef generateX(numPoints, start, finish):\n return [((finish-start)/(numPoints-1))*i+start for i in range(numPoints)]\n\ndef trapezoidal(x, y):\n return ((x[1]-x[0])/2)*(y[0] + 2 * np.sum([y[i] for i in range(1,len(y)-2)]) + y[len(y)-1])\n\ndef romberg(start, end, firstNumPoints, func):\n x1 = generateX(firstNumPoints, start, end)\n y1 = [func(x1[i]) for i in range(0,firstNumPoints)]\n x2 = generateX(firstNumPoints*2, start,end)\n y2 = [func(x2[i]) for i in range(0,firstNumPoints*2)]\n\n trap1 = trapezoidal(x1,y1)\n trap2 = trapezoidal(x2,y2)\n\n return trap2 + (trap2-trap1) / 3\n\ndef gaussQuadrature(a, b, func, numPoints):\n def t(x):\n return 0.5*((b-a)*x+a+b)\n scale = (b-a)/2\n\n x = gaussPoints(numPoints)\n w = gaussWeights(numPoints)\n\n terms = [func(t(x[i]))*w[i]*scale for i in range(len(x))]\n return sum(terms)\n" }, { "alpha_fraction": 0.5147895216941833, "alphanum_fraction": 0.5910125374794006, "avg_line_length": 24.83823585510254, "blob_id": "ecd70a2ae1e3c679408aee7a840d0a96c71c3a41", "content_id": "a24ab1530d92a00e06d2abb3f0be23fadd31f5af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1758, "license_type": "no_license", "max_line_length": 73, "num_lines": 68, "path": "/homework5/prob2.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from legendre import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = [0.01,0.9998,2.1203,3.0023,3.9892,5.0017]\ny = [0.9631,0.5221,0.233,0.1248,0.0107,0.0065]\n\ndef func(a,b,x):\n return b*np.e**(a*x)\n\ndef normal1(x, y, a, b):\n return (y-b*np.e**(a*x))*x*np.e**(a*x)\n\ndef normal2(x, y, a, b):\n return y-b*np.e**(a*x)\n\ndef f1a(x,y,a,b):\n return x**2*np.e**(a*x)*(y-2*b*np.e**(a*x))\n\ndef f1b(x,y,a,b):\n return x*np.e**(2*a*x)\n\ndef f2a(x,y,a,b):\n return -b*x*np.e**(a*x)\n\ndef f2b(x,y,a,b):\n return -np.e**(a*x)\n\ndef inverseJacobi(a,b):\n topLeft = sum([f1a(x[i],y[i],a,b) for i in range(len(x))])\n topRight = sum([f1b(x[i],y[i],a,b) for i in range(len(x))])\n botLeft = sum([f2a(x[i],y[i],a,b) for i in range(len(x))])\n botRight = sum([f2b(x[i],y[i],a,b) for i in range(len(x))])\n\n j = np.matrix([[topLeft,topRight],[botLeft,botRight]])\n\n return j.I\n\ndef tolerance(g1,g2):\n top = np.maximum(abs(g2[0]-g1[0]),abs(g2[1]-g1[1]))\n bot = np.maximum(abs(g2[0]), abs(g2[1]))\n return top/bot\n\nguess = [-1.,1.]\n\nwhile(1 == 1):\n J = inverseJacobi(guess[0],guess[1])\n f1 = sum([normal1(x[i],y[i],guess[0],guess[1]) for i in range(len(x))])\n f2 = sum([normal2(x[i],y[i],guess[0],guess[1]) for i in range(len(x))])\n deltaX = -J*np.matrix([[f1],[f2]])\n oldGuess = guess\n deltaX = deltaX.A1\n guess = [guess[0]+deltaX[0], guess[1]+deltaX[1]]\n\n if(tolerance(oldGuess,guess) < .00001):\n break\n\nx1 = generateX(100, -0.1, 5.1)\ny1 = [func(guess[0],guess[1],x1[i]) for i in range(len(x1))]\nE = sum([(y[i]-func(guess[0],guess[1],x[i]))**2 for i in range(len(x))])\n\nprint(\"The best fit function is: {0}e^({1}x)\".format(guess[1],guess[0]))\nprint(\"The sum of the squared errors is: {0}\".format(E))\n\nplt.figure(1)\nplt.plot(x,y)\nplt.plot(x1,y1)\nplt.show()\n\n" }, { "alpha_fraction": 0.46543002128601074, "alphanum_fraction": 0.5716694593429565, "avg_line_length": 15.472222328186035, "blob_id": "090eaecb5ddb4f6a3d572ecbc70e582ee9efbcaf", "content_id": "cd12af701c785bfc18f7ae2ba2d3fb5e2c42b2d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "no_license", "max_line_length": 32, "num_lines": 36, "path": "/homework5/prob3.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from legendre import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n if x <= -0.5:\n return 0.\n elif x < 0.5:\n return 1.\n else:\n return 0.\n\nP0 = genP(0, f)\nP1 = genP(1, f)\nP2 = genP(2, f)\nP3 = genP(3, f)\nP4 = genP(4, f)\nP1(1)\n\nx1 = generateX(400, -1., 1.)\nx2 = generateX(600, -1.25, 1.25)\ny = [f(i) for i in x1]\ny0 = [P0(i) for i in x2]\ny1 = [P1(i) for i in x2]\ny2 = [P2(i) for i in x2]\ny3 = [P3(i) for i in x2]\ny4 = [P4(i) for i in x2]\n\nplt.figure(1)\nplt.plot(x1, y)\nplt.plot(x2, y0)\nplt.plot(x2, y1)\nplt.plot(x2, y2)\nplt.plot(x2, y3)\nplt.plot(x2, y4)\nplt.show()\n" }, { "alpha_fraction": 0.527884840965271, "alphanum_fraction": 0.5505300164222717, "avg_line_length": 24.816484451293945, "blob_id": "afd52ac8f706fbbcdbeb45e9b74a11163a3582f4", "content_id": "8d460c4d1d93e7f1e8c6455df045f216997cc432", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16604, "license_type": "no_license", "max_line_length": 133, "num_lines": 643, "path": "/homework1/gauss.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "\"\"\"\ngauss_elim_1.py\n\nIncludes code for functions that do basic vector and\nmatrix arithmetic. Most of these functions support\nthe function ge_1(aug) which takes an n by n+1\naugmented matrix and returns a row-reduced matrix and\nan approximate solution vector of the corresponding linear\nsystem. It uses gaussian elimination with a naive pivot\nstrategy. That is, at each stage in the row reduction it\nchooses, as the pivot, the first nonzero entry that lies\non or below the diagonal in the current column.\n\nrevision 0.01 02/06/12 added code [ds]\nrevision 0.02 02/06/12 gardened out some code [bic]\nrevision 1.23 02/08/12 added aug_2 example, cleaned code [ds]\nrevision 1.24 02/09/12 cleaned code some more [ds]\nrevision 2.00 03/12/12 changed filename, commented out tests [ds]\n\nmatrix examples: [[28, 12, 20, 28], [4, 32, 28, 16]] , 2 by 4\n [[28, 12, 20, 28]] , 1 by 4\n [[[28], [12], [20], [28]] , 4 by 1\n\n\nvector example [28, 12, 20, 28] \n\n\"\"\"\nimport math\n\ndef rows(mat):\n \"return number of rows\"\n return(len(mat))\n\ndef cols(mat):\n \"return number of cols\"\n return(len(mat[0]))\n \ndef zero(m,n):\n \"Create zero matrix\"\n new_mat = [[0 for col in range(n)] for row in range(m)]\n return new_mat\n \ndef transpose(mat):\n \"return transpose of mat\"\n new_mat = zero(cols(mat),rows(mat))\n for row in range(rows(mat)):\n for col in range(cols(mat)):\n new_mat[col][row] = mat[row][col]\n return(new_mat)\n\ndef dot(A,B):\n \"vector dot product\"\n if len(A) != len(B):\n print(\"dot: list lengths do not match\")\n return()\n dot=0\n for i in range(len(A)):\n dot = dot + A[i]*B[i]\n return(dot)\n\ndef getCol(mat, col):\n \"return column col from matrix mat\"\n return([r[col] for r in mat])\n\ndef getRow(mat, row):\n \"return row row from matrix mat\"\n return(mat[row])\n\ndef matMult(mat1,mat2):\n \"multiply two matrices\"\n if cols(mat1) != rows(mat2):\n print(\"multiply: mismatched matrices\")\n return()\n prod = zero(rows(mat1),cols(mat2))\n for row in range(rows(mat1)):\n for col in range(cols(mat2)):\n prod[row][col] = dot(mat1[row],getCol(mat2,col))\n return(prod)\n\ndef vectorQ(V):\n \"mild test to see if V is a vector\"\n if type(V) != type([1]):\n return(False)\n if type(V[0]) == type([1]):\n return(False)\n return(True)\n\ndef vecMatMult(M,V):\n result = range(len(V))\n for i in range(len(V)):\n result[i] = [M[i][j]*V[j] for j in range(len(V))]\n return result\n\ndef scalarMult(a,mat):\n \"multiply a scalar times a matrix\"\n if vectorQ(mat):\n return([a*m for m in mat])\n for row in range(rows(mat)):\n for col in range(cols(mat)):\n mat[row][col] = a*mat[row][col]\n return(mat)\n\ndef addVectors(A,B):\n \"add two vectors\"\n if len(A) != len(B):\n print(\"addVectors: different lengths\")\n return()\n return([A[i]+B[i] for i in range(len(A))])\n\ndef swaprows(M,i,j):\n \"swap rows i and j in matrix M\"\n N=copyMatrix(M)\n T = N[i]\n N[i] = N[j]\n N[j] = T\n return N\n\ndef copyMatrix(M):\n return([[M[row][col] for col in range(cols(M))]for row in\n range(rows(M))])\n\ndef addrows(M, f, t, scale=1):\n \"add scale times row f to row t\"\n N=copyMatrix(M)\n T=addVectors(scalarMult(scale,N[f]),N[t])\n N[t]=T\n return(N)\n\ndef roundMat(mat, p):\n A = range(len(mat)) \n for i in range(len(mat)):\n A[i] = [round(mat[i][j],p) for j in range(len(mat[i]))]\n return A\n \ndef show(mat):\n \"Print out matrix\"\n for row in mat:\n print(row)\n\ndef showMany(mats):\n n = len(mats)\n for i in range(len(mats[0])):\n for j in range(n):\n print '\\t%f'%mats[j][i],\n print ''\n\ndef compareMats(A,B):\n C = range(len(A))\n for i in range(len(A)):\n C[i] = [A[i][j]-B[i][j] for j in range(len(A[i]))]\n return C\n\ndef avgElement(A):\n sum = 0;\n for i in range(len(A)):\n for j in range(len(A[0])):\n sum = sum + math.fabs(A[i][j])\n return sum / (len(A) + len(A[0]))\n\n### vectors vs rowVectors and colVectors\n### the latter are matrices\n\ndef vec2rowVec(vec):\n \"[a,b,c] -> [[a,b,c]]\"\n return([vec])\n\ndef vec2colVec(vec):\n return(transpose(vec2rowVec(vec)))\n\ndef colVec2vec(mat):\n rowVec = transpose(mat)\n return(rowVec[0])\n\ndef augment(mat,vec):\n \"given nxn mat and n length vector return augmented matrix\"\n amat = []\n for row in range(rows(mat)):\n amat.append(mat[row]+[vec[row]])\n return(amat)\n\n\ndef getAandb(aug):\n \"Returns the coef. matrix A and the vector b of Ax=b\"\n m = rows(aug)\n n = cols(aug)\n A = zero(m,n-1)\n b = zero(m,1)\n for i in range(m):\n for j in range(n-1):\n A[i][j] = aug[i][j]\n \n for i in range(m):\n b[i] = aug[i][n-1]\n Aandb = [A,b]\n return(Aandb)\n\ndef checkSol_1(aug,x):\n \"For aug=[A|b], returns Ax, b, and b-Ax as vectors\"\n A = getAandb(aug)[0]\n b = getAandb(aug)[1]\n x_col_vec = vec2colVec(x)\n Ax = matMult(A,x_col_vec)\n r = addVectors(b,scalarMult(-1.0,colVec2vec(Ax)))\n L = [Ax,b,r]\n return(L)\n\ndef resErrorVector(aug,x):\n \"For aug=[A|b], returns Ax, b, and b-Ax as vectors\"\n A = getAandb(aug)[0]\n b = getAandb(aug)[1]\n x_col_vec = vec2colVec(x)\n Ax = matMult(A,x_col_vec)\n r = addVectors(b,scalarMult(-1.0,colVec2vec(Ax)))\n return(r)\n\n\n### The naive gaussian elimination code begins here.\n\ndef populateHilbert(n):\n H = range(1,n+1)\n index = 0\n for row in range(0,n):\n H[row] = [1./(k+index) for k in range(1,n+1)]\n index = index + 1\n return H\n\ndef hilbertInverse(n):\n H = range(n)\n for k in range(1,n+1):\n H[k-1] = [math.pow(-1,k+l)*(k+l-1)*binomCoe(n+k-1,n-l)*binomCoe(n+l-1,n-k)*math.pow(binomCoe(k+l-2,k-1),2) for l in range(1,n+1)]\n return H\n\ndef binomCoe(n,k):\n top = factorial(n)\n bot = factorial(k)*factorial(n-k)\n return top/bot\n\ndef factorial(n):\n product = 1\n for i in range(1,n+1):\n product = product * i\n return product\n\ndef bHilbert(n):\n b = range(n)\n b[0] = 2./math.pi\n b[1] = 1./math.pi\n if (n > 2):\n for i in range(2,n):\n b[i] = b[1] - i*b[1]*(i-1)*b[1]*b[i-2]\n return b\n\ndef createHilbert(n):\n H = populateHilbert(n)\n b = bHilbert(n)\n return augment(H,b)\n\ndef LU(M):\n \"return L and U\"\n U = copyMatrix(M)\n cs = cols(M)-1 # no need to consider last two cols\n rs = rows(M)\n L = createIdentity(rs)\n for col in range(cs+1):\n scale = -1.0 / U[col][col]\n for row in range(col+1,rs): \n L[row][col] = -scale * U[row][col]\n U=addrows(U, col, row, scale * U[row][col])\n return L, U\n\ndef L(M):\n \"return L and U\"\n U = copyMatrix(M)\n cs = cols(M)-1 # no need to consider last two cols\n rs = rows(M)\n L = createIdentity(rs)\n for col in range(cs+1):\n scale = -1.0 / U[col][col]\n for row in range(col+1,rs): \n L[row][col] = -scale * U[row][col]\n U=addrows(U, col, row, scale * U[row][col])\n return L\n\ndef U(M):\n \"return L and U\"\n U = copyMatrix(M)\n cs = cols(M)-1 # no need to consider last two cols\n rs = rows(M)\n L = createIdentity(rs)\n for col in range(cs+1):\n scale = -1.0 / U[col][col]\n for row in range(col+1,rs): \n L[row][col] = -scale * U[row][col]\n U=addrows(U, col, row, scale * U[row][col])\n return U\n\ndef forwardSub(M):\n \"\"\"\n given a row reduced augmented matrix with nonzero \n diagonal entries, returns a solution vector\n \n \"\"\"\n cs = cols(M)-1 # cols not counting augmented col\n sol = [0 for i in range(cs)] # place for solution vector\n sol[0] = M[0][cs] / M[0][0]\n for i in range(1,cs):\n row = i # work backwards\n sol[row] = ((M[row][cs] - sum([M[row][j]*sol[j] for\n j in range(0,row)])) / M[row][row]) \n return(sol)\n\ndef gaussSeidel(M,v,tolerance):\n v2 = range(len(v))\n for i in range(len(v)):\n v2[i] = (1/M[i][i]) * (M[i][len(v)-1] - sum([M[i][j]*v2[j] for j in range(i)]) - sum([M[i][k]*v[k] for k in range(i+1,len(v))]))\n tolCheck = maxNorm(addVectors(v2, scaleVector(v,-1))) / maxNorm(v2)\n if tolCheck < tolerance :\n return v2\n else :\n return gaussSeidel(M,v2,tolerance)\n\ndef maxNorm(v):\n max = v[0]\n for i in range(1,len(v)):\n if v[i] > max:\n max = v[i]\n return max\n\ndef createIdentity(n):\n I = range(n)\n for i in range(n):\n I[i] = range(n)\n for j in range(n):\n if(i == j):\n I[i][j] = 1.\n else:\n I[i][j] = 0.\n return I\n\ndef invertScaledGauss(M):\n \"return row reduced version of M\"\n N = copyMatrix(M) \n rs = rows(M)\n idMat = createIdentity(rs)\n for i in range(rs):\n N = augment(N, getCol(idMat, i))\n rs = rows(N)\n N = scaleRows(N)\n for col in range(rs):\n j = findPartialPivot(N,col)\n if j < 0:\n print(\"\\nrowReduce: No pivot found for column index %d \"%(col))\n else:\n if j != col:\n N = swaprows(N,col,j)\n scale = -1.0 / N[col][col]\n for row in range(col+1,rs): \n N=addrows(N, col, row, scale * N[row][col])\n return solveInverse(N)\n\ndef invertGauss(M):\n \"return row reduced version of M\"\n rs = rows(M)\n idMat = createIdentity(rs)\n N = copyMatrix(M)\n for i in range(rs):\n N = augment(N, getCol(idMat, i))\n rs = rows(N)\n for col in range(rs):\n j = findPivotrow1(N,col)\n if j < 0:\n print(\"\\nrowReduce: No pivot found for column index %d \"%(col))\n return(N)\n else:\n if j != col:\n N = swaprows(N,col,j)\n scale = -1.0 / N[col][col]\n for row in range(col+1,rs): \n N=addrows(N, col, row, scale * N[row][col])\n return solveInverse(N)\n\ndef solveInverse(N):\n \"\"\"\n given a row reduced augmented matrix with nonzero \n diagonal entries, returns a solution vector\n \n \"\"\"\n inverse = 1\n m = range(rows(N))\n length = m\n for i in length:\n m[i] = [N[i][j] for j in range(rows(N))]\n for k in range(rows(N)):\n M = augment(m, getCol(N, rows(N)+k))\n cs = cols(M)-1 # cols not counting augmented col\n sol = [0 for i in range(cs)] # place for solution vector\n for i in range(1,cs+1):\n row = cs-i # work backwards\n sol[row] = ((M[row][cs] - sum([M[row][j]*sol[j] for\n j in range(row+1,cs)])) / M[row][row]) \n inverse = createAug(inverse, sol)\n return inverse\n\ndef createAug(M,v):\n if M != 1:\n return augment(M,v)\n else:\n return [[v[i]] for i in range(len(v))]\n\ndef findPivotrow1(mat,col):\n \"Finds index of the first row with nonzero entry on or\"\n \"below diagonal. If there isn't one return(-1).\"\n for row in range(col, rows(mat)):\n if mat[row][col] != 0:\n return(row)\n return(-1)\n\n\ndef rowReduce(M):\n \"return row reduced version of M\"\n N = copyMatrix(M)\n cs = cols(M)-2 # no need to consider last two cols\n rs = rows(M)\n for col in range(cs+1):\n j = findPivotrow1(N,col)\n if j < 0:\n print(\"\\nrowReduce: No pivot found for column index %d \"%(col))\n return(N)\n else:\n if j != col:\n N = swaprows(N,col,j)\n scale = -1.0 / N[col][col]\n for row in range(col+1,rs): \n N=addrows(N, col, row, scale * N[row][col])\n return(N)\n\ndef rowReduceTrace(M):\n \"return row reduced version of M\"\n print\n show(M)\n print\n N = copyMatrix(M)\n cs = cols(M)-2 # no need to consider last two cols\n rs = rows(M)\n for col in range(cs+1):\n j = findPivotrow1(N,col)\n if j < 0:\n print(\"\\nrowReduce: No pivot found for column index %d \"%(col))\n return(N)\n else:\n if j != col:\n N = swaprows(N,col,j)\n scale = -1.0 / N[col][col]\n for row in range(col+1,rs): \n N=addrows(N, col, row, scale * N[row][col])\n show(N)\n print\n return(N)\n\ndef scaleVector(V, s):\n return [k*s for k in V]\n\ndef scaleRows(M):\n N = copyMatrix(M)\n for row in range(len(N)):\n scalerIndex = 0\n for index in range(len(N[row])):\n if N[row][index] > N[row][scalerIndex]:\n scalerIndex = index\n N[row] = scaleVector(N[row], 1/(N[row][scalerIndex]))\n return N\n\ndef scaledPartialRowReduce(M):\n N = scaleRows(M)\n return rowReducePartialPivots(N)\n\ndef findPartialPivot(mat, col):\n pivot = col\n for row in range(col, len(mat)):\n if math.fabs(mat[row][col]) > math.fabs(mat[pivot][col]):\n pivot = row\n\n if mat[pivot][col] == 0:\n return -1\n return pivot\n\ndef rowReducePartialPivots(M):\n \"return row reduced version of M\"\n N = copyMatrix(M)\n cs = cols(M)-2 # no need to consider last two cols\n rs = rows(M)\n for col in range(cs+1):\n j = findPartialPivot(N,col)\n if j < 0:\n print(\"\\nrowReduce: No pivot found for column index %d \"%(col))\n for col in range(cs+1):\n j = findPartialPivot(N,col)\n if j < 0:\n print(\"\\nrowReduce: No pivot found for column index %d \"%(col))\n return(N)\n else:\n if j != col:\n N = swaprows(N,col,j)\n scale = -1.0 / N[col][col]\n for row in range(col+1,rs): \n N=addrows(N, col, row, scale * N[row][col])\n return(N)\n\ndef backSub(M):\n \"\"\"\n given a row reduced augmented matrix with nonzero \n diagonal entries, returns a solution vector\n \n \"\"\"\n cs = cols(M)-1 # cols not counting augmented col\n sol = [0 for i in range(cs)] # place for solution vector\n for i in range(1,cs+1):\n row = cs-i # work backwards\n sol[row] = ((M[row][cs] - sum([M[row][j]*sol[j] for\n j in range(row+1,cs)])) / M[row][row]) \n return(sol)\n\ndef backSubTrace(M):\n \"\"\"\n given a row reduced augmented matrix with nonzero \n diagonal entries, returns a solution vector\n \n \"\"\"\n print 'After being reduced our matrix is:'\n show(M)\n print\n cs = cols(M)-1 # cols not counting augmented col\n sol = [0 for i in range(cs)] # place for solution vector\n for i in range(1,cs+1):\n row = cs-i # work backwards\n sol[row] = ((M[row][cs] - sum([M[row][j]*sol[j] for\n j in range(row+1,cs)])) / M[row][row]) \n print\n print 'Back sub step %d'%i\n show(sol)\n return(sol)\n\n\ndef diag_test(mat):\n \"\"\"\n Returns True if no diagonal element is zero, False\n otherwise.\n \n \"\"\"\n for row in range(rows(mat)):\n if mat[row][row] == 0:\n return(False)\n else:\n return(True)\n\n\ndef ge_1(aug): \n \"\"\"\n Given an augmented matrix it returns a list. The [0]\n element is the row-reduced augmented matrix, and \n ge_1(aug)[1] is a solution vector. The solution\n vector is empty if there is no unique solution.\n \n \"\"\"\n aug_n = rowReduce(aug)\n if diag_test(aug_n):\n sol = backSub(aug_n)\n else:\n print(\"\\nge_1(): There is no unique solution\")\n sol = []\n results = [aug_n, sol]\n return(results)\n\n\n### Some Testing code begins here.\n\nA= [[4,-2,1],\n [-2,4,-2],\n [1,-2,4]]\n\n\nC=[2,3,5]\n\n\naug = [[ 1.0, -1.0, 2.0, -1.0, 8.0],\n [ 0.0, 0.0, -1.0, -1.0, -4.0],\n [ 0.0, 2.0, -1.0, 1.0, 6.0],\n [ 0.0, 0.0, 2.0, 4.0, 12.0]]\n\n\naug_2 = [[ 1, -1, 2, -1, 8],\n [ 0, 0, -1, -1, -4],\n [ 0, 2, -1, 1, 6],\n [ 0, 0, 2, 2, 12]]\n\n\n\"\"\"\n\ndef showProcess(A,S):\n \"given matrix A and vector S, get B=AS and show solve for S\"\n print(\"A\")\n show(A)\n print(\"S=%s\"%(S))\n B = matMult(A,vec2colVec(S))\n print(\"A*S=%s\"%(B))\n AS = augment(A,colVec2vec(B))\n print(\"augment(A,A*S)=\")\n show(AS)\n Ar=rowReduce(AS)\n print(\"row reduced Ar=\")\n show(Ar)\n sol = backSub(Ar)\n print(\"solution is %s\"% sol)\n print(\"aug = \")\n show(aug)\n aug_n = rowReduce(aug)\n print(\"aug_n = \")\n show(aug_n)\n print(\"the solution from ge_1(aug) is %s\"%(ge_1(aug)[1]))\n print(\"\\naug = \")\n show(aug)\n L = getAandb(aug)\n print(\"\\nA = \")\n show(L[0])\n print(\"\\nb = %s\"%(L[1]))\n y = ge_1(aug)[1]\n print(\"\\ny = ge_1(aug)[1] = %s\"%(y))\n x_vec = vec2rowVec(y)\n print(\"\\nx_row_vec = %s\"%(x_vec))\n x = transpose(vec2rowVec(y))\n print(\"\\nx_col_vec = %s\"%(x))\n Ax = matMult(L[0],x)\n print(\"\\nAx = %s\"%(Ax))\n print(\"\\nAx_vec = %s\"%(colVec2vec(Ax)))\n x_col_vec = vec2colVec(ge_1(aug)[1])\n L = checkSol_1(aug,ge_1(aug)[1])\n print(\"\\naug_2_n = ge_1(aug_2)[0] = \\n\")\n show(outputlist[0])\n print(\"\\nge_1(aug_2)[1] is %s\"%(outputlist[1]))\n\nshowProcess(A,C)\n\n\"\"\"\n\n\n\n\n" }, { "alpha_fraction": 0.5954631567001343, "alphanum_fraction": 0.6512287259101868, "avg_line_length": 25.424999237060547, "blob_id": "8704e48351bc31058e888c1f848f85139df25868", "content_id": "edd04865194622be85c36770e03c4ea28396c5d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1058, "license_type": "no_license", "max_line_length": 75, "num_lines": 40, "path": "/homework4/newton.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom polynomials import *\n\ndef generateX(numPoints, start, finish):\n return [((finish-start)/(numPoints-1))*i+start for i in range(numPoints)]\n\ndef singleTol(old,new):\n top = np.fabs(old-new)\n return top/np.fabs(old)\n\ndef infinTol(old,new):\n top = [np.fabs(old[i]-new[i]) for i in range(len(old))]\n top = max(top)\n bot = [np.fabs(old[i]) for i in range(len(old))]\n return top/max(bot)\n\ndef newton(eqn,dEqn,guess):\n return guess - eqn(guess)/dEqn(guess)\n\ndef newton2d(one,two, guess):\n xD1 = derivative2dX(one)\n xD2 = derivative2dX(two)\n yD1 = derivative2dY(one)\n yD2 = derivative2dY(two)\n\n J1 = [evaluate2d(xD1,guess), evaluate2d(yD1,guess)]\n J2 = [evaluate2d(xD2,guess), evaluate2d(yD2,guess)]\n\n scalar = 1./(J1[0]*J2[1]-J1[1]*J2[0])\n\n Jinverse = [[scalar*J2[1],-scalar*J1[1]],\n [-scalar*J2[0],scalar*J1[0]]]\n\n f1 = evaluate2d(one,guess)\n f2 = evaluate2d(two, guess)\n\n JIxF1 = Jinverse[0][0]*f1 + Jinverse[0][1]*f2\n JIxF2 = Jinverse[1][0]*f1 + Jinverse[1][1]*f2\n\n return [guess[0]-JIxF1,guess[1]-JIxF2]\n\n" }, { "alpha_fraction": 0.48217055201530457, "alphanum_fraction": 0.5170542597770691, "avg_line_length": 30.463415145874023, "blob_id": "5ebfcee3b77bf843a8e927446ec0684d07fffcea", "content_id": "3e8ea8b13d340d62b90ad7a21c40059e6f01d5d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1290, "license_type": "no_license", "max_line_length": 70, "num_lines": 41, "path": "/hw0/polynomials.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "'''###################################################################\npolynomials.py\n homework for math 400\n last worked on: 1/31/14\n represent a polynomail by a list of lists\n where each inner list has 2 elements, a coefficeint\n and an exponent. The printPoly function requires that\n if there is a constant in the polynomial, it must be the\n last element in the list. The derivative function has the\n same requirement with the additional requirement that if the\n polynomail contians an ax^1 term, it must be the last element\n in the list other than any constants.\n'''###################################################################\n\ntestP = [[4,512],[7,256],[3,1],[1,0]]\n\ndef printPoly(P):\n for i in range(len(P)):\n if P[i][1] > 1 and i < len(P)-1 :\n print(\"%sx^%s +\"%(P[i][0], P[i][1])),\n elif P[i][1] == 1 and i < len(P)-1 :\n print(\"%sx + \"%(P[i][0])),\n elif P[i][1] > 1:\n print(\"%sx^%s\"%(P[i][0], P[i][1])),\n elif P[i][1] == 1:\n print(\"%sx\"%(P[i][0])),\n else:\n print(\"%s\"%(P[i][0])),\n print\n\ndef derivative(P):\n D=[]\n for i in range(len(P)):\n D.append([P[i][0]*P[i][1],P[i][1]-1])\n if D[i][1] == 0:\n break\n return D\n\nprintPoly(testP)\nprintPoly(derivative(testP))\nprintPoly(testP)\n" }, { "alpha_fraction": 0.7636203765869141, "alphanum_fraction": 0.7724077105522156, "avg_line_length": 57.35897445678711, "blob_id": "b7579d39d4ac6cccae87149e8c2621cc581294d6", "content_id": "3c86e020834afca05184908e3dacb15a372a60e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2276, "license_type": "no_license", "max_line_length": 89, "num_lines": 39, "path": "/homework1/prob4.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "from gauss import *\n\nn = [3,5,7,8,10,15,20,25]\nprint 'We will compare the exact inverse of Hilbert matrices of different'\nprint 'sizes with approximate inverses found with basic Gaussian elemination'\nprint 'and partialy scaled Gaussian elemination by subtracting each element'\nprint 'in the approximation from each element in the exact inverse. The closer'\nprint 'the resulting matrix is to the zero matrix, better the approximation was.'\nprint 'Because these matrices are hard to fit on the screen, instead of showing'\nprint 'them we will sum the absolute value of each element in the compare matrix'\nprint 'and divide by the number of elements in the matrix to get an average element'\nprint 'error. We will also show the result of multiplying the approximations with the'\nprint 'Hilbert matrix to see how close to the identy matrix we get. Again '\nprint 'Because it is hard to read these matrices on the screen we will print'\nprint 'the average element error from the identy matrix rather than the matrix'\n\nfor i in n:\n H = populateHilbert(i)\n I = hilbertInverse(i)\n Hb = invertGauss(H)\n Hs = invertScaledGauss(H)\n print '\\n\\t\\tFor size %s'%i\n avgE = avgElement(compareMats(I,Hb))\n avgI = avgElement(compareMats(matMult(H,Hb), createIdentity(i)))\n print 'For basic Gaussian elemination the average element error is: %s'%avgE\n print 'And the approximation times the Hilbert matrix is: %s\\n'%avgI\n\n avgE = avgElement(compareMats(I,Hs))\n avgI = avgElement(compareMats(matMult(H,Hs), createIdentity(i)))\n print 'For partially scaled Gaussian elemination the average element error is: %s'%avgE\n print 'And the approximation times the Hilbert matrix is: %s\\n'%avgI\n\nprint 'All the way up to size 7 the average element error is pretty small but as soon'\nprint 'as we reach size 8, both approximations have huge jumps in their error that keep'\nprint 'getting bigger. By 25 they are HUGE. What is particularly interesting is that'\nprint 'the difference between the identity matrix and the multiple of the approximation'\nprint 'and the Hilbert matrix never gets that big. Under size 15 it seems pretty close.'\nprint 'Even at size 25, the error is much bigger than what is acceptable but compared to'\nprint 'the erros in the approximations themselves, they are nothing'\n" }, { "alpha_fraction": 0.4312267601490021, "alphanum_fraction": 0.4854680597782135, "avg_line_length": 27.180952072143555, "blob_id": "193eae1a066ab4c459bfea9158369f03f1b77069", "content_id": "de8094ec590d596c81b669e89bfbec8226271a55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5918, "license_type": "no_license", "max_line_length": 70, "num_lines": 210, "path": "/homework4/polynomials.py", "repo_name": "aryner/numericalAnalysis", "src_encoding": "UTF-8", "text": "'''###################################################################\npolynomials.py\n update: 5/3/14\n added stuff deal with polynomials having 2 unknowns\n the derivative and evaluate functions make a lot of\n assumptions. Those two should only be used if it is\n known that for all terms the degree of one of the\n variables is <= 1 otherwise who knows i haven't even\n tested for that but I know it wont be good\n\nhomework for math 400\n last worked on: 1/31/14\n represent a polynomail by a list of lists\n where each inner list has 2 elements, a coefficeint\n and an exponent. The printPoly function requires that\n if there is a constant in the polynomial, it must be the\n last element in the list. The derivative function has the\n same requirement with the additional requirement that if the\n polynomail contians an ax^1 term, it must be the last element\n in the list other than any constants.\n'''###################################################################\n\ntestP = [[4,512],[7,256],[3,1],[1,0]]\ntest2d = [[[3,2]],[[-1,2]]]\ntest2d2 = [[[-1,2]],[['3x',2],[-1,0]]]\n\ndef add2d(one,two):\n X=[]\n Y=[]\n xD = []\n yD = []\n for i in range(len(one[0])):\n found = False\n if isinstance(one[0][i][0], (int,long,float,complex)):\n for j in range(len(two[0])):\n if isinstance(two[0][j][0], (int,long,float,complex)):\n if one[0][i][1] == two[0][j][1]:\n X.append([one[0][i][0]+two[0][j][0],one[0][i][1]])\n xD.append(j)\n found=True\n else:\n X.append(two[0][j])\n xD.append(j)\n if found==False:\n X.append(one[0][i])\n else:\n X.append(one[0][i])\n\n for i in range(len(one[1])):\n found = False\n if isinstance(one[1][i][0], (int,long,float,complex)):\n for j in range(len(two[1])):\n if isinstance(two[1][j][0], (int,long,float,complex)):\n if one[1][i][1] == two[1][j][1]:\n Y.append([one[1][i][0]+two[1][j][0],one[1][i][1]])\n yD.append(j)\n found=True\n else:\n Y.append(two[1][j])\n yD.append(j)\n if found==False:\n Y.append(one[1][i])\n else:\n Y.append(one[1][i])\n\n for i in range(len(xD)):\n del two[0][xD[i]]\n for i in range(len(yD)):\n del two[1][yD[i]]\n\n for i in range(len(two[1])):\n Y.append(two[1][i])\n for i in range(len(two[0])):\n X.append(two[0][i])\n return [X,Y]\n\n\n\ndef evaluate2d(P,v):\n sol = 0\n for i in range(len(P[0])):\n if isinstance(P[0][i][0], (int,long,float,complex)):\n sol = sol + P[0][i][0]*v[0]**P[0][i][1]\n else:\n num = 1\n if len(P[0][i][0]) > 1:\n num = float(P[0][i][0][:-1])\n else:\n num = float(P[0][i][0])\n sol = sol + num*v[1]*v[0]**P[0][i][1]\n for i in range(len(P[1])):\n if isinstance(P[1][i][0], (int,long,float,complex)):\n sol = sol + P[1][i][0]*v[1]**P[1][i][1]\n else:\n num = 1\n if len(P[1][i][0]) > 1 :\n num = float(P[1][i][0][:-1])\n else:\n num = float(P[1][i][0])\n sol = sol + num*v[0]*v[1]**P[1][i][1]\n return sol\n\ndef derivative2dX(P):\n X=[]\n Y=[]\n for i in range(len(P[0])):\n if P[0][i][1] != 0:\n if isinstance(P[0][i][0], (int,long,float,complex)):\n X.append([P[0][i][0]*P[0][i][1],P[0][i][1]-1])\n if P[0][i][1] == 0:\n break\n else:\n num = float(P[0][i][0][:-1])\n X.append([str(num*P[0][i][1])+'y',P[0][i][1]-1])\n if P[1][i][1] == 0:\n break\n for i in range(len(P[1])):\n if isinstance(P[1][i][0], (int,long,float,complex)):\n this = 'stub'\n else:\n Y.append([P[1][i][0][:-1],P[1][i][1]])\n return [X,Y]\n\ndef derivative2dY(P):\n X=[]\n Y=[]\n for i in range(len(P[1])):\n if P[1][i][1] != 0:\n if isinstance(P[1][i][0], (int,long,float,complex)):\n Y.append([P[1][i][0]*P[1][i][1],P[1][i][1]-1])\n if P[1][i][1] == 0:\n break\n else:\n num = float(P[1][i][0][:-1])\n Y.append([str(num*P[1][i][1])+'x',P[1][i][1]-1])\n if P[1][i][1] == 0:\n break\n for i in range(len(P[0])):\n if isinstance(P[0][i][0], (int,long,float,complex)):\n this = 'stub'\n else:\n X.append([P[0][i][0][:-1],P[0][i][1]])\n return [X,Y]\n\n\ndef print2d(P):\n for j in range(len(P[0])):\n if P[0][j][1] > 1 and j < len(P[0])-1 :\n print(\"%sx^%s +\"%(P[0][j][0], P[0][j][1])),\n elif P[0][j][1] == 1 and j < len(P[0])-1 :\n print(\"%sx + \"%(P[0][j][0])),\n elif P[0][j][1] > 1:\n print(\"%sx^%s\"%(P[0][j][0], P[0][j][1])),\n elif P[0][j][1] == 1:\n print(\"%sx\"%(P[0][j][0])),\n else:\n print(\"%s\"%(P[0][j][0])),\n\n for j in range(len(P[1])):\n if P[1][j][1] > 1 and j < len(P[0])-1 :\n print(\"%sy^%s +\"%(P[1][j][0], P[1][j][1])),\n elif P[1][j][1] == 1 and j < len(P[1])-1 :\n print(\"%sy + \"%(P[1][j][0])),\n elif P[1][j][1] > 1:\n print(\"%sy^%s\"%(P[1][j][0], P[1][j][1])),\n elif P[1][j][1] == 1:\n print(\"%sy\"%(P[1][j][0])),\n else:\n print(\"%s\"%(P[1][j][0])),\n\ndef printPoly(P):\n for i in range(len(P)):\n if P[i][1] > 1 and i < len(P)-1 :\n print(\"%sx^%s +\"%(P[i][0], P[i][1])),\n elif P[i][1] == 1 and i < len(P)-1 :\n print(\"%sx + \"%(P[i][0])),\n elif P[i][1] > 1:\n print(\"%sx^%s\"%(P[i][0], P[i][1])),\n elif P[i][1] == 1:\n print(\"%sx\"%(P[i][0])),\n else:\n print(\"%s\"%(P[i][0])),\n print\n\ndef derivative(P):\n D=[]\n for i in range(len(P)):\n D.append([P[i][0]*P[i][1],P[i][1]-1])\n if D[i][1] == 0:\n break\n return D\n\n#printPoly(testP)\n#printPoly(derivative(testP))\n#printPoly(testP)\n#print2d(test2d)\n#print \n#print evaluate2d(test2d,[2,2])\n#print2d(derivative2dX(test2d))\n#print\n#print2d(derivative2dY(test2d))\n#print\n#print2d(test2d2)\n#print \n#print evaluate2d(test2d2,[2,2])\n#print2d(derivative2dX(test2d2))\n#print\n#print2d(derivative2dY(test2d2))\n#print\n#print2d(add2d(test2d,test2d2))\n" } ]
19
ramtinsaffarkhorasani/taklif5
https://github.com/ramtinsaffarkhorasani/taklif5
e99b9cff41b36dd20a8a23f6d33e94d05fd60709
22e69f4fcca957728ed85ebea3188146936e3008
3242a7547862677cb42cb44f494278994cd47c53
refs/heads/main
2023-07-07T06:15:34.981601
2021-08-14T14:57:20
2021-08-14T14:57:20
396,022,838
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.38425925374031067, "alphanum_fraction": 0.46759259700775146, "avg_line_length": 13.571428298950195, "blob_id": "781f805b0da94c916835c71aaadb04cbe24fec74", "content_id": "bf3aa0b9f4a2f7622f3232bcdd87380fa90fdfac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "no_license", "max_line_length": 22, "num_lines": 14, "path": "/lacposht.py", "repo_name": "ramtinsaffarkhorasani/taklif5", "src_encoding": "UTF-8", "text": "import turtle\r\na= turtle.Turtle()\r\n \r\nb= 3\r\nc= 70\r\nd = 360.0 / b\r\nfor i in range(1000):\r\n for i in range(b):\r\n a.forward(c)\r\n a.right(d)\r\n b = b+1\r\n c = 70\r\n d = 360.0 / b\r\nturtle.done()" }, { "alpha_fraction": 0.3862803876399994, "alphanum_fraction": 0.42490842938423157, "avg_line_length": 35.5625, "blob_id": "a90de5c1564880052819983df58f1378b586b384", "content_id": "dfd6a8dbb333cf8c7ac9fc7b7b8aee26ba9b2404", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3003, "license_type": "no_license", "max_line_length": 189, "num_lines": 80, "path": "/tictactoe.py", "repo_name": "ramtinsaffarkhorasani/taklif5", "src_encoding": "UTF-8", "text": "import random\r\nanswer=int(input(\"do nafare(1) tak nafare(2) : \"))\r\ndef show_game_board():\r\n for i in range(3):\r\n for j in range(3):\r\n print(game[i][j] , end=' ') \r\n print()\r\ndef check():\r\n if (game[0][0]=='X' and game[0][1]=='X' and game[0][2]=='X') or (game[1][0]=='X' and game[1][1]=='X' and game[1][2]=='X') or (game[2][0]=='X' and game[2][1]=='X' and game[2][2]=='X'):\r\n print(\"nafar aval bord\")\r\n exit()\r\n elif (game[0][0]=='X' and game[1][0]=='X' and game[2][0]=='X') or (game[0][1]=='X' and game[1][1]=='X' and game[2][1]=='X') or (game[0][2]=='X' and game[1][2]=='X' and game[2][2]=='X'):\r\n print(\"nafar dovom board\")\r\n exit() \r\n elif (game[0][0]=='X' and game[1][1]=='X' and game[2][2]=='X') or (game[0][2]=='X' and game[1][1]=='X' and game[2][0]=='X') :\r\n print(\"nafar aval bord\")\r\n exit() \r\n elif (game[0][0]=='O' and game[0][1]=='O' and game[0][2]=='O') or (game[1][0]=='O' and game[1][1]=='O' and game[1][2]=='O') or (game[2][0]=='O' and game[2][1]=='O' and game[2][2]=='O'):\r\n print(\"nafar dovom bord\")\r\n exit() \r\n elif (game[0][0]=='O' and game[1][0]=='O' and game[2][0]=='O') or (game[0][1]=='O' and game[1][1]=='O' and game[2][1]=='O') or (game[0][2]=='O' and game[1][2]=='O' and game[2][2]=='O'):\r\n print(\"nafar dovom bord\")\r\n exit() \r\n elif (game[0][0]=='O' and game[1][1]=='O' and game[2][2]=='O') or (game[0][2]=='O' and game[1][1]=='O' and game[2][0]=='O') :\r\n print(\"nafar dovom bordplayer2 win\")\r\n exit() \r\n\r\n\r\ngame = [['_','_','_'],\r\n ['_','_','_'],\r\n ['_','_','_']]\r\n\r\nshow_game_board() \r\n\r\nwhile True:\r\n\r\n print(\"vared kon:\")\r\n while True:\r\n row=int(input(\"enter the row: \")) \r\n col=int(input(\"enter the clomun \")) \r\n if 0<=row<=2 and 0<=col<=2:\r\n if game[row][col]=='_':\r\n game[row][col] = 'X'\r\n break\r\n else:\r\n print(\"bazi ro glitch nakon\")\r\n break\r\n else:\r\n print(\"index is out of range , Try again!\")\r\n show_game_board()\r\n check() \r\n print(\"vared kon nafar dovom\")\r\n while True:\r\n if answer == \"1\":\r\n row=int(input(\"enter the row\")) \r\n col=int(input(\"enter the clomun\"))\r\n if 0<=row<=2 and 0<=col<=2: \r\n if game[row][col]=='_': \r\n game[row][col] = 'O'\r\n break\r\n else:\r\n print(\"glitch nakon\")\r\n break\r\n \r\n else:\r\n print(\"index is out of range , Try again!\")\r\n show_game_board()\r\n check()\r\n\r\n \r\n print(\"player 2 PC :\")\r\n while True:\r\n if answer == \"2\":\r\n row=random.randint(0,2)\r\n col=random.randint(0,2) \r\n if game[row][col]=='_': \r\n game[row][col] = 'O'\r\n break\r\n show_game_board()\r\n check()" }, { "alpha_fraction": 0.45483872294425964, "alphanum_fraction": 0.48064514994621277, "avg_line_length": 21.846153259277344, "blob_id": "8a6bbc4c5b2ec2ab8830ddf2102c4e7ca8d9bad0", "content_id": "fd457b02c9ebf1bd471e782b5cf284854227ceec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 310, "license_type": "no_license", "max_line_length": 45, "num_lines": 13, "path": "/6.py", "repo_name": "ramtinsaffarkhorasani/taklif5", "src_encoding": "UTF-8", "text": "a=int(input())\r\nb=[[None for i in range(a)]for j in range(a)]\r\nfor i in range(a):\r\n b[i][0]=1\r\nfor i in range(a):\r\n b[i][i]\r\nfor i in range(2,a):\r\n for j in range(a):\r\n b[i][j]=b[i-1][j-1]+b[i-1][j-1]\r\nfor i in range(a):\r\n for j in range(i+1):\r\n print(b[i][j],end=\"\\t\")\r\n print()\r\n" } ]
3
ElenaAfanasyeva/html_generate
https://github.com/ElenaAfanasyeva/html_generate
826d6bb96d5b8282565b091ab829a1f8a13e46f7
87ca23bf632c1af02abdd72b52ce37dd79ad55b8
a34de71e0f1f76f12a58ee4be47850c6e5f50c44
refs/heads/master
2021-01-18T03:24:32.723238
2017-03-27T21:24:18
2017-03-27T21:24:18
85,825,166
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3556250035762787, "alphanum_fraction": 0.37015625834465027, "avg_line_length": 56.657657623291016, "blob_id": "018e87730d1b54f82d441e372bb1d0d5a9b206da", "content_id": "616c35bfa2b69c184e5a5e58aa4d0d655399ab78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6416, "license_type": "no_license", "max_line_length": 142, "num_lines": 111, "path": "/html_generate.py", "repo_name": "ElenaAfanasyeva/html_generate", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\n\n\ndef search_folder_with_script():\n directory = os.path.dirname(os.path.abspath(__file__))\n print directory\n current_folder = ''\n for i in directory:\n if i == '\\\\':\n current_folder = ''\n else:\n current_folder = current_folder + i\n return current_folder\n\n\ndef paste_images_in_folder():\n files = os.listdir(os.path.dirname(os.path.abspath(__file__)))\n images = filter(lambda x: x.endswith('.JPG'), files)\n for i in images:\n AlbumHtmlFile.write(' <article> \\n'\n ' <a class=\"thumbnail\"'\n 'href=\"images/fulls/' + i + '.jpg\"'\n ' data-position=\"left center\"> '\n '<img src=\"images/thumbs/' + i + '.jpg\"'\n ' alt=\"' + i + '\" /></a> \\n' +\n '<h2>Владимир Протас</h2> \\n' +\n '<p>' + i + '</p> \\n'\n ' </article> \\n')\n\n\nAlbumHtmlFile = open('index.html', 'w')\nAlbumHtmlFile.write('<!DOCTYPE HTML> \\n' +\n '<!-- \\n' +\n ' Lens by HTML5 UP \\n' +\n ' html5up.net | @n33co \\n' +\n ' Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)\\n' +\n '--> \\n' +\n '<html> \\n' +\n ' <head> \\n' +\n ' <title>' +\n search_folder_with_script() +\n ' | Vladimir Protas - famous Ukrainian sculptor </title> \\n' +\n ' <meta charset=\"utf-8\" /> \\n' +\n ' meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> \\n' +\n ' <!--[if lte IE 8]><script src=\"assets/js/ie/html5shiv.js\"></script><![endif]--> \\n' +\n ' <link rel=\"stylesheet\" href=\"assets/css/main.css\" /> \\n' +\n ' <!--[if lte IE 8]><link rel=\"stylesheet\" href=\"assets/css/ie8.css\" /><![endif]--> \\n' +\n ' <!--[if lte IE 9]><link rel=\"stylesheet\" href=\"assets/css/ie9.css\" /><![endif]--> \\n' +\n ' <noscript><link rel=\"stylesheet\" href=\"assets/css/noscript.css\" /></noscript> \\n' +\n ' </head> \\n' +\n ' <body class=\"is-loading-0 is-loading-1 is-loading-2\"> \\n' +\n '\\n' +\n ' <!-- Main --> \\n' +\n ' <div id=\"main\"> \\n' +\n '\\n' +\n ' <!-- Header --> \\n' +\n ' <header id=\"header\"> \\n' +\n ' <h1>' +\n search_folder_with_script() +\n '</h1> \\n' +\n ' <p><a href=\"../cv-rus.html\" target=\"_blank\">Про меня</a> |'\n '<a href=\"../cv.html\" target=\"_blank\">About me</a> |'\n '<noindex>'\n '<a href=\"http://www.facebook.com/profile.php?id=100002194797317\" target=\"_blank\" rel=\"nofollow\">Facebook Profile</a> |'\n ' <a href=\"http://www.facebook.com/home.php?sk=group_198239200217172\" target=\"_blank\" rel=\"nofollow\">Facebook Group</a> |'\n '<a href=\"../index.html\" target=\"_blank\">На главную</a> </p> \\n' +\n ' </header> \\n' +\n ' <!-- Thumbnail -->\\n' +\n ' <section id=\"thumbnails\">\\n')\npaste_images_in_folder()\nAlbumHtmlFile.write(' </section> \\n'\n ' <!-- Footer --> \\n'\n ' <footer id=\"footer\"> \\n'\n ' <ul class=\"copyright\"> \\n'\n ' <li>Copyright Protas V.N. &copy; 2010-2017</li></li> \\n'\n ' </ul> \\n'\n ' </footer> \\n \\n'\n ' </div> \\n \\n'\n ' <!-- hit.ua --> \\n'\n ''' <a href='http://hit.ua/?x=68914' target='_blank'> \\n'''\n ' <script language=\"javascript\" type=\"text/javascript\"><!-- \\n'\n ' Cd=document;Cr=\"&\"+Math.random();Cp=\"&s=1\"; \\n'\n ' Cd.cookie=\"b=b\";if(Cd.cookie)Cp+=\"&c=1\"; \\n'\n ' Cp+=\"&t=\"+(new Date()).getTimezoneOffset(); \\n'\n '\t\t\tif(self!=top)Cp+=\"&f=1\"; \\n'\n ' //--></script> \\n'\n ' <script language=\"javascript1.1\" type=\"text/javascript\"><!-- \\n'\n ' if(navigator.javaEnabled())Cp+=\"&j=1\";\\n'\n ' //--></script> \\n'\n ' <script language=\"javascript1.2\" type=\"text/javascript\"><!--\\n'\n ' if(typeof(screen)!='\"'undefined'\"')Cp+=\"&w=\"+screen.width+\"&h=\"+ \\n'\n ' screen.height+\"&d=\"+(screen.colorDepth?screen.colorDepth:screen.pixelDepth); \\n'\n ' //--></script> \\n'\n ' <script language=\"javascript\" type=\"text/javascript\"><!-- \\n'\n ''' Cd.write(\"<img src='http://c.hit.ua/hit?i=68914&g=0&x=2\"+Cp+Cr+\n \"&r=\" + escape(Cd.referrer) + \"&u=\" + escape(window.location.href) +\n \"' border='0' wi\"+\"dth='1' he\"+\"ight='1'/>\");\n //--></script>\n <noscript><img src='http://c.hit.ua/hit?i=68914&amp;g=0&amp;x=2' border='0'/>\n\n </noscript></a>\n <!-- / hit.ua -->'''\n ' <!-- Scripts --> \\n'\n ' <script src=\"assets/js/jquery.min.js\"></script> \\n'\n ' <script src=\"assets/js/skel.min.js\"></script> \\n'\n ' <!--[if lte IE 8]><script src=\"assets/js/ie/respond.min.js\"></script><![endif]--> \\n'\n ' <script src=\"assets/js/main.js\"></script> \\n'\n ' </body> \\n'\n '</html>')\nAlbumHtmlFile.close()\n" } ]
1
eni65/CFG-session-3-
https://github.com/eni65/CFG-session-3-
6cfd63abaad30eaefdfc8dfd2185618a221fa876
1beb6312bbcb4bcfd56ba52edc857d8557eb8363
02c0fb0fde22627a2b247a56c073ece812f8133c
refs/heads/master
2020-04-03T22:30:20.930249
2018-10-31T19:15:33
2018-10-31T19:15:33
155,604,736
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7631579041481018, "alphanum_fraction": 0.7631579041481018, "avg_line_length": 37, "blob_id": "09103231e0fd8def1aa01a42cc41ed694daf5517", "content_id": "1bfd03cd49e2e5e2aa07301be3cf1e6cdf540eaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 38, "license_type": "no_license", "max_line_length": 37, "num_lines": 1, "path": "/new python file.py", "repo_name": "eni65/CFG-session-3-", "src_encoding": "UTF-8", "text": "print 'Hello this is the python file'\n" } ]
1
Music-AMG/animation_nodes
https://github.com/Music-AMG/animation_nodes
aa1cb6b46a6d0ec8b9e30cb9308c5ea231e7a9c4
8ff9b9bbcf774841f8bd7705afb93ce0c70714ac
7d033e6899a68a67083e49f0fb3bd38e1063b1ad
refs/heads/master
2021-01-17T23:35:06.124217
2015-10-31T17:13:55
2015-10-31T17:13:55
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6245426535606384, "alphanum_fraction": 0.6290459036827087, "avg_line_length": 40.79999923706055, "blob_id": "afdcfb0d051525e256f1272df865436ec0012fcd", "content_id": "07d919a347def109aa102a05f8d623763c13e0e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3553, "license_type": "no_license", "max_line_length": 103, "num_lines": 85, "path": "/nodes/rotation/convert_rotations.py", "repo_name": "Music-AMG/animation_nodes", "src_encoding": "UTF-8", "text": "import bpy\nfrom bpy.props import *\nfrom ... tree_info import keepNodeLinks\nfrom ... events import executionCodeChanged\nfrom ... base_types.node import AnimationNode\n\nconversionTypeItems = [\n (\"QUATERNION_TO_EULER\", \"Quaternion to Euler\", \"\", \"NONE\", 0),\n (\"EULER_TO_QUATERNION\", \"Euler to Quaternion\", \"\", \"NONE\", 1),\n (\"QUATERNION_TO_MATRIX\", \"Quaternion to Matrix\", \"\", \"NONE\", 2),\n (\"MATRIX_TO_QUATERNION\", \"Matrix to Quaternion\", \"\", \"NONE\", 3),\n (\"EULER_TO_MATRIX\", \"Euler to Matrix\", \"\", \"NONE\", 4),\n (\"MATRIX_TO_EULER\", \"Matrix to Euler\", \"\", \"NONE\", 5)]\n\nclass ConvertRotationsNode(bpy.types.Node, AnimationNode):\n bl_idname = \"an_ConvertRotationsNode\"\n bl_label = \"Convert Rotations\"\n\n onlySearchTags = True\n searchTags = [(name, {\"conversionType\" : repr(type)}) for type, name, _,_,_ in conversionTypeItems]\n\n def conversionTypeChanged(self, context):\n self.createSockets()\n executionCodeChanged()\n\n conversionType = EnumProperty(name = \"Conversion Type\", default = \"QUATERNION_TO_EULER\",\n items = conversionTypeItems, update = conversionTypeChanged)\n\n def create(self):\n self.width = 160\n self.conversionType = \"QUATERNION_TO_EULER\"\n\n def draw(self, layout):\n layout.prop(self, \"conversionType\", text = \"\")\n\n def drawLabel(self):\n for item in conversionTypeItems:\n if self.conversionType == item[0]: return item[1]\n\n def getExecutionCode(self):\n if self.conversionType == \"QUATERNION_TO_EULER\":\n return \"euler = quaternion.to_euler('XYZ')\"\n if self.conversionType == \"EULER_TO_QUATERNION\":\n return \"quaternion = euler.to_quaternion()\"\n\n if self.conversionType == \"QUATERNION_TO_MATRIX\":\n return \"matrix = quaternion.to_matrix().to_4x4()\"\n if self.conversionType == \"MATRIX_TO_QUATERNION\":\n return \"quaternion = matrix.to_quaternion()\"\n\n if self.conversionType == \"EULER_TO_MATRIX\":\n return \"matrix = euler.to_matrix().to_4x4()\"\n if self.conversionType == \"MATRIX_TO_EULER\":\n return \"euler = matrix.to_euler('XYZ')\"\n\n def getUsedModules(self):\n return [\"mathutils\"]\n\n @keepNodeLinks\n def createSockets(self):\n self.inputs.clear()\n self.outputs.clear()\n\n if self.conversionType == \"QUATERNION_TO_EULER\":\n self.inputs.new(\"an_QuaternionSocket\", \"Quaternion\", \"quaternion\")\n self.outputs.new(\"an_EulerSocket\", \"Euler\", \"euler\")\n if self.conversionType == \"EULER_TO_QUATERNION\":\n self.inputs.new(\"an_EulerSocket\", \"Euler\", \"euler\")\n self.outputs.new(\"an_QuaternionSocket\", \"Quaternion\", \"quaternion\")\n\n if self.conversionType == \"QUATERNION_TO_MATRIX\":\n self.inputs.new(\"an_QuaternionSocket\", \"Quaternion\", \"quaternion\")\n self.outputs.new(\"an_MatrixSocket\", \"Matrix\", \"matrix\")\n if self.conversionType == \"MATRIX_TO_QUATERNION\":\n self.inputs.new(\"an_MatrixSocket\", \"Matrix\", \"matrix\")\n self.outputs.new(\"an_QuaternionSocket\", \"Quaternion\", \"quaternion\")\n\n if self.conversionType == \"EULER_TO_MATRIX\":\n self.inputs.new(\"an_EulerSocket\", \"Euler\", \"euler\")\n self.outputs.new(\"an_MatrixSocket\", \"Matrix\", \"matrix\")\n if self.conversionType == \"MATRIX_TO_EULER\":\n self.inputs.new(\"an_MatrixSocket\", \"Matrix\", \"matrix\")\n self.outputs.new(\"an_EulerSocket\", \"Euler\", \"euler\")\n\n self.inputs[0].defaultDrawType = \"PREFER_PROPERTY\"\n" } ]
1
ivanacvetkoski/classification-tmd
https://github.com/ivanacvetkoski/classification-tmd
1e7e831b8edd25812d74d9ffa0a98762afb38218
f0b4fdc127253da52bf60ba41e85d747ab972773
c042cb3dae6bd305445d457677f9f9c83db07d85
refs/heads/master
2021-04-18T09:33:51.571670
2020-03-23T20:10:04
2020-03-23T20:10:04
249,530,226
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8231707215309143, "alphanum_fraction": 0.8262194991111755, "avg_line_length": 81, "blob_id": "99445e1807a1b243081a4a592013bc09d70642eb", "content_id": "c229c3654574b57125a17060be1ff5ae7f08dcb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 328, "license_type": "no_license", "max_line_length": 217, "num_lines": 4, "path": "/README.md", "repo_name": "ivanacvetkoski/classification-tmd", "src_encoding": "UTF-8", "text": "# classification-tmd\nKlasifikacija \nNa osnovu vrednosti koje su zabelezili devet senzora u pametnim telefonima, klasifikujemo podatke prema vrsti transporta u sledece kategorije autobus, voz, automobil, hodanje i mirovanje. Podaci su preuzeti sa adrese:\nhttps://www.kaggle.com/fschwartzer/tmd-dataset-5-seconds-sliding-window.\n" }, { "alpha_fraction": 0.672099232673645, "alphanum_fraction": 0.6855268478393555, "avg_line_length": 33.867645263671875, "blob_id": "580b6b9cd2572f51a51831e5510c2390e52be931", "content_id": "f33df81a46ce531292875ae3c129eb8c816b3398", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9756, "license_type": "no_license", "max_line_length": 175, "num_lines": 272, "path": "/tmd.py", "repo_name": "ivanacvetkoski/classification-tmd", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nfrom sklearn.model_selection import train_test_split, GridSearchCV\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.naive_bayes import GaussianNB, BernoulliNB\r\nfrom sklearn.metrics import classification_report\r\nimport sklearn.preprocessing as prep\r\nimport numpy as np\r\nimport sklearn.metrics as met\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n#Ucitavamo podatke i skracujemo imena atributima\r\ndf=pd.read_csv('dataset.csv')\r\ndf.columns = df.columns.str.replace('android.sensor.','').str.replace('#','_')\r\n\r\nprint('Informacije o bazi')\r\nprint(df.info())\r\nprint('Prvih 5 istanci')\r\nprint(df.head())\r\n\r\ndf=df.dropna()\r\ndf=df.drop_duplicates()\r\n\r\n#Resavamo se outliers-a\r\ndf_x=df.drop(df.columns[-1],axis=1)\r\ndf_y=df[df.columns[-1]]\r\nQ1 = df_x.quantile(0.25)\r\nQ3 = df_x.quantile(0.75)\r\nIQR = Q3 - Q1\r\nv=1.5\r\n\r\ndf_no_out_x=df_x[~((df_x < (Q1 - v*IQR)) | (df_x > (Q3 + v*IQR))).any(axis=1)]\r\ndf_no_out_y=df_y[~((df_x < (Q1 - v*IQR)) | (df_x > (Q3 + v*IQR))).any(axis=1)]\r\n\r\nnew_idxs=pd.RangeIndex(len(df_no_out_y.index))\r\ndf_no_out_x.index=new_idxs\r\ndf_no_out_y.index=new_idxs\r\n\r\ndf_no_out=pd.concat([df_no_out_x,df_no_out_y], axis=1)\r\n\r\n#Preko korelacije smanjujemo dimenziju baze\r\n#ovaj deo je preuzet sa interneta\r\n\r\ncormatrix=df.corr()\r\n#fig, ax = plt.subplots(figsize=(16, 8))\r\n#sns.heatmap(cormatrix, annot=True ,square=True)\r\n#plt.show()\r\n\r\n#Atributi sa korelacijom manjom od p\r\np = 0.5\r\nvar = []\r\nfor i in cormatrix.columns:\r\n for j in cormatrix.columns:\r\n if(i!=j):\r\n if np.abs(cormatrix[i][j]) > p:\r\n var.append([i,j])\r\n\r\nupper = cormatrix.where(np.triu(np.ones(cormatrix.shape), k=1).astype(np.bool))\r\n\r\n#Nadji indekse sa korelacijom vecom od c\r\nc=0.5\r\nto_drop = [column for column in upper.columns if any(abs(upper[column]) > c)]\r\n#Izbaci atribute\r\ndata_less_cor=df.drop(to_drop, axis=1)\r\n\r\ncormatrix_less_cor=data_less_cor.corr()\r\nfig, ax = plt.subplots(figsize=(16, 8))\r\nsns.heatmap(cormatrix_less_cor, annot=True ,square=True)\r\nplt.show()\r\n#do ovog dela je preuzeto\r\n\r\n#Poredicemo preciznost razlicitih algoritama nad podacima sa outliers-ima koje nismo ni normalizovani ni standardizovali,\r\n# sa outliers-ima koje jesmo normalizovani i standardizovali,\r\n# bez outliers-a koje jesmo normalizovani i standardizovali,\r\n# sa smanjenim brojem atributa sa outliers-ima i bez njih\r\n\r\nfeatures=df.columns[:37].tolist()\r\nx_without_prep=df[features]\r\ny_without_prep=df['target']\r\n\r\nx=df[features]\r\ny=df['target']\r\nx=pd.DataFrame(prep.MinMaxScaler().fit_transform(x))\r\nx=pd.DataFrame(prep.StandardScaler().fit_transform(x))\r\nx.columns = features\r\n\r\nx_no_out=df_no_out[features]\r\ny_no_out=df_no_out['target']\r\nx_no_out=pd.DataFrame(prep.MinMaxScaler().fit_transform(x_no_out))\r\nx_no_out=pd.DataFrame(prep.StandardScaler().fit_transform(x_no_out))\r\nx_no_out.columns = features\r\n\r\n\r\nfeatures_cor=data_less_cor.columns[:12].tolist()\r\nx_cor=data_less_cor[features_cor]\r\ny_cor=data_less_cor['target']\r\nx_cor=pd.DataFrame(prep.MinMaxScaler().fit_transform(x_cor))\r\nx_cor=pd.DataFrame(prep.StandardScaler().fit_transform(x_cor))\r\nx_cor.columns = features_cor\r\n\r\n#Ovaj deo se ponavlja samo sada uklanjamo outliers-e manjoj dimenziji\r\ndf_x2=data_less_cor.drop(data_less_cor.columns[-1],axis=1)\r\ndf_y2=data_less_cor[data_less_cor.columns[-1]]\r\nQ1_2 = df_x2.quantile(0.25)\r\nQ3_2 = df_x2.quantile(0.75)\r\nIQR_2 = Q3_2 - Q1_2\r\nv=1.5\r\n\r\ndata_less_cor_no_out_x=df_x2[~((df_x2 < (Q1_2 - v*IQR_2)) | (df_x2 > (Q3_2 + v*IQR_2))).any(axis=1)]\r\ndata_less_cor_no_out_y=df_y2[~((df_x2 < (Q1_2 - v*IQR_2)) | (df_x2 > (Q3_2 + v*IQR_2))).any(axis=1)]\r\n\r\nnew_idxs2=pd.RangeIndex(len(data_less_cor_no_out_y.index))\r\ndata_less_cor_no_out_x.index=new_idxs2\r\ndata_less_cor_no_out_y.index=new_idxs2\r\n\r\ndata_less_corr_no_out=pd.concat([data_less_cor_no_out_x,data_less_cor_no_out_y], axis=1)\r\n\r\nx_no_out2=data_less_corr_no_out[features_cor]\r\ny_no_out2=data_less_corr_no_out['target']\r\nx_no_out2=pd.DataFrame(prep.MinMaxScaler().fit_transform(x_no_out2))\r\nx_no_out2=pd.DataFrame(prep.StandardScaler().fit_transform(x_no_out2))\r\nx_no_out2.columns = features_cor\r\n\r\n\r\nx_without_prep_train, x_without_prep_test, y_without_prep_train, y_without_prep_test= train_test_split(x_without_prep, y_without_prep, train_size=0.7, stratify=y_without_prep)\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.7, stratify=y)\r\nx_train_no_out, x_test_no_out, y_train_no_out, y_test_no_out = train_test_split(x_no_out, y_no_out, train_size=0.7, stratify=y_no_out)\r\nx_train_cor, x_test_cor, y_train_cor, y_test_cor = train_test_split(x_cor, y_cor, train_size=0.7, stratify=y_cor)\r\nx_train_no_out2, x_test_no_out2, y_train_no_out2, y_test_no_out2 = train_test_split(x_no_out2, y_no_out2, train_size=0.7, stratify=y_no_out2)\r\n\r\n#Unakrsna validacija koju cemo koristiti za KNN\r\ndef cross_validation(algorithm, parameters, scores, x_train, y_train, x_test, y_test):\r\n\r\n for score in scores:\r\n print(\"Mera \", score)\r\n\r\n clf = GridSearchCV(algorithm, parameters, cv=10, scoring='%s_macro' % score)\r\n clf.fit(x_train, y_train)\r\n\r\n print(\"Najbolji parametri:\")\r\n print(clf.best_params_)\r\n\r\n print(\"Izvestaj za test skup:\")\r\n y_true, y_pred = y_test, clf.predict(x_test)\r\n print(classification_report(y_true, y_pred))\r\n\r\n\r\n y_pred = clf.predict(x_test)\r\n cnf_matrix = met.confusion_matrix(y_test, y_pred)\r\n print(\"Matrica konfuzije\", cnf_matrix, sep=\"\\n\")\r\n\r\n print(\"\\n\")\r\n acc = met.accuracy_score(y_test, y_pred)\r\n print(\"Preciznost\", acc)\r\n print(\"\\n\")\r\n\r\n#KNN\r\ndef knn(x_train_, y_train_, x_test_, y_test_):\r\n param = [{'n_neighbors': range(3, 15),\r\n 'p': [1, 2],\r\n 'weights': ['uniform', 'distance'],\r\n }]\r\n\r\n scores = ['precision', 'f1']\r\n cross_validation(KNeighborsClassifier(), param, scores, x_train_, y_train_, x_test_, y_test_)\r\n\r\n\r\n#Naivni Bajes\r\ndef g_nayve_bayes(x_train, y_train, x_test, y_test):\r\n clf_gnb = GaussianNB()\r\n clf_gnb.fit(x_train, y_train)\r\n\r\n y_pred = clf_gnb.predict(x_test)\r\n\r\n cnf_matrix = met.confusion_matrix(y_test, y_pred)\r\n print(\"Matrica konfuzije\", cnf_matrix, sep=\"\\n\")\r\n print(\"\\n\")\r\n\r\n acc = met.accuracy_score(y_test, y_pred)\r\n print(\"Preciznost\", acc)\r\n print(\"\\n\")\r\n\r\n class_report = met.classification_report(y_test, y_pred, target_names=df[\"target\"].unique())\r\n print(\"Izvestaj klasifikacije\", class_report, sep=\"\\n\")\r\n\r\n\r\ndef b_nayve_bayes(x_train, y_train, x_test, y_test):\r\n clf_gnb = BernoulliNB()\r\n clf_gnb.fit(x_train, y_train)\r\n\r\n y_pred = clf_gnb.predict(x_test)\r\n\r\n cnf_matrix = met.confusion_matrix(y_test, y_pred)\r\n print(\"Matrica konfuzije\", cnf_matrix, sep=\"\\n\")\r\n print(\"\\n\")\r\n\r\n acc = met.accuracy_score(y_test, y_pred)\r\n print(\"Preciznost\", acc)\r\n print(\"\\n\")\r\n\r\n class_report = met.classification_report(y_test, y_pred, target_names=df[\"target\"].unique())\r\n print(\"Izvestaj klasifikacije\", class_report, sep=\"\\n\")\r\n\r\nprint()\r\nprint('KNN nad nesredjenim podacima') #nisu normalizovani ni standardizovani\r\nprint()\r\nknn(x_without_prep_train, y_without_prep_train, x_without_prep_test, y_without_prep_test)\r\n\r\nprint('KNN nad normalizovanim i standardizovanim podacima')\r\nprint()\r\nknn(x_train, y_train, x_test, y_test)\r\n\r\nprint('KNN nad normalizovanim i standardizovanim podacima bez outlier-a')\r\nprint()\r\nknn(x_train_no_out, y_train_no_out, x_test_no_out, y_test_no_out)\r\n\r\nprint('KNN nad normalizovanim i standardizovanim podacima kojima je smanjena dimenzija')\r\nprint()\r\nknn(x_train_cor, y_train_cor, x_test_cor, y_test_cor)\r\n\r\n\r\nprint('KNN nad normalizovanim i standardizovanim podacima kojima je smanjena dimenzija i iz kojih su izbaceni outliers-i')\r\nprint()\r\nknn(x_train_no_out2, y_train_no_out2, x_test_no_out2, y_test_no_out2)\r\n\r\n\r\nprint()\r\n\r\nprint('Gaussian Nayve Bayes nad nesredjenim podacima') #nisu normalizovani ni standardizovani\r\nprint()\r\ng_nayve_bayes(x_without_prep_train, y_without_prep_train, x_without_prep_test, y_without_prep_test)\r\n\r\nprint('Gaussian Nayve Bayes nad normalizovanim i standardizovanim podacima')\r\nprint()\r\ng_nayve_bayes(x_train, y_train, x_test, y_test)\r\n\r\nprint('Gaussian Nayve Bayes nad normalizovanim i standardizovanim podacima bez outlier-a')\r\nprint()\r\ng_nayve_bayes(x_train_no_out, y_train_no_out, x_test_no_out, y_test_no_out)\r\n\r\nprint('Gaussian Nayve Bayes nad normalizovanim i standardizovanim podacima kojima je smanjena dimenzija')\r\nprint()\r\ng_nayve_bayes(x_train_cor, y_train_cor, x_test_cor, y_test_cor)\r\n\r\n\r\nprint('Gaussian Nayve Bayes nad normalizovanim i standardizovanim podacima kojima je smanjena dimenzija i iz kojih su izbaceni outliers-i')\r\nprint()\r\ng_nayve_bayes(x_train_no_out2, y_train_no_out2, x_test_no_out2, y_test_no_out2)\r\n\r\nprint()\r\nprint('Bernoulli Nayve Bayes nad nesredjenim podacima') #nisu normalizovani ni standardizovani\r\nprint()\r\nb_nayve_bayes(x_without_prep_train, y_without_prep_train, x_without_prep_test, y_without_prep_test)\r\n\r\nprint('Bernoulli Nayve Bayes nad normalizovanim i standardizovanim podacima')\r\nprint()\r\nb_nayve_bayes(x_train, y_train, x_test, y_test)\r\n\r\nprint('Bernoulli Nayve Bayes nad normalizovanim i standardizovanim podacima bez outlier-a')\r\nprint()\r\nb_nayve_bayes(x_train_no_out, y_train_no_out, x_test_no_out, y_test_no_out)\r\n\r\nprint('Bernoulli Nayve Bayes nad normalizovanim i standardizovanim podacima kojima je smanjena dimenzija')\r\nprint()\r\nb_nayve_bayes(x_train_cor, y_train_cor, x_test_cor, y_test_cor)\r\n\r\n\r\nprint('Bernoulli Nayve Bayes nad normalizovanim i standardizovanim podacima kojima je smanjena dimenzija i iz kojih su izbaceni outliers-i')\r\nprint()\r\nb_nayve_bayes(x_train_no_out2, y_train_no_out2, x_test_no_out2, y_test_no_out2)\r\n" } ]
2
jonathanKingston/tls-canary
https://github.com/jonathanKingston/tls-canary
7cc10ebfc4cd5d413ebf9e02481d0c369b5211eb
09e0f545c7d5cf019b1527c11695cf3392cf262e
f42ed94f7dc1cbc713c8044e16832cba78be2db6
refs/heads/master
2021-01-22T07:47:13.605690
2017-02-03T00:12:34
2017-02-03T00:12:34
81,846,193
0
0
null
2017-02-13T16:32:01
2017-01-11T18:41:39
2017-02-03T00:12:35
null
[ { "alpha_fraction": 0.6103351712226868, "alphanum_fraction": 0.6452513933181763, "avg_line_length": 25.518518447875977, "blob_id": "383ecf676c6b7a88f5ea03378db45f0e5bd17e1a", "content_id": "8afdbb1aa55e1f48b9f3c28e9ad8fdfd124d2fd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1432, "license_type": "no_license", "max_line_length": 90, "num_lines": 54, "path": "/template/js/Utility.js", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "function Utility() {}\n\nUtility.createElement = function ( element, attributeArray) {\n var node = document.createElement(element);\n if (attributeArray !== undefined) {\n for (var i=0;i<attributeArray.length;i++) {\n for (var attribute in attributeArray[i]) {\n var a = document.createAttribute(attribute);\n a.value = attributeArray[i][attribute];\n node.setAttributeNode(a);\n }\n }\n }\n return node;\n};\n\nUtility.appendChildren = function(nodes) {\n var parentNode = arguments[0];\n for (var i=1;i<arguments.length;i++) {\n parentNode.appendChild(arguments[i]);\n }\n return parentNode;\n};\n\nfunction decodeEntities(s){\n var str, temp= document.createElement('p');\n temp.innerHTML= s;\n str= temp.textContent || temp.innerText;\n temp=null;\n return str;\n}\n\n// Credit here goes to http://krazydad.com/tutorials/makecolors.php\nfunction byte2Hex(n) {\n var nybHexString = \"0123456789ABCDEF\";\n return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);\n}\n\nfunction RGB2Color(r,g,b) {\n return '#' + byte2Hex(r) + byte2Hex(g) + byte2Hex(b);\n}\n\nfunction returnColorArray (n) {\n var a = [];\n var frequency = 0.3;\n for (var i = 0; i < n; ++i) {\n var red = Math.sin(frequency*i + 0) * 127 + 128;\n var green = Math.sin(frequency*i + 2) * 127 + 128;\n var blue = Math.sin(frequency*i + 4) * 127 + 128;\n\n a.push (RGB2Color(red,green,blue));\n }\n return a;\n}\n" }, { "alpha_fraction": 0.5502304434776306, "alphanum_fraction": 0.5600614547729492, "avg_line_length": 37.761905670166016, "blob_id": "b9804f71e9d01883958c3ad43059394d1b853086", "content_id": "31eea882c281806c616559f44896ec0c3f0fb9fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3255, "license_type": "no_license", "max_line_length": 93, "num_lines": 84, "path": "/firefox_app.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport ConfigParser\nimport glob\nimport os\n\n\nclass FirefoxApp(object):\n \"\"\"Class holding information about an extracted Firefox application directory\"\"\"\n\n __locations = {\n \"osx\": {\n \"base\": \"Firefox*.app\",\n \"exe\": os.path.join(\"Contents\", \"MacOS\", \"firefox\"),\n \"browser\": os.path.join(\"Contents\", \"Resources\", \"browser\"),\n \"ini\": os.path.join(\"Contents\", \"Resources\", \"application.ini\"),\n },\n \"linux\": {\n \"base\": \"firefox\",\n \"exe\": \"firefox\",\n \"browser\": \"browser\",\n \"ini\": \"application.ini\",\n },\n \"win\": {\n \"base\": \"core\",\n \"exe\": \"firefox.exe\",\n \"browser\": \"browser\",\n \"ini\": \"application.ini\",\n },\n }\n\n def __init__(self, directory):\n\n # Assuming that directory points to a directory\n # where a stock Firefox archive was extracted.\n self.platform = None\n self.app_dir = None\n for platform in self.__locations:\n base = self.__locations[platform][\"base\"]\n matches = glob.glob(os.path.join(directory, base))\n if len(matches) == 0:\n continue\n elif len(matches) == 1:\n if os.path.isdir(matches[0]):\n self.platform = platform\n self.app_dir = matches[0]\n break\n raise Exception(\"Unsupported application package format (missing base folder)\")\n\n if self.platform is None:\n raise Exception(\"Unsupported application package platform\")\n\n # Fill in the rest of the package locations\n self.exe = os.path.join(self.app_dir, self.__locations[self.platform][\"exe\"])\n self.browser = os.path.join(self.app_dir, self.__locations[self.platform][\"browser\"])\n self.app_ini = os.path.join(self.app_dir, self.__locations[self.platform][\"ini\"])\n\n # Sanity checks\n if not os.path.isfile(self.exe) or not os.path.isdir(self.browser):\n raise Exception(\"Unsupported application package format (missing files)\")\n\n # For `linux`: byte 4 in ELF header is 01/02 for 32/64 bit\n # TODO: detect 32/64 bit for win\n if self.platform == \"linux\":\n with open(self.exe) as f:\n head = f.read(5)\n if head[4] == '\\x01':\n self.platform = \"linux32\"\n elif head[4] == '\\x02':\n self.platform = \"linux\"\n else:\n raise Exception(\"Unsupported ELF binary (%s)\" % ord(head[4]))\n\n # Determine Firefox version\n ini_parser = ConfigParser.SafeConfigParser()\n ini_parser.read(self.app_ini)\n self.version = ini_parser.get(\"App\", \"Version\")\n # For versions that have no `CodeName` specified, extract it from the repo name.\n try:\n self.release = ini_parser.get(\"App\", \"CodeName\")\n except ConfigParser.NoOptionError:\n self.release = ini_parser.get(\"App\", \"sourcerepository\").split(\"-\")[-1]" }, { "alpha_fraction": 0.5609756112098694, "alphanum_fraction": 0.5652797818183899, "avg_line_length": 32.590362548828125, "blob_id": "d910c963bd5bb5125a040e6e729219ec381b9e32", "content_id": "feed3d9c879b04632e6d6ae869c4205d457fdbff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2788, "license_type": "no_license", "max_line_length": 106, "num_lines": 83, "path": "/cache.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport logging\nimport os\nfrom shutil import rmtree\nfrom time import time\n\nlogger = logging.getLogger(__name__)\n\n\nclass DiskCache(object):\n\n def __init__(self, root_directory, maximum_age=24*60*60, purge=False):\n global logger\n self.__root = os.path.abspath(root_directory)\n self.__maximum_age = maximum_age\n if not os.path.exists(self.__root):\n logger.debug('Creating cache directory %s' % self.__root)\n os.mkdir(self.__root) # Assumes existing root workdir\n if purge:\n self.purge()\n\n def list(self):\n \"\"\"Return list of IDs in cache\"\"\"\n return os.listdir(self.__root)\n\n def __clear(self):\n \"\"\"Remove all entries from cache directory\"\"\"\n global logger\n logger.debug(\"Clearing cache directory `%s`\" % self.__root)\n for cache_id in self:\n path = self[cache_id]\n if os.path.isdir(path):\n rmtree(path)\n else:\n os.remove(path)\n\n def delete(self, id_or_path=None):\n \"\"\"\n Delete cache entries by ID or full path.\n Delete everything if no ID or path given.\n \"\"\"\n if id_or_path is None:\n self.__clear()\n return\n path = self[id_or_path.lstrip(self.__root)]\n if os.path.isdir(path):\n rmtree(path)\n elif os.path.exists(path):\n os.remove(path)\n\n def purge(self, maximum_age=None):\n \"\"\"Remove stale entries from cache directory\"\"\"\n global logger\n logger.debug(\"Purging stale cache entries from `%s`\" % self.__root)\n if maximum_age is None:\n maximum_age = self.__maximum_age\n now = time() # Current time as epoch\n stale_limit = now - maximum_age\n for cache_id in self:\n path = self[cache_id]\n mtime = os.path.getmtime(path) # Modification time as epoch (might have just 1.0s resolution)\n if mtime < stale_limit:\n logger.debug('Purging stale cache entry `%s`' % cache_id)\n if os.path.isdir(path):\n rmtree(path)\n else:\n os.remove(path)\n\n def __iter__(self):\n \"\"\"Iterate IDs of cache entries\"\"\"\n for name in self.list():\n yield name\n\n def __contains__(self, cache_id):\n \"\"\"Check for presence of ID in cache\"\"\"\n return cache_id in self.list()\n\n def __getitem__(self, cache_id):\n \"\"\"Return full path of cache entry (existing or not)\"\"\"\n return os.path.join(self.__root, cache_id)\n" }, { "alpha_fraction": 0.6999316215515137, "alphanum_fraction": 0.7047163248062134, "avg_line_length": 37, "blob_id": "a2f98881adf7c7409b5ccbdbbb9bceb6fb110bb7", "content_id": "9779551810940fc7b031f230460c00e7aef4175b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2926, "license_type": "no_license", "max_line_length": 91, "num_lines": 77, "path": "/tests/firefox_extractor_test.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom distutils.spawn import find_executable\nfrom nose import SkipTest\nfrom nose.tools import *\nimport os\nimport shutil\nimport tempfile\n\nimport firefox_extractor as fe\nimport firefox_app as fa\n\n\ntest_dir = os.path.split(__file__)[0]\ntmp_dir = None\n\n\ndef test_setup():\n \"\"\"set up test fixtures\"\"\"\n global tmp_dir\n tmp_dir = tempfile.mkdtemp(prefix=\"tlscanarytest_\")\n\n\ndef test_teardown():\n \"\"\"tear down test fixtures\"\"\"\n global tmp_dir\n if tmp_dir is not None:\n shutil.rmtree(tmp_dir, ignore_errors=True)\n tmp_dir = None\n\n\n@with_setup(test_setup, test_teardown)\ndef test_osx_extractor():\n \"\"\"Extractor can extract a OS X Nightly archive\"\"\"\n global test_dir, tmp_dir\n\n # Skip test when hdiutil is not available.\n if find_executable(\"hdiutil\") is None:\n raise SkipTest('Missing `hdiutil`. Not testing OS X extractor.')\n\n test_archive = os.path.join(test_dir, \"files\", \"firefox-nightly_osx-dummy.dmg\")\n assert_true(os.path.isfile(test_archive))\n\n app = fe.extract(\"osx\", test_archive, tmp_dir)\n\n assert_true(type(app) is fa.FirefoxApp, \"return value is correct\")\n assert_true(os.path.isdir(app.app_dir), \"app dir is extracted\")\n assert_true(os.path.isfile(app.app_ini), \"app ini is extracted\")\n assert_true(os.path.isdir(app.browser), \"browser dir is extracted\")\n assert_true(os.path.isfile(app.exe), \"exe file is extracted\")\n assert_true(app.exe.startswith(tmp_dir), \"archive is extracted to specified directory\")\n assert_equal(app.platform, \"osx\", \"platform is detected correctly\")\n assert_equal(app.release, \"Nightly\", \"release branch is detected correctly\")\n assert_equal(app.version, \"53.0a1\", \"version is detected correctly\")\n\n\n@with_setup(test_setup, test_teardown)\ndef test_linux_extractor():\n \"\"\"Extractor can extract a Linux Nightly archive\"\"\"\n global test_dir, tmp_dir\n\n test_archive = os.path.join(test_dir, \"files\", \"firefox-nightly_linux-dummy.tar.bz2\")\n assert_true(os.path.isfile(test_archive))\n\n app = fe.extract(\"linux\", test_archive, tmp_dir)\n\n assert_true(type(app) is fa.FirefoxApp, \"return value is correct\")\n assert_true(os.path.isdir(app.app_dir), \"app dir is extracted\")\n assert_true(os.path.isfile(app.app_ini), \"app ini is extracted\")\n assert_true(os.path.isdir(app.browser), \"browser dir is extracted\")\n assert_true(os.path.isfile(app.exe), \"exe file is extracted\")\n assert_true(app.exe.startswith(tmp_dir), \"archive is extracted to specified directory\")\n assert_equal(app.platform, \"linux\", \"platform is detected correctly\")\n assert_equal(app.release, \"Nightly\", \"release branch is detected correctly\")\n assert_equal(app.version, \"53.0a1\", \"version is detected correctly\")\n" }, { "alpha_fraction": 0.7572613954544067, "alphanum_fraction": 0.7593361139297485, "avg_line_length": 24.3157901763916, "blob_id": "2484bd9d57e088eed2233d0cdc0d7cc86ec28078", "content_id": "a84d6a676b5c8f129429d40a7cbf0d185c2500de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 482, "license_type": "no_license", "max_line_length": 96, "num_lines": 19, "path": "/README.md", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# TLS Canary version 3\nAutomated testing of Firefox for TLS/SSL web compatibility\n\nResults live here:\nhttp://tlscanary.mozilla.org\n\n## This project\n* Downloads a branch build and a release build of Firefox.\n* Automatically runs thousands of secure sites on those builds.\n* Diffs the results and presents potentially broken sites in an HTML page for further diagnosis.\n\n## Usage\n* virtualenv .\n* source bin/activate\n* pip install -e .\n* tls-canary --help\n\n## Testing\n* nosetests -s\n\n" }, { "alpha_fraction": 0.6891734600067139, "alphanum_fraction": 0.6938300132751465, "avg_line_length": 38.76852035522461, "blob_id": "4e0302c80a457da9f9284213d6366b326fb768b0", "content_id": "f2859fc700f1ce792f09b74967177e2c4c00f116", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4295, "license_type": "no_license", "max_line_length": 107, "num_lines": 108, "path": "/tests/firefox_downloader_test.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport mock\nfrom nose.tools import *\nimport os\nimport shutil\nimport tempfile\nfrom time import sleep\n\nimport firefox_downloader as fd\n\n\ntest_dir = os.path.split(__file__)[0]\ntmp_dir = None\n\n\ndef test_setup():\n \"\"\"set up test fixtures\"\"\"\n global tmp_dir\n tmp_dir = tempfile.mkdtemp(prefix=\"tlscanarytest_\")\n\n\ndef test_teardown():\n \"\"\"tear down test fixtures\"\"\"\n global tmp_dir\n if tmp_dir is not None:\n shutil.rmtree(tmp_dir, ignore_errors=True)\n tmp_dir = None\n\n\n@with_setup(test_setup, test_teardown)\ndef test_firefox_downloader_instance():\n \"\"\"FirefoxDownloader instances sanity check\"\"\"\n global tmp_dir\n fdl = fd.FirefoxDownloader(tmp_dir)\n\n build_list, platform_list, test_default, base_default = fdl.list()\n assert_true(\"nightly\" in build_list and \"release\" in build_list, \"build list looks sane\")\n assert_true(\"linux\" in platform_list and \"osx\" in platform_list, \"platform list looks sane\")\n assert_true(test_default in build_list and base_default in build_list, \"defaults are valid builds\")\n\n\n@with_setup(test_setup, test_teardown)\ndef test_firefox_downloader_exceptions():\n \"\"\"Test handling of invalid parameters\"\"\"\n global tmp_dir\n fdl = fd.FirefoxDownloader(tmp_dir, cache_timeout=1)\n build_list, platform_list, test_default, base_default = fdl.list()\n\n assert_true(\"foobar\" not in build_list and \"foobar\" not in platform_list)\n assert_raises(Exception, fdl.download, \"foobar\", platform_list[0])\n assert_raises(Exception, fdl.download, test_default, \"foobar\")\n\n\n@with_setup(test_setup, test_teardown)\[email protected]('urllib2.urlopen')\[email protected]('sys.stdout') # to silence progress bar\ndef test_firefox_downloader_downloading(mock_stdout, mock_urlopen):\n \"\"\"Test the download function\"\"\"\n global tmp_dir\n fdl = fd.FirefoxDownloader(tmp_dir, cache_timeout=1)\n\n mock_req = mock.Mock()\n mock_read = mock.Mock(side_effect=(\"foo\", \"bar\", None))\n mock_info = mock.Mock()\n mock_getheader = mock.Mock(return_value=\"6\")\n mock_info.return_value = mock.Mock(getheader=mock_getheader)\n mock_req.info = mock_info\n mock_req.read = mock_read\n mock_urlopen.return_value = mock_req\n\n output_file_name = fdl.download(\"nightly\", \"linux\", use_cache=True)\n assert_equal(mock_getheader.call_args_list, [((\"Content-Length\",),)],\n \"only checks content length (assumed by test mock)\")\n expected_url = \"\"\"https://download.mozilla.org/?product=firefox-nightly-latest&os=linux64&lang=en-US\"\"\"\n assert_true(mock_urlopen.call_args_list == [((expected_url,),)], \"downloads the expected URL\")\n assert_equal(len(mock_read.call_args_list), 3, \"properly calls read()\")\n assert_true(output_file_name.endswith(\"firefox-nightly_linux64.tar.bz2\"), \"uses expected file name\")\n assert_true(output_file_name.startswith(tmp_dir), \"writes file to expected directory\")\n assert_true(os.path.isfile(output_file_name), \"creates proper file\")\n with open(output_file_name, \"r\") as f:\n content = f.read()\n assert_equal(content, \"foobar\", \"downloads expected content\")\n\n # Test caching by re-downloading\n mock_read.reset_mock()\n mock_read.side_effect = (\"foo\", \"bar\", None)\n second_output_file_name = fdl.download(\"nightly\", \"linux\", use_cache=True)\n assert_false(mock_read.called, \"does not re-download\")\n assert_equal(output_file_name, second_output_file_name, \"uses cached file\")\n\n # Test purging on obsolete cache. Cache is purged on fdl init.\n sleep(1.1)\n mock_read.reset_mock()\n mock_read.side_effect = (\"foo\", \"bar\", None)\n fdl = fd.FirefoxDownloader(tmp_dir, cache_timeout=1)\n fdl.download(\"nightly\", \"linux\", use_cache=True)\n assert_true(mock_read.called, \"re-downloads when cache is stale\")\n\n # Test caching when file changes upstream (checks file size).\n mock_getheader.reset_mock()\n mock_getheader.return_value = \"7\"\n mock_read.reset_mock()\n mock_read.side_effect = (\"foo\", \"barr\", None)\n fdl.download(\"nightly\", \"linux\", use_cache=True)\n assert_true(mock_read.called, \"re-downloads when upstream changes\")\n" }, { "alpha_fraction": 0.545616865158081, "alphanum_fraction": 0.5520442724227905, "avg_line_length": 39.58695602416992, "blob_id": "7cfa7a73580b441b9de8ba89cea5620bd1094acb", "content_id": "d040ce2e725552a67dd3c669c487a2877f49df14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5601, "license_type": "no_license", "max_line_length": 97, "num_lines": 138, "path": "/firefox_downloader.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport logging\nimport os\nimport sys\nimport time\nimport urllib2\n\nimport cache\nimport progress_bar\n\nlogger = logging.getLogger(__name__)\n\n\nclass FirefoxDownloader(object):\n\n __base_url = 'https://download.mozilla.org/?product=firefox' \\\n '-{release}&os={platform}&lang=en-US'\n build_urls = {\n 'esr': __base_url.format(release='esr-latest', platform='{platform}'),\n 'release': __base_url.format(release='latest', platform='{platform}'),\n 'beta': __base_url.format(release='beta-latest', platform='{platform}'),\n 'aurora': __base_url.format(release='aurora-latest', platform='{platform}'),\n 'nightly': __base_url.format(release='nightly-latest', platform='{platform}')\n }\n __platforms = {\n 'osx': {'platform': 'osx', 'extension': 'dmg'},\n 'linux': {'platform': 'linux64', 'extension': 'tar.bz2'},\n 'linux32': {'platform': 'linux', 'extension': 'tar.bz2'},\n 'win': {'platform': 'win64', 'extension': 'exe'},\n 'win32': {'platform': 'win', 'extension': 'exe'}\n }\n\n @staticmethod\n def list():\n build_list = FirefoxDownloader.build_urls.keys()\n platform_list = FirefoxDownloader.__platforms.keys()\n test_default = \"nightly\"\n base_default = \"release\"\n return build_list, platform_list, test_default, base_default\n\n def __init__(self, workdir, cache_timeout=24*60*60):\n self.__workdir = workdir\n self.__cache = cache.DiskCache(os.path.join(workdir, \"cache\"), cache_timeout, purge=True)\n\n @staticmethod\n def __get_to_file(url, filename):\n try:\n\n # TODO: Validate the server's SSL certificate\n req = urllib2.urlopen(url)\n file_size = int(req.info().getheader('Content-Length').strip())\n\n # Caching logic is: don't re-download if file of same size is\n # already in place. TODO: Switch to ETag if that's not good enough.\n # This already prevents cache clutter with incomplete files.\n if os.path.isfile(filename):\n if os.stat(filename).st_size == file_size:\n req.close()\n logger.warning('Skipping download using cached file `%s`' % filename)\n return filename\n else:\n logger.warning('Purging incomplete or obsolete cache file `%s`' % filename)\n os.remove(filename)\n\n logger.info('Downloading `%s` to %s' % (url, filename))\n if sys.stdout.isatty():\n progress = progress_bar.ProgressBar(0, file_size, show_percent=True,\n show_boundary=True)\n else:\n progress = None\n downloaded_size = 0\n chunk_size = 32 * 1024\n with open(filename, 'wb') as fp:\n next_status_update = time.time() # To enforce initial update\n while True:\n chunk = req.read(chunk_size)\n if not chunk:\n break\n downloaded_size += len(chunk)\n fp.write(chunk)\n\n # Update status if stdout is a terminal\n if progress is not None:\n progress.set(downloaded_size)\n now = time.time()\n if now > next_status_update:\n next_status_update = now + 0.1 # 10 times per second\n sys.stdout.write('\\r%s' % progress)\n sys.stdout.flush()\n\n # The final status update\n if sys.stdout.isatty():\n sys.stdout.write('\\r%s\\n' % progress)\n sys.stdout.flush()\n\n except urllib2.HTTPError, err:\n if os.path.isfile(filename):\n os.remove(filename)\n logger.error('HTTP error: %s, %s' % (err.code, url))\n return None\n\n except urllib2.URLError, err:\n if os.path.isfile(filename):\n os.remove(filename)\n logger.error('URL error: %s, %s' % (err.reason, url))\n return None\n\n except KeyboardInterrupt:\n if os.path.isfile(filename):\n os.remove(filename)\n if sys.stdout.isatty():\n print\n logger.critical('Download interrupted by user')\n return None\n\n return filename\n\n def download(self, release, platform, use_cache=True):\n\n if release not in self.build_urls:\n raise Exception(\"Failed to download unknown release `%s`\" % release)\n if platform not in self.__platforms:\n raise Exception(\"Failed to download for unknown platform `%s`\" % platform)\n\n download_platform = self.__platforms[platform]['platform']\n extension = self.__platforms[platform]['extension']\n url = self.build_urls[release].format(platform=download_platform)\n cache_id = 'firefox-%s_%s.%s' % (release, download_platform, extension)\n\n # Always delete cached file when cache function is overridden\n if cache_id in self.__cache and not use_cache:\n self.__cache.delete(cache_id)\n\n # __get_to_file will not re-download if same-size file is already there.\n return self.__get_to_file(url, self.__cache[cache_id])\n" }, { "alpha_fraction": 0.6267772316932678, "alphanum_fraction": 0.6338862776756287, "avg_line_length": 28.10344886779785, "blob_id": "d5f7affa8a02bdef30e03f23bd417996c67e5c45", "content_id": "588d14723f86736bb190dc413d3775838489d0d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 844, "license_type": "no_license", "max_line_length": 75, "num_lines": 29, "path": "/setup.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom setuptools import setup, find_packages\n\nPACKAGE_VERSION = '0.1'\n\n# Dependencies\nwith open('requirements.txt') as f:\n deps = f.read().splitlines()\n\nsetup(name='tls_canary',\n version=PACKAGE_VERSION,\n description='TLS/SSL Test Suite for Firefox',\n classifiers=[],\n keywords='mozilla',\n author='Christiane Ruetten',\n author_email='[email protected]',\n url='https://github.com/cr/tls-canary',\n license='MPL',\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n install_requires=deps,\n entry_points={\"console_scripts\": [\n \"tls_canary = main:main\"\n ]}\n)\n" }, { "alpha_fraction": 0.563813328742981, "alphanum_fraction": 0.5680159330368042, "avg_line_length": 37.313560485839844, "blob_id": "3445d365d5d471af22947f73d2fbdee938337c5e", "content_id": "93cf135c3e2f259f2bc26b89f1ad2a23e70116cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4521, "license_type": "no_license", "max_line_length": 106, "num_lines": 118, "path": "/firefox_runner.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport json\nimport logging\nimport os\nfrom Queue import Queue, Empty\nimport subprocess\nfrom threading import Thread\nimport time\n\nlogger = logging.getLogger(__name__)\n\n\ndef read_from_worker(worker, queue):\n global logger\n logger.debug('Reader thread started for worker %s' % worker)\n for line in iter(worker.stdout.readline, b''):\n try:\n queue.put(json.loads(line))\n except ValueError:\n # FIXME: XPCshell is currently issuing many warnings, constant warning is too verbose\n # logger.warning(\"Unexpected script output: %s\" % line.strip())\n logger.debug(\"Unexpected script output: %s\" % line.strip())\n logger.debug('Reader thread finished for worker %s' % worker)\n worker.stdout.close()\n\n\nclass FirefoxRunner(object):\n def __init__(self, app, work_list, work_dir, data_dir, num_workers=10, info=False, cert_dir=None):\n self.__exe_file = app.exe\n self.__work_list = Queue(maxsize=len(work_list))\n for row in work_list:\n self.__work_list.put(row)\n self.__work_dir = work_dir # usually ~/.tlscanary\n self.__data_dir = data_dir # usually module directory\n self.__num_workers = num_workers\n self.workers = []\n self.results = Queue(maxsize=len(work_list))\n self.__info = info\n self.__cert_dir = cert_dir\n\n def maintain_worker_queue(self):\n for worker in self.workers:\n ret = worker.poll()\n if ret is not None:\n logger.debug('Worker terminated with return code %d' % ret)\n self.workers.remove(worker)\n\n while len(self.workers) < self.__num_workers:\n if self.__work_list.empty():\n return 0\n rank, url = self.__work_list.get()\n rank_url = \"%d,%s\" % (rank, url)\n cmd = [self.__exe_file,\n '-xpcshell',\n os.path.join(self.__data_dir, \"js\", \"scan_url.js\"),\n '-u=%s' % rank_url,\n '-d=%s' % self.__data_dir]\n if self.__info:\n cmd.append(\"-j=true\")\n if self.__cert_dir is not None:\n cmd.append(\"-c=%s\" % self.__cert_dir)\n logger.debug(\"Executing shell command `%s`\" % ' '.join(cmd))\n worker = subprocess.Popen(\n cmd,\n cwd=self.__data_dir,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n bufsize=1) # `1` means line-buffered\n self.workers.append(worker)\n # Spawn a reader thread, because stdio reads are blocking\n reader = Thread(target=read_from_worker, name=\"Reader_\"+rank_url, args=(worker, self.results))\n reader.daemon = True # Thread dies with worker\n reader.start()\n logger.debug('Spawned worker, now %d in queue' % len(self.workers))\n\n return self.__work_list.qsize()\n\n def is_done(self):\n return len(self.workers) == 0 and self.__work_list.empty()\n\n def get_result(self):\n \"\"\"Read from result queue. Returns None if empty.\"\"\"\n try:\n return self.results.get_nowait()\n except Empty:\n return None\n\n def __wait_for_remaining_workers(self, delay):\n kill_time = time.time() + delay\n while time.time() < kill_time:\n for worker in self.workers:\n ret = worker.poll()\n if ret is not None:\n logger.debug('Worker terminated with return code %d' % ret)\n self.workers.remove(worker)\n if len(self.workers) == 0:\n break\n time.sleep(0.05)\n\n def terminate_workers(self):\n # Signal workers to terminate\n for worker in self.workers:\n worker.terminate()\n # Wait for 5 seconds for workers to finish\n self.__wait_for_remaining_workers(5)\n\n # Kill remaining workers\n for worker in self.workers:\n worker.kill() # Same as .terminate() on Windows\n # Wait for 5 seconds for workers to finish\n self.__wait_for_remaining_workers(5)\n\n if len(self.workers) != 0:\n logger.warning('There are %d non-terminating workers remaining' % len(self.workers))\n" }, { "alpha_fraction": 0.5478261113166809, "alphanum_fraction": 0.5585921406745911, "avg_line_length": 28.45121955871582, "blob_id": "06a72695babd577b49450ad3b070be2981a39030", "content_id": "187d2bb5b20c08373a3a099c4e5f88b0fa89de56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2415, "license_type": "no_license", "max_line_length": 75, "num_lines": 82, "path": "/url_store.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport csv\nimport os\n\n__datasets = {\n 'alexa': 'alexa_top_sites.csv',\n 'alexa5k': 'alexa_top5k_sites.csv',\n 'alexa10k': 'alexa_top10k_sites.csv',\n 'alexa100k': 'alexa_top100k_sites.csv',\n 'debug': 'debug.csv',\n 'debug2': 'debug2.csv',\n # 'google': 'google_ct_list.csv', # disabled until cleaned\n 'pulse': 'pulse_top_sites_list.csv',\n 'smoke': 'smoke_list.csv',\n 'test': 'test_url_list.csv',\n 'top1m': 'top-1m.csv'\n}\n\n\ndef list():\n dataset_list = __datasets.keys()\n dataset_list.sort()\n dataset_default = \"alexa\"\n assert dataset_default in dataset_list\n return dataset_list, dataset_default\n\n\ndef iter(dataset, data_dir):\n if dataset.endswith('.csv'):\n csv_file_name = os.path.abspath(dataset)\n else:\n csv_file_name = __datasets[dataset]\n with open(os.path.join(data_dir, csv_file_name)) as f:\n csv_reader = csv.reader(f)\n for row in csv_reader:\n assert 0 <= len(row) <= 2\n if len(row) == 2:\n rank, url = row\n yield int(rank), url\n elif len(row) == 1:\n rank = 0\n url = row[0]\n yield int(rank), url\n else:\n continue\n\n\nclass URLStore(object):\n def __init__(self, data_dir):\n self.__data_dir = os.path.abspath(data_dir)\n self.__loaded_datasets = []\n self.clear()\n\n def clear(self):\n \"\"\"Clear all active URLs from store.\"\"\"\n self.__urls = []\n\n def __len__(self):\n \"\"\"Returns number of active URLs in store.\"\"\"\n return len(self.__urls)\n\n def __iter__(self):\n \"\"\"Iterate all active URLs in store.\"\"\"\n for rank, url in self.__urls:\n yield rank, url\n\n @staticmethod\n def list():\n \"\"\"List handles and files for all static URL databases.\"\"\"\n return list()\n\n def load(self, datasets):\n \"\"\"Load datasets arrayinto active URL store.\"\"\"\n if type(datasets) == str:\n datasets = [datasets]\n for dataset in datasets:\n for nr, url in iter(dataset, self.__data_dir):\n self.__urls.append((nr, url))\n self.__loaded_datasets.append(dataset)\n" }, { "alpha_fraction": 0.5783132314682007, "alphanum_fraction": 0.5854326486587524, "avg_line_length": 38.98540115356445, "blob_id": "1b39581d758f32d7278f2534a1c407bb8c27c24e", "content_id": "4e156371ef24a41f227ff550294b1360476e7b3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5494, "license_type": "no_license", "max_line_length": 90, "num_lines": 137, "path": "/progress_bar.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport datetime\n\n\nclass ProgressBar(object):\n \"\"\"A neat progress bar for the terminal\"\"\"\n\n _box = u' ▏▎▍▌▋▊▉█'\n _boundary_l = u'|'\n _boundary_r = u'|'\n\n def __init__(self, min_value, max_value, outer_width=50,\n show_percent=False, show_boundary=False, stats_window=0):\n self._min = float(min_value)\n self._max = float(max_value)\n self._diff = self._max - self._min\n self._value = self._min\n self._outer_width = outer_width\n self._show_percent = show_percent\n self._show_boundary = show_boundary\n self._bar_width = self._outer_width\n self._stats_window = stats_window\n self._stats = []\n self._start_time = None\n if show_percent:\n self._bar_width -= 5\n if show_boundary:\n self._bar_width -= len(self._boundary_l + self._boundary_r)\n if self._bar_width < 1:\n raise Exception('Insufficient outer width for progress bar')\n\n def set(self, value):\n \"\"\"Set the current value. Will be limited to [min, max]\"\"\"\n self._value = float(max(self._min, min(self._max, value)))\n if self._start_time is None:\n self._start_time = datetime.datetime.now()\n if self._stats_window > 0:\n self._stats.append((datetime.datetime.now(), self._value))\n if len(self._stats) > self._stats_window:\n self._stats = self._stats[-self._stats_window:]\n\n def stats(self):\n \"\"\"Return a list of runtime statistics\"\"\"\n\n past = datetime.datetime.now() - datetime.timedelta(1)\n if len(self._stats) < 2:\n return 0., datetime.timedelta(0), past, 0., datetime.timedelta(0), past\n\n relative_done = (self._value - self._min) / self._diff\n relative_todo = 1.0 - relative_done\n\n # Calculate rate and ETA relative to overall progress\n try:\n latest_update_time, _ = self._stats[-1]\n elapsed_time = latest_update_time - self._start_time\n overall_rate = relative_done / elapsed_time.seconds\n overall_rest_time = datetime.timedelta(seconds=(relative_todo / overall_rate))\n overall_eta = latest_update_time + overall_rest_time\n except ZeroDivisionError:\n # If rate was zero\n overall_rest_time = datetime.timedelta(0)\n overall_eta = past\n\n # Calculate rate and ETA relative to current progress\n try:\n window_start_time, window_start_value = self._stats[0]\n window_end_time, window_end_value = self._stats[-1]\n window_elapsed_time = window_end_time - window_start_time\n window_done = (window_end_value - window_start_value) / self._diff\n current_rate = window_done / window_elapsed_time.seconds\n current_rest_time = datetime.timedelta(seconds=(relative_todo / current_rate))\n current_eta = window_end_time + current_rest_time\n except ZeroDivisionError:\n # If rate was zero\n current_rest_time = datetime.timedelta(0)\n current_eta = past\n\n return overall_rate * self._diff, overall_rest_time, overall_eta, \\\n current_rate * self._diff, current_rest_time, current_eta\n\n def _draw_bar(self):\n \"\"\"Helper function that returns the bare bar as a string\"\"\"\n\n # There is a fixed number of boxes in the whole progress bar.\n n_boxes = self._bar_width\n # Every box has a fixed number of states between empty and full.\n n_box_states = len(self._box) - 1\n # So the whole bar has a fixed number of states, too.\n n_bar_states = n_box_states * n_boxes\n \n # Calculate the set value relative to the total number of bar states.\n bar_value = int(n_bar_states * (self._value - self._min) / self._diff)\n\n # This is what happens next: Number each box i = 0..n_boxes-1\n # bar = range(0, n_boxes)\n\n # Calculate the base state number for each box.\n # bar = map(lambda i: n_box_states * i, bar)\n\n # Subtract each box's base state number from the current bar value.\n # bar = map(lambda base: bar_value - base, bar)\n\n # Restrict each box to a value in [0..n_box_states].\n # bar = map(lambda x: max(0, min(n_box_states, x)), bar)\n\n # Look up the `eigths box` unicode character for every box state.\n # bar = map(lambda state: self._box[state], bar)\n\n # This is an equivalent but about twice as efficient one-liner:\n bar = [self._box[max(0, min(n_box_states, bar_value - n_box_states * i))]\n for i in xrange(0, n_boxes)]\n\n return u''.join(bar)\n\n def __unicode__(self):\n \"\"\"Returns the `rendered` bar as a unicode string\"\"\"\n\n line = u''\n if self._show_percent:\n percent = int(100.0 * (self._value - self._min) / self._diff)\n line += u'%3d%% ' % percent\n if self._show_boundary:\n line += self._boundary_l\n line += self._draw_bar()\n if self._show_boundary:\n line += self._boundary_r\n\n return line\n\n def __str__(self):\n \"\"\"Returns the `rendered` bar as a utf-8 string\"\"\"\n return unicode(self).encode('utf-8')\n" }, { "alpha_fraction": 0.7027027010917664, "alphanum_fraction": 0.7567567825317383, "avg_line_length": 8.25, "blob_id": "c2dbb7d4f6a05571521d4c1d035887868f101f4a", "content_id": "7590410aa3c6e756da3ee74fb21aa2f9dc4162ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 37, "license_type": "no_license", "max_line_length": 11, "num_lines": 4, "path": "/requirements.txt", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "coloredlogs\nipython\nnose >= 1.3\nmock\n" }, { "alpha_fraction": 0.7888888716697693, "alphanum_fraction": 0.8037037253379822, "avg_line_length": 26, "blob_id": "1a44942fb5d6e0f526b1da98ed5c78fba9a96ddf", "content_id": "270970d8783694abb0d99015211a6f35c3fd07ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 270, "license_type": "no_license", "max_line_length": 31, "num_lines": 10, "path": "/linux_bootstrap.sh", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# AWS Ubuntu linux bootstrap\nsudo apt-get update\nsudo apt-get install libgtk-3-0\nsudo apt-get install libxt6\nsudo apt-get install libasound2\nsudo apt-get install python\nsudo apt-get install python-dev\nsudo apt-get install virtualenv\nsudo apt-get install gcc\n" }, { "alpha_fraction": 0.6677053570747375, "alphanum_fraction": 0.6702549457550049, "avg_line_length": 32.619049072265625, "blob_id": "9562bda00634fb0aeba6519d51b01d4c694ccfa6", "content_id": "08323c263eb1ffad6f4174b0c8b1f175118a568c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3530, "license_type": "no_license", "max_line_length": 103, "num_lines": 105, "path": "/firefox_extractor.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport tarfile\nimport tempfile\n\nfrom firefox_app import FirefoxApp\n\nlogger = logging.getLogger(__name__)\n\n\n# TODO: Ensure that all images are unmounted at exit.\n# Images may still be mounted when global tmp_dir is removed at exit,\n# for example when extraction throws an exception.\n\n# TODO: Cache extracted files, too. Takes very long to unpack 100 MByte.\n\n\ndef __osx_mount_dmg(dmg_file, mount_point):\n global logger\n assert('\"' not in dmg_file + mount_point)\n assert(dmg_file.endswith('.dmg'))\n cmd = '''hdiutil attach -readonly -noverify -noautoopen -noautoopenro''' \\\n ''' -noautoopenrw -nobrowse -noidme -noautofsck -mount required''' \\\n ''' -quiet -mountpoint \"%s\" \"%s\"''' % (mount_point, dmg_file)\n logger.debug(\"Executing shell command `%s`\" % cmd)\n # Throws subprocess.CalledProcessError on non-zero exit value\n subprocess.check_call(cmd, shell=True)\n\n\ndef __osx_unmount_dmg(mount_point):\n global logger\n assert('\"' not in mount_point)\n cmd = 'hdiutil detach -quiet -force \"%s\"' % mount_point\n logger.debug(\"Executing shell command `%s`\" % cmd)\n # Throws subprocess.CalledProcessError on non-zero exit value\n subprocess.check_call(cmd, shell=True)\n\n\ndef __osx_extract(archive_file, tmp_dir):\n global logger\n\n logger.info(\"Extracting MacOS X archive\")\n extract_dir = tempfile.mkdtemp(dir=tmp_dir, prefix='extracted_')\n mount_dir = tempfile.mkdtemp(dir=tmp_dir, prefix='mount_')\n logger.debug('Mounting image `%s` at mount point `%s`' % (archive_file, mount_dir))\n __osx_mount_dmg(archive_file, mount_dir)\n\n try:\n # Copy everything over\n if os.path.exists(extract_dir):\n shutil.rmtree(extract_dir)\n logger.debug('Copying files from mount point `%s` to `%s`' % (mount_dir, extract_dir))\n shutil.copytree(mount_dir, extract_dir, symlinks=True)\n\n except Exception, err:\n logger.error('Error while extracting image. Detaching image from mount point `%s`' % mount_dir)\n __osx_unmount_dmg(mount_dir)\n raise err\n\n except KeyboardInterrupt, err:\n logger.error('User abort. Detaching image from mount point `%s`' % mount_dir)\n __osx_unmount_dmg(mount_dir)\n raise err\n\n logger.debug('Detaching image from mount point `%s`' % mount_dir)\n __osx_unmount_dmg(mount_dir)\n\n return extract_dir\n\n\ndef __linux_extract(archive_file, tmp_dir):\n global logger\n\n logger.info(\"Extracting Linux archive\")\n extract_dir = tempfile.mkdtemp(dir=tmp_dir, prefix='extracted_')\n logger.debug(\"Extracting Linux archive `%s` to `%s`\" % (archive_file, extract_dir))\n\n try:\n with tarfile.open(archive_file) as tf:\n tf.extractall(extract_dir)\n\n except Exception, err:\n logger.error('Error while extracting image: %s' % err)\n raise err\n\n return extract_dir\n\n\ndef extract(platform, archive_file, tmp_dir):\n \"\"\"Extract a Firefox archive file into a subfolder in the given temp dir.\"\"\"\n global logger\n\n if platform == 'osx':\n extract_dir = __osx_extract(archive_file, tmp_dir)\n elif platform == \"linux\" or platform == \"linux32\":\n extract_dir = __linux_extract(archive_file, tmp_dir)\n else:\n extract_dir = None\n return FirefoxApp(extract_dir)\n" }, { "alpha_fraction": 0.6732869744300842, "alphanum_fraction": 0.6782522201538086, "avg_line_length": 25.526315689086914, "blob_id": "82345d7d525cad0baed5d965a4a7f1c2b260353b", "content_id": "db6bb4b6f8398d66220e5fc9ebb8fd14169615e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1007, "license_type": "no_license", "max_line_length": 76, "num_lines": 38, "path": "/cleanup.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport atexit\nimport signal\n\n\n__cleanup_done = False\n\n\ndef init():\n \"\"\"Register cleanup handler\"\"\"\n\n # print \"Registering cleanup handler\"\n\n global __cleanup_done\n __cleanup_done = False\n\n # Will be OS-specific, see https://docs.python.org/2/library/signal.html\n atexit.register(cleanup_handler)\n signal.signal(signal.SIGTERM, cleanup_handler)\n signal.signal(signal.SIGHUP, cleanup_handler)\n\n\ndef cleanup_handler():\n \"\"\"The cleanup handler that runs when process terminates\"\"\"\n # print \"Cleanup handler called\"\n global __cleanup_done\n if not __cleanup_done:\n __cleanup_done = True\n for child in CleanUp.__subclasses__():\n child.at_exit()\n\n\nclass CleanUp(object):\n \"\"\"When process terminates, .at_exit() is called on every subclass.\"\"\"\n pass" }, { "alpha_fraction": 0.6598157286643982, "alphanum_fraction": 0.6686747074127197, "avg_line_length": 33.839508056640625, "blob_id": "c9b33810737bdeaca50a7aa2fedd907ceb7ebeef", "content_id": "edb5e211516e3a1fd039689db844a9979b22721c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2822, "license_type": "no_license", "max_line_length": 107, "num_lines": 81, "path": "/tests/cache_test.py", "repo_name": "jonathanKingston/tls-canary", "src_encoding": "UTF-8", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom math import floor\nfrom nose.tools import *\nimport os\nimport shutil\nimport tempfile\nfrom time import sleep, time\n\nimport cache\n\n\ntest_dir = os.path.split(__file__)[0]\ntmp_dir = None\n\n\ndef test_setup():\n \"\"\"set up test fixtures\"\"\"\n global tmp_dir\n tmp_dir = tempfile.mkdtemp(prefix=\"tlscanarytest_\")\n\n\ndef test_teardown():\n \"\"\"tear down test fixtures\"\"\"\n global tmp_dir\n if tmp_dir is not None:\n shutil.rmtree(tmp_dir, ignore_errors=True)\n tmp_dir = None\n\n\n@with_setup(test_setup, test_teardown)\ndef test_cache_instance():\n \"\"\"Comprehensive cache test suite\"\"\"\n global tmp_dir\n\n # CAVE: Some file systems (HFS+, ext3, ...) only provide timestamps with 1.0 second resolution.\n # This affects testing accuracy when working with `maximum_age` in the range of a second.\n # Wait until we're within 10ms past a full second to keep jitter low and this test stable.\n t = time()\n while t - floor(t) >= 0.01:\n t = time()\n\n cache_root_dir = os.path.join(tmp_dir, \"test_cache\")\n dc = cache.DiskCache(cache_root_dir, maximum_age=1, purge=False)\n\n assert_true(os.path.isdir(cache_root_dir), \"cache creates directory\")\n assert_equal(len(dc.list()), 0, \"cache is initially empty\")\n\n # Create a test entry in the cache\n test_file = dc[\"foo\"]\n with open(test_file, \"w\") as f:\n f.write(\"foo\")\n\n assert_true(test_file.startswith(cache_root_dir), \"cache entries are located in cache directory\")\n assert_true(\"foo\" in dc, \"cache accepts new file entries\")\n assert_false(\"baz\" in dc, \"cache does not obviously phantasize about its content\")\n\n # Create a slightly newer cache entry\n # Ensure that it's regarded to be one second younger even with 1s mtime resolution\n sleep(1.01)\n newer_test_file = dc[\"bar\"]\n with open(newer_test_file, \"w\") as f:\n f.write(\"bar\")\n\n assert_true(\"foo\" in dc and \"bar\" in dc and len(dc.list()) == 2, \"cache accepts more new file entries\")\n\n # At this point, \"foo\" is considered to be at least 1s old, \"bar\" just a few ms.\n assert_true(\"foo\" in dc and \"bar\" in dc, \"purge only happens when explicitly called\")\n dc.purge(maximum_age=10)\n assert_true(\"foo\" in dc and \"bar\" in dc, \"purge only affects stale files\")\n dc.purge() # uses `maximum_age` value from init, 1\n assert_true(\"foo\" not in dc, \"purge actually purges\")\n assert_true(\"bar\" in dc, \"purge does not overly purge\")\n\n dc.delete()\n assert_true(\"bar\" not in dc and len(dc.list()) == 0, \"cache can be fully emptied\")\n\n # Deleting unknown cache entries should not lead to an error\n dc.delete(\"foofoo\")\n" } ]
16
volltin/USTC_Emoji
https://github.com/volltin/USTC_Emoji
d0f82f2cb054f91b6a732c348db059a35403335b
fd2a2a1521c953e21dddd5add1e1a8e8be36044f
b39d1502a8ebe390f61a76373822ca890e9d8214
refs/heads/master
2021-06-26T07:30:52.403899
2017-09-15T07:40:58
2017-09-15T07:40:58
103,534,495
11
1
null
2017-09-14T13:16:52
2017-09-15T07:18:37
2017-09-15T07:40:59
Python
[ { "alpha_fraction": 0.6741071343421936, "alphanum_fraction": 0.7008928656578064, "avg_line_length": 12.235294342041016, "blob_id": "4c9b9346a02d099adbfbafa014b27bbe9a70dbae", "content_id": "643fe01bda46c2a7dae851aed11ece843a1c9a8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 224, "license_type": "no_license", "max_line_length": 43, "num_lines": 17, "path": "/README.md", "repo_name": "volltin/USTC_Emoji", "src_encoding": "UTF-8", "text": "# USTC Emoji\n\nA simple script to draw emoji on USTC logo.\n\nYou can add more emoji in `EMOJI_DIR`\n\n## Usage\n\nMakesure you have PIL installed.\n\n`python ustc_emoji.py`\n\n## Example\n\n![joy](output/703.jpg)\n\n![red](output/752.jpg)" }, { "alpha_fraction": 0.5403472781181335, "alphanum_fraction": 0.5638406276702881, "avg_line_length": 31.633333206176758, "blob_id": "dad74443d7cfd492ce93185297ba42a382488461", "content_id": "31c364ccf95b31e3a5a0c3cb8301e181d813dc34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2937, "license_type": "no_license", "max_line_length": 109, "num_lines": 90, "path": "/ustc_emoji.py", "repo_name": "volltin/USTC_Emoji", "src_encoding": "UTF-8", "text": "from __future__ import print_function\n\nfrom PIL import Image, ImageDraw\n\n# USTC logo image\nLOGO_FILE = './ustcblue.jpg'\n\n# Emoji images (if filename is \"%d.*\", you can add allow_range)\nEMOJI_DIR = './emoji/'\n\n# Output dir\nOUTPUT_DIR = './output'\n\n# Offset for drawing\nX_OFFSET = 10\nY_OFFSET = 30\n\n# Center circle size\nR = 310\n\n# Caches for rotated logos\nROTATED_LOGOS = {}\n\ndef draw_emoji(logo, emoji, rotation = 0):\n import math\n output = Image.new('RGB', (logo.size), (255, 255, 255))\n\n # Find center\n x, y = logo.size\n x += X_OFFSET\n y += Y_OFFSET\n cx, cy = x / 2, y / 2\n ex, ey = R, R\n center = (cx - ex / 2, cy - ey / 2, cx + ex / 2, cy + ey / 2)\n center = [int(i) for i in center]\n\n # Clear center\n draw = ImageDraw.Draw(logo)\n draw.ellipse(center, fill=(255, 255, 255))\n\n if rotation in ROTATED_LOGOS:\n # Take the logo from caches\n logo_canvas = ROTATED_LOGOS[rotation]\n else:\n # Set the canvas for drawing logo\n logo_canvas = Image.new('RGB', (x * 3, y * 3), (255, 255, 255))\n logo_canvas.paste(logo, (x, y))\n\n # Rotate logo\n r_cos, r_sin = math.cos(math.radians(rotation)), math.sin(math.radians(rotation))\n dx, dy = x + cx - r_cos * cx + r_sin * cy, y + cy - r_sin * cx - r_cos * cy\n matrix = (r_cos, -r_sin, dx, r_sin, r_cos, dy)\n logo_canvas = logo_canvas.transform((x, y), method=Image.AFFINE, data=matrix)\n ROTATED_LOGOS[rotation] = logo_canvas\n\n # Resize emoji\n emoji = emoji.resize((center[2] - center[0], center[3] - center[1]))\n\n # Draw emoji on logo\n output.paste(logo_canvas, (0, 0))\n output.paste(emoji, center, mask=emoji)\n return output\n\ndef generate_all_emoji(logo, emoji_dir, output_dir, allow_range=None, rotation_sequence=None):\n import os\n for root, dirs, files in os.walk(emoji_dir):\n i, length = 0, len(files)\n for name in files:\n i += 1\n try:\n print(\"Generating:\", i, '/', length)\n emoji = Image.open(root + '/' + name)\n index, suffix = name.split('.')\n if allow_range and int(index) not in allow_range: continue\n output = draw_emoji(logo, emoji)\n output.save(output_dir + '/' + index + \".jpg\", \"JPEG\",\n quality=80, optimize=True, progressive=True)\n if rotation_sequence is not None:\n outputs = [draw_emoji(logo, emoji, rot) for rot in rotation_sequence]\n output.save(output_dir + '/' + index + \".gif\", \"GIF\",\n save_all=True, loop=0, duration=50, append_images=outputs)\n except:\n continue\n\nif __name__ == \"__main__\":\n logo = Image.open(LOGO_FILE)\n\n rotations = range(18, 360, 18)\n\n generate_all_emoji(logo, EMOJI_DIR, OUTPUT_DIR, allow_range=range(700, 800), rotation_sequence=rotations)\n" } ]
2
donghoony/guahmchatbot
https://github.com/donghoony/guahmchatbot
f1259d4f664c7f0f6fb8e8c15e25861925b72640
f9b60d5445043d78ea21cb662801f5170c851f6b
9ddddd8c35a1fb357c420e676fc7d32a1002ec3d
refs/heads/master
2022-03-02T14:40:34.217170
2019-10-29T16:21:27
2019-10-29T16:21:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5011062026023865, "alphanum_fraction": 0.5265486836433411, "avg_line_length": 30.719297409057617, "blob_id": "2c11ff9475f174d418a7f1b9a5a7eadc769c8403", "content_id": "469ea1ab1221afe72a30e99871c841c68bf85586", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1848, "license_type": "no_license", "max_line_length": 138, "num_lines": 57, "path": "/app/temp.py", "repo_name": "donghoony/guahmchatbot", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport requests\nimport sqlite3\n\nmeal_table = sqlite3.connect('meal_table.db', check_same_thread=False)\nmonth = ['Zeronull','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']\n\nc = meal_table.cursor()\ntry:\n for i in month:\n c.execute(\"\"\"CREATE TABLE {}(\n day integer,\n lunch text,\n dinner text)\"\"\".format(i))\nexcept sqlite3.OperationalError:\n print(\"Table already exists, Skipping...\")\n\n\n# 중식 r1, 석식 r2\nr1 = requests.get(\n \"https://stu.sen.go.kr/sts_sci_md00_001.do?schulCode=B100005528&schMmealScCode=2&schulCrseScCode=4\")\n\nc1 = r1.content\n\nhtml1 = BeautifulSoup(c1, \"html.parser\")\n\ntr1 = html1.find_all('tbody')\n\ntd1 = tr1[0].find_all('td')\ntable = []\nfor i in range(35):\n table.append(list(map(str, str(td1[i].find('div')).replace('<div>', '').replace('</div>','').replace('&amp;',',',-1).split('<br/>'))))\n\n\nfor i in range(len(table)):\n # 월초여백, 월말여백\n isLunch = 0\n if len(table[i]) == 1:\n continue\n else:\n for j in range(len(table[i])):\n if j == 0:\n day = table[i][j]\n continue\n if table[i][j] == '[중식]':\n isLunch = True\n if table[i][j] == '[석식]':\n isLunch = False\n if isLunch == True and table[i][j] != '[중식]':\n c.execute(\"INSERT INTO {} (day, lunch) VALUES (?, ?)\".format(month[11]), (day, table[i][j],))\n meal_table.commit()\n if isLunch == 0 and table[i][j] != '[석식]':\n c.execute(\"INSERT INTO {} (day, dinner) VALUES (?, ?)\".format(month[11]), (day, table[i][j],))\n meal_table.commit()\nday = 5\nc.execute(\"SELECT * FROM Nov WHERE day = 5\")\nprint(c.fetchall())\n" }, { "alpha_fraction": 0.6744186282157898, "alphanum_fraction": 0.6910299062728882, "avg_line_length": 31.44444465637207, "blob_id": "61e9f9de689a54f602e359dc2dc2302fd56cb2f3", "content_id": "b9c3937c618fba3151d6dfea2c0f0d8a4a71471c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 301, "license_type": "no_license", "max_line_length": 51, "num_lines": 9, "path": "/app/models.py", "repo_name": "donghoony/guahmchatbot", "src_encoding": "UTF-8", "text": "from django.db import models\r\n\r\n# Create your models here.\r\n\r\nclass MemberBusAlert(models.Model):\r\n user_key = models.CharField(max_length = 20)\r\n bus_num = models.CharField(max_length = 4)\r\n goschool_stn = models.CharField(max_length = 5)\r\n gohome_stn = models.CharField(max_length = 5)\r\n" }, { "alpha_fraction": 0.31110307574272156, "alphanum_fraction": 0.338188111782074, "avg_line_length": 42.89663314819336, "blob_id": "758b6778e19fa18f1d62ea029351c8957afaf85b", "content_id": "18fc8fcddce1046e714ec009e602311060d3ba0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 45768, "license_type": "no_license", "max_line_length": 126, "num_lines": 861, "path": "/app/views.py", "repo_name": "donghoony/guahmchatbot", "src_encoding": "UTF-8", "text": "from django.http import JsonResponse\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nimport urllib.request as ul\r\nimport xmltodict\r\nimport json\r\nimport time as t\r\nimport sqlite3\r\nimport datetime as dt\r\n\r\n# Dump codes below\r\n# BusStops, to School\r\n# schoolBusStop13 = ['벽산아파트', '약수맨션', '노량진역', '대방역2번출구앞']\r\n# schoolBusStop5513 = ['관악구청', '서울대입구', '봉천사거리, 봉천중앙시장', '봉현초등학교', '벽산블루밍벽산아파트303동앞']\r\n# BusStop values, to School\r\n# numBusStop13 = ['21910', '20891', '20867', '20834']\r\n# numBusStop5513 = ['21130', '21252', '21131', '21236', '21247']\r\n\r\nbus_db = sqlite3.connect('bus_key.db', check_same_thread=False)\r\n\r\ntry:\r\n c = bus_db.cursor()\r\n c.execute(\"\"\"CREATE TABLE BusService (\r\n user_key text,\r\n bus_num integer,\r\n school_stn text,\r\n home_stn text)\"\"\")\r\nexcept sqlite3.OperationalError:\r\n print(\"Table already exists, Skip making table...\")\r\n\r\n# BusStops, to Home\r\nhomeBusStop13 = ['관악드림타운북문 방면 (동작13)', '벽산아파트 방면 (동작13)']\r\nhomeBusStop5513 = ['관악드림타운북문 방면 (5513)', '벽산아파트 방면 (5513)']\r\nhomeBusStop01 = ['관악드림타운북문 방면 (관악01)', '벽산아파트 방면 (관악01)']\r\n\r\n# Setting lines\r\nsetting13 = ['대방역2번출구앞 (설정)', '현대아파트 (설정)', '노량진역 (설정)', '우성아파트 (설정)', '건영아파트 (설정)', '신동아상가 (설정)',\r\n '동작등기소 (설정)', '부강탕 (설정)', '밤골 (설정)', '약수맨션 (설정)', '빌라삼거리, 영도교회 (설정)', '방범초소 (설정)', '벽산아파트 (설정)']\r\nsetting5513 = ['관악구청 (설정)', '서울대입구 (설정)', '봉천사거리, 봉천중앙시장 (설정)', '봉원중학교, 행운동우성아파트 (설정)',\r\n '관악푸르지오아파트 (설정)', '봉현초등학교 (설정)', '벽산블루밍벽산아파트303동앞 (설정)']\r\nsetting01 = ['봉천역 (설정)', '두산아파트입구 (설정)', '현대시장 (설정)', '구암초등학교정문 (설정)', '성현동주민센터 (설정)', '구암어린이집앞 (설정)',\r\n '숭실대입구역2번출구 (설정)', '봉천고개현대아파트 (설정)', '봉현초등학교_01 (설정)', '관악드림타운115동 (설정)']\r\n\r\nbus_stn_dict_13 = {'대방역2번출구앞': ['20834', 2], '현대아파트': ['20007', 2], '노량진역': ['20867', 1],\r\n '우성아파트': ['20878', 1], '건영아파트': ['20894', 0], '신동아상가': ['20897', 0],\r\n '동작등기소': ['20730', 2], '부강탕': ['20913', 0], '밤골': ['20918', 0], '약수맨션': ['20891', 1],\r\n '빌라삼거리, 영도교회': ['20922', 0], '방범초소': ['20924', 0], '벽산아파트': ['21910', 0]}\r\nbus_stn_dict_5513 = {'관악구청': ['21130', 5], '서울대입구': ['21252', 1], '봉천사거리, 봉천중앙시장': ['21131', 7],\r\n '봉원중학교, 행운동우성아파트': ['21132', 8], '관악푸르지오아파트': ['21133', 7], '봉현초등학교': ['21236', 2],\r\n '벽산블루밍벽산아파트303동앞': ['21247', 0]}\r\nbus_stn_dict_01 = {'봉천역': ['21508', 0], '두산아파트입구': ['21526', 0], '현대시장': ['21536', 0], '구암초등학교정문': ['21545', 0],\r\n '성현동주민센터': ['21565', 0], '구암어린이집앞': ['21575', 0], '숭실대입구역2번출구': ['20810', 0],\r\n '봉천고개현대아파트': ['20820', 0], '봉현초등학교_01': ['21236', 0], '관악드림타운115동': ['21239', 0]}\r\n\r\n# Meal table, index(0-4) => Mon-Fri\r\nlunch = []\r\ndinner = []\r\n\r\n# n은 xml상에서 봤을 때 itemList 순서임, index이므로 0부터 시작.\r\ndef bus(n, busStn, busNo):\r\n print(\"Attempt to get the {}, {}, {} bus info...\".format(n, busStn, busNo))\r\n url = 'http://ws.bus.go.kr/api/rest/stationinfo/getStationByUid?ServiceKey=fef2WSoMFkV557J%2BKKEe0LmP4Y1o8IsH6x4Lv4p0pArUHTs6sk6sHVGaNfkFZRM2sSUn5Uvw0JzETmEyk5VeoA%3D%3D&arsId=' + busStn\r\n request = ul.Request(url)\r\n response = ul.urlopen(request)\r\n rescode = response.getcode()\r\n\r\n # URL에 정상적으로 접근했을 시 rescode의 값은 200이 된다.\r\n if rescode == 200:\r\n responseData = response.read()\r\n rD = xmltodict.parse(responseData)\r\n rDJ = json.dumps(rD)\r\n rDD = json.loads(rDJ)\r\n busrDD = rDD[\"ServiceResult\"][\"msgBody\"][\"itemList\"]\r\n\r\n if len(busrDD) > 30:\r\n bus01 = busrDD[\"arrmsg1\"]\r\n bus02 = busrDD[\"arrmsg2\"]\r\n id01 = busrDD[\"vehId1\"]\r\n id02 = busrDD[\"vehId2\"]\r\n\r\n else:\r\n bus01 = busrDD[n][\"arrmsg1\"]\r\n bus02 = busrDD[n][\"arrmsg2\"]\r\n id01 = busrDD[n][\"vehId1\"]\r\n id02 = busrDD[n][\"vehId2\"]\r\n\r\n bus01 = '곧' if bus01 == '곧 도착' else bus01\r\n bus01 = bus01.replace('분', '분 ').replace('초후', '초 후 ').replace('번째', ' 정류장')\r\n bus01 = '전 정류장 출발' if bus01 == '0 정류장 전' else bus01\r\n bus02 = bus02.replace('분', '분 ').replace('초후', '초 후 ').replace('번째', ' 정류장')\r\n\r\n # 동작13과 5513의 리턴값이 다르다, 타요버스가 없으니까 타요 제외.\r\n if busNo == 13:\r\n tayoList = ['24', '57', '58', '92', '95']\r\n tayo1 = '이번 버스는 타요차량입니다.' if id01[-2:] in tayoList else '이번 버스는 일반차량입니다.'\r\n tayo2 = '다음 버스는 타요차량입니다.' if id02[-2:] in tayoList else '다음 버스는 일반차량입니다.'\r\n if bus01 in ['출발대기', '운행종료']:\r\n tayo1 = ''\r\n if bus02 in ['출발대기', '운행종료']:\r\n tayo2 = ''\r\n return [bus01, bus02, tayo1, tayo2]\r\n\r\n elif busNo in [5513, 1]:\r\n return [bus01, bus02]\r\n\r\n\r\nisRefreshed = 0\r\nupdatedtime = 0\r\nbus_stn_setting_list = []\r\nisSetting = False\r\nsettingTime = 0\r\n\r\n\r\ndef foodie(n, isForce):\r\n global isRefreshed, updatedtime, lunch, dinner\r\n print(\"Attempting to access in Meal table, Updated = {}\".format(['False', 'True'][isRefreshed]))\r\n y, m, d = map(str, str(dt.datetime.now())[:10].split('-'))\r\n # 2018.10.29 형식\r\n ymd = y + '.' + m + '.' + d\r\n currenttime = int(t.time())\r\n dayList = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\r\n weekendRefresh = 0\r\n # 일요일, 새로고침되지 않았을 때 실행 (다른 방법 필요할듯, 업데이트 날짜 가져와서 7일 내이면 넘기고, 아니면 업데이트 하는 식으로)\r\n # food함수 내에는 고쳐질 게 많다. 토요일, 일요일에 리턴하는 0값을 처리해야 함.\r\n # 또, 방학이나 공휴일처럼 평일이지만 배식하지 않는 경우를 추가해줘야 함.\r\n # -> 500000초 (약 5.7일) 초과 시 자동 업데이트, 단 foodie 함수가 활성화돼야 함\r\n\r\n print(\"Time elasped after task built : {}\".format(currenttime - updatedtime))\r\n if ((currenttime - updatedtime) > 500000) or (isRefreshed == 0) or (lunch == []) or (isForce):\r\n if isForce:\r\n print('Forcing to update')\r\n print('Getting meals, wait for moment...')\r\n from bs4 import BeautifulSoup\r\n import requests\r\n # 중식 r1, 석식 r2\r\n r1 = requests.get(\r\n \"http://stu.sen.go.kr/sts_sci_md01_001.do?\"\r\n \"schulCode=B100005528&schMmealScCode=2&schulCrseScCode=4&schYmd=\" + ymd)\r\n r2 = requests.get(\r\n \"http://stu.sen.go.kr/sts_sci_md01_001.do?\"\r\n \"schulCode=B100005528&schMmealScCode=3&schulCrseScCode=4&schYmd=\" + ymd)\r\n c1 = r1.content\r\n c2 = r2.content\r\n html1 = BeautifulSoup(c1, \"html.parser\")\r\n html2 = BeautifulSoup(c2, \"html.parser\")\r\n tr1 = html1.find_all('tr')\r\n td1 = tr1[2].find_all('td')\r\n tr2 = html2.find_all('tr')\r\n td2 = tr2[2].find_all('td')\r\n td1 = [\"급식이 없습니다.\\n\" for i in range(7)] if td1 == [] else td1\r\n td2 = [\"급식이 없습니다.\\n\" for i in range(7)] if td2 == [] else td2\r\n\r\n for i in range(1, 6):\r\n td1[i] = str(td1[i])\r\n td2[i] = str(td2[i])\r\n tempdish1 = td1[i].replace('<td class=\"textC\">', '').replace('<br/>', '\\n', -1).replace('</td>',\r\n '').replace('&amp;',\r\n ', ').replace(\r\n '\\n', '\\n- ', -1)\r\n dish1 = '- ======== -\\n- '\r\n for _ in tempdish1:\r\n if _ in '1234567890.':\r\n continue\r\n else:\r\n dish1 += _\r\n\r\n tempdish2 = td2[i].replace('<td class=\"textC\">', '').replace('<br/>', '\\n', -1).replace('</td>',\r\n '').replace('&amp;',\r\n ', ').replace(\r\n '\\n', '\\n- ', -1)\r\n dish2 = '- ======== -\\n- '\r\n for _ in tempdish2:\r\n if _ in '1234567890.':\r\n continue\r\n else:\r\n dish2 += _\r\n\r\n lunch.append(dish1 + '======== -')\r\n dinner.append(dish2 + '======== -')\r\n\r\n lunch += ['메뉴가 없습니다.'] * 2\r\n dinner += ['메뉴가 없습니다.'] * 2\r\n updatedtime = int(t.time())\r\n isRefreshed = 1\r\n if weekendRefresh == 0:\r\n weekendRefresh = 1\r\n print(\"Meal task has been built / refreshed!\")\r\n\r\n # 주말에 함수 호출시에 리프레시 0으로 맞춰주자\r\n if n == 'Sun':\r\n if weekendRefresh == 0:\r\n isRefreshed = 0\r\n\r\n return [str(dayList.index(n)), m, d]\r\n\r\n\r\ndef keyboard(request):\r\n return JsonResponse(\r\n {\r\n 'type': 'buttons',\r\n\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n )\r\n\r\n\r\n@csrf_exempt\r\ndef message(request):\r\n global bus_stn_setting_list, bus_stn_dict_13, bus_stn_dict_5513, bus_stn_dict_01, isSetting, settingTime, lunch, dinner\r\n json_str = (request.body).decode('utf-8')\r\n received_json = json.loads(json_str)\r\n clickedButton = received_json['content']\r\n user_key = received_json['user_key']\r\n if clickedButton == '초기화면':\r\n print(\"User {} pushed '초기화면'\".format(user_key))\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '초기화면으로 돌아갑니다.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n # Sets up the user_key based route from below\r\n # 등하굣길 설정은 bus_key.db에 데이터베이스형식으로 저장\r\n elif clickedButton == '내 등하굣길 설정하기':\r\n if not isSetting or t.time() - settingTime > 20:\r\n isSetting = True\r\n settingTime = t.time()\r\n if len(bus_stn_setting_list) != 0:\r\n bus_stn_setting_list = []\r\n print(\"Setting list is not empty, Cleaning up...\")\r\n bus_stn_setting_list.append(user_key)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': 'Step 1 / 3: 버스를 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['관악01 (설정)', '동작13 (설정)', '5513 (설정)']\r\n }\r\n }\r\n )\r\n else:\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '현재 설정 중인 사용자가 있습니다. 잠시 후 다시 시도해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '동작13 (설정)':\r\n bus_stn_setting_list.append(13)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': 'Step 2 / 3: 등교 시 이용하는 버스정류장을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['대방역2번출구앞 (설정)', '현대아파트 (설정)', '노량진역 (설정)', '우성아파트 (설정)', '건영아파트 (설정)', '신동아상가 (설정)',\r\n '동작등기소 (설정)', '부강탕 (설정)', '밤골 (설정)', '약수맨션 (설정)', '빌라삼거리, 영도교회 (설정)', '방범초소 (설정)',\r\n '벽산아파트 (설정)']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '5513 (설정)':\r\n bus_stn_setting_list.append(5513)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': 'Step 2 / 3: 등교 시 이용하는 버스정류장을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['관악구청 (설정)', '서울대입구 (설정)', '봉천사거리, 봉천중앙시장 (설정)', '봉원중학교, 행운동우성아파트 (설정)',\r\n '관악푸르지오아파트 (설정)', '봉현초등학교 (설정)', '벽산블루밍벽산아파트303동앞 (설정)']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '관악01 (설정)':\r\n bus_stn_setting_list.append(1)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': 'Step 2 / 3: 등교 시 이용하는 버스정류장을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['봉천역 (설정)', '두산아파트입구 (설정)', '현대시장 (설정)', '구암초등학교정문 (설정)', '성현동주민센터 (설정)',\r\n '구암어린이집앞 (설정)',\r\n '숭실대입구역2번출구 (설정)', '봉천고개현대아파트 (설정)', '봉현초등학교_01 (설정)', '관악드림타운115동 (설정)']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton in setting01:\r\n bus_stn_setting_list.append(bus_stn_dict_01.get(clickedButton.replace(' (설정)', ''))[0])\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': 'Step 3 / 3: 하교방향을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['벽산아파트방면 (설정)', '관악드림타운아파트방면 (설정)']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton in setting13:\r\n bus_stn_setting_list.append(bus_stn_dict_13.get(clickedButton.replace(' (설정)', ''))[0])\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': 'Step 3 / 3: 하교방향을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['벽산아파트방면 (설정)', '관악드림타운아파트방면 (설정)']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton in setting5513:\r\n bus_stn_setting_list.append(bus_stn_dict_5513.get(clickedButton.replace(' (설정)', ''))[0])\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': 'Step 3 / 3: 하교방향을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['벽산아파트방면 (설정)', '관악드림타운아파트방면 (설정)']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton in ['벽산아파트방면 (설정)', '관악드림타운아파트방면 (설정)']:\r\n bus_stn_setting_list.append(['21243', '21244'][['벽산아파트방면 (설정)', '관악드림타운아파트방면 (설정)'].index(clickedButton)])\r\n\r\n c = bus_db.cursor()\r\n\r\n c.execute(\"SELECT * FROM BusService WHERE user_key = ?\", (bus_stn_setting_list[0],))\r\n if c.fetchall() != []:\r\n c.execute(\"DELETE FROM BusService WHERE user_key = ?\", (bus_stn_setting_list[0],))\r\n print(\"This user already have the route, Deleting it ... \")\r\n\r\n c.execute(\"INSERT INTO BusService VALUES (?, ?, ?, ?)\",\r\n (bus_stn_setting_list[0], bus_stn_setting_list[1], bus_stn_setting_list[2], bus_stn_setting_list[3]))\r\n bus_db.commit()\r\n\r\n c.execute(\"SELECT * FROM BusService WHERE user_key = ?\", (bus_stn_setting_list[0],))\r\n print(c.fetchall())\r\n print(\"User route has been successfully created. ^ \")\r\n isSetting = False\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '설정되었습니다. 이제 간편하게 내 등하굣길 버스안내를 이용하실 수 있습니다.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n # Setting user_key based route finished.\r\n\r\n elif clickedButton == '구암고 급식안내':\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '중 / 석식을 선택해 주세요.\\n매일 오후 5시 이후에는 다음날 급식을 안내합니다.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['중식', '석식', '초기화면']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton in ['중식', '석식']:\r\n tmr = 0\r\n flist = foodie(str(t.ctime())[:3], 0)\r\n day, m, d = map(int, flist)\r\n print(\"User {} is trying to get meal task\".format(user_key))\r\n if int(str(t.ctime())[11:13]) > 16: # 5시가 지나면 내일 밥을 보여준다\r\n tmr = 1\r\n if day < 6:\r\n day += 1\r\n else:\r\n day = 0\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🍴 {}의 {}식단 🍴\\n📜 {} / {} ( {} ) 📜\\n{}'.format('오늘' if tmr == 0 else '내일',\r\n '중식' if clickedButton == '중식' else '석식',\r\n m, d if tmr == 0 else d + 1,\r\n '월화수목금토일'[day],\r\n lunch[day] if clickedButton == '중식' else\r\n dinner[day])\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '내 등굣길 버스안내':\r\n c = bus_db.cursor()\r\n c.execute(\"SELECT * FROM BusService WHERE user_key = ?\", (user_key,))\r\n school = c.fetchone()\r\n if not school:\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '내 등/하굣길이 설정돼 있지 않습니다. 초기화면에서 설정해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n if school[1] == 13:\r\n for stn_name, stn_list in bus_stn_dict_13.items():\r\n if stn_list[0] == school[2]:\r\n busStn, n = stn_name, stn_list[1]\r\n break\r\n busList = bus(n, school[2], 13)\r\n bus01, bus02, tayo1, tayo2 = map(str, busList)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n{}\\n\\n다음 🚌 : {}{}\\n{}'.format(busStn, school[2], bus01,\r\n ' 도착 예정' if bus01 not in [\r\n '출발대기',\r\n '운행종료'] else '',\r\n tayo1, bus02,\r\n ' 도착 예정' if bus02 not in [\r\n '출발대기',\r\n '운행종료'] else '',\r\n tayo2)\r\n\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n elif school[1] == 5513:\r\n for stn_name, stn_list in bus_stn_dict_5513.items():\r\n if stn_list[0] == school[2]:\r\n busStn, n = stn_name, stn_list[1]\r\n break\r\n bus(n, school[2], 5513)\r\n busList = bus(n, school[2], 5513)\r\n bus01, bus02 = map(str, busList)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n\\n다음 🚌 : {}{}\\n'.format(busStn, school[2], bus01,\r\n ' 도착 예정' if bus01 not in [\r\n '출발대기', '운행종료'] else '',\r\n bus02,\r\n ' 도착 예정' if bus02 not in [\r\n '출발대기', '운행종료'] else '')\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n # 01\r\n else:\r\n for stn_name, stn_list in bus_stn_dict_01.items():\r\n if stn_list[0] == school[2]:\r\n busStn, n = stn_name, stn_list[1]\r\n break\r\n bus01, bus02 = map(str, bus(n, school[2], 1))\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n\\n다음 🚌 : {}{}\\n'.format(busStn, school[2], bus01,\r\n ' 도착 예정' if bus01 not in [\r\n '출발대기', '운행종료'] else '',\r\n bus02,\r\n ' 도착 예정' if bus02 not in [\r\n '출발대기', '운행종료'] else '')\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '내 하굣길 버스안내':\r\n c = bus_db.cursor()\r\n c.execute(\"SELECT * FROM BusService WHERE user_key = ?\", (user_key,))\r\n school = c.fetchone()\r\n if not school:\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '내 등/하굣길이 설정돼 있지 않습니다. 초기화면에서 설정해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n if school[1] == 13:\r\n bus01, bus02, tayo1, tayo2 = map(str, bus(1, school[3], 13))\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n{}\\n\\n다음 🚌 : {}{}\\n{}'.format('구암중고등학교', school[3],\r\n bus01,\r\n ' 도착 예정' if bus01 not in [\r\n '출발대기',\r\n '운행종료'] else '',\r\n tayo1, bus02,\r\n ' 도착 예정' if bus02 not in [\r\n '출발대기',\r\n '운행종료'] else '',\r\n tayo2)\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n elif school[1] == 5513:\r\n busList = bus(2, school[3], 5513)\r\n bus01, bus02 = map(str, busList)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n\\n다음 🚌 : {}{}\\n'.format('구암중고등학교', school[3], bus01,\r\n ' 도착 예정' if bus01 not in [\r\n '출발대기', '운행종료'] else '',\r\n bus02,\r\n ' 도착 예정' if bus02 not in [\r\n '출발대기', '운행종료'] else '')\r\n\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n else:\r\n bus01, bus02 = map(str, bus(2, school[3], 1))\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n\\n다음 🚌 : {}{}\\n'.format('구암중고등학교', school[3], bus01,\r\n ' 도착 예정' if bus01 not in [\r\n '출발대기', '운행종료'] else '',\r\n bus02,\r\n ' 도착 예정' if bus02 not in [\r\n '출발대기', '운행종료'] else '')\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '등하교 버스안내':\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '노선 및 방향을 선택해 주세요'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['초기화면', '관악01 - 등교', '관악01 - 하교', '동작13 - 등교', '동작13 - 하교', '5513 - 등교', '5513 - 하교']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '5513 - 등교':\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '정류장을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['초기화면', '관악구청', '서울대입구', '봉천사거리, 봉천중앙시장', '봉원중학교, 행운동우성아파트',\r\n '관악푸르지오아파트', '봉현초등학교', '벽산블루밍벽산아파트303동앞']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '동작13 - 등교':\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '정류장을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['초기화면', '대방역2번출구앞', '현대아파트', '노량진역', '우성아파트', '건영아파트', '신동아상가',\r\n '동작등기소', '부강탕', '밤골', '약수맨션', '빌라삼거리, 영도교회', '방범초소', '벽산아파트']\r\n\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '관악01 - 등교':\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '정류장을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['초기화면', '봉천역', '두산아파트입구', '현대시장', '구암초등학교정문', '성현동주민센터', '구암어린이집앞',\r\n '숭실대입구역2번출구', '봉천고개현대아파트', '봉현초등학교_01', '관악드림타운115동']\r\n }\r\n }\r\n )\r\n\r\n if clickedButton in bus_stn_dict_13.keys():\r\n busStop, n = map(str, bus_stn_dict_13.get(clickedButton))\r\n busList = bus(int(n), busStop, 13)\r\n bus01, bus02, tayo1, tayo2 = map(str, busList)\r\n\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n{}\\n\\n다음 🚌 : {}{}\\n{}'.format(clickedButton, busStop, bus01,\r\n ' 도착 예정' if bus01 not in [\r\n '출발대기', '운행종료'] else '',\r\n tayo1, bus02,\r\n ' 도착 예정' if bus02 not in [\r\n '출발대기', '운행종료'] else '',\r\n tayo2)\r\n\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n if clickedButton in bus_stn_dict_5513.keys():\r\n busStop, n = map(str, bus_stn_dict_5513.get(clickedButton))\r\n busList = bus(int(n), busStop, 5513)\r\n bus01, bus02 = map(str, busList)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n\\n다음 🚌 : {}{}\\n'.format(clickedButton, busStop, bus01,\r\n ' 도착 예정' if bus01 not in ['출발대기',\r\n '운행종료'] else '',\r\n bus02,\r\n ' 도착 예정' if bus02 not in ['출발대기',\r\n '운행종료'] else '')\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n if clickedButton in bus_stn_dict_01.keys():\r\n busStop, n = map(str, bus_stn_dict_01.get(clickedButton))\r\n busList = bus(int(n), busStop, 1)\r\n bus01, bus02 = map(str, busList)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n\\n다음 🚌 : {}{}\\n'.format(clickedButton, busStop, bus01,\r\n ' 도착 예정' if bus01 not in ['출발대기',\r\n '운행종료'] else '',\r\n bus02,\r\n ' 도착 예정' if bus02 not in ['출발대기',\r\n '운행종료'] else '')\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n # No need to touch below, Final\r\n\r\n elif clickedButton == '동작13 - 하교':\r\n\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '동작13 버스 방향을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['관악드림타운북문 방면 (동작13)', '벽산아파트 방면 (동작13)', '초기화면']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '5513 - 하교':\r\n\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '5513 버스 방향을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['관악드림타운북문 방면 (5513)', '벽산아파트 방면 (5513)', '초기화면']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '관악01 - 하교':\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '관악01 버스 방향을 선택해 주세요.'\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['관악드림타운북문 방면 (관악01)', '벽산아파트 방면 (관악01)', '초기화면']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton in homeBusStop13:\r\n busStop = ['21244', '21243'][homeBusStop13.index(clickedButton)]\r\n busList = bus(1, busStop, 13)\r\n bus01, bus02, tayo1, tayo2 = map(str, busList)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n{}\\n\\n다음 🚌 : {}{}\\n{}'.format(clickedButton, busStop, bus01,\r\n ' 도착 예정' if bus01 not in [\r\n '출발대기', '운행종료'] else '',\r\n tayo1, bus02,\r\n ' 도착 예정' if bus02 not in [\r\n '출발대기', '운행종료'] else '',\r\n tayo2)\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton in homeBusStop5513:\r\n busStop = ['21244', '21243'][homeBusStop5513.index(clickedButton)]\r\n busList = bus(2, busStop, 5513)\r\n bus01, bus02 = map(str, busList)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n\\n다음 🚌 : {}{}\\n'.format(clickedButton, busStop, bus01,\r\n ' 도착 예정' if bus01 not in ['출발대기',\r\n '운행종료'] else '',\r\n bus02,\r\n ' 도착 예정' if bus02 not in ['출발대기',\r\n '운행종료'] else '')\r\n\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton in homeBusStop01:\r\n busStop = ['21244', '21243'][homeBusStop01.index(clickedButton)]\r\n busList = bus(0, busStop, 1)\r\n bus01, bus02 = map(str, busList)\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': '🚏 {} ( {} )\\n\\n이번 🚌 : {}{}\\n\\n다음 🚌 : {}{}\\n'.format(clickedButton, busStop, bus01,\r\n ' 도착 예정' if bus01 not in ['출발대기',\r\n '운행종료'] else '',\r\n bus02,\r\n ' 도착 예정' if bus02 not in ['출발대기',\r\n '운행종료'] else '')\r\n\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말']\r\n }\r\n }\r\n )\r\n\r\n elif clickedButton == '도움말':\r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': \"안녕하세요! 구암고등학교 급식 및 버스정보를 알려주는 알렉스봇입니다 :)\\n\"\r\n \"원하시는 메뉴 중 하나를 골라 정보를 열람하시면 됩니다.\\n\"\r\n \"오류나 추가 요구사항은 관리자에게 문의하거나 오픈채팅을 통해 부탁드립니다.\\n\"\r\n \"자신이 등하교하는 정류장이 존재하지 않는다면 문의해주세요.\\n\"\r\n \"\\n============\\n\\n\"\r\n \"자료제공 : 서울특별시교육청, 서울특별시버스정보시스템\\n\"\r\n \"플러스친구 개발 : 구암고등학교 2018학년도 졸업, 건국대학교 컴퓨터공학과 19' 이동훈 \\n\"\r\n \"Github : https://github.com/donghoony/guahmchatbot\\n\"\r\n \"이용해 주셔서 고맙습니다 :)\"\r\n\r\n },\r\n\r\n\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말', '급식 새로고침']\r\n }\r\n }\r\n )\r\n elif clickedButton == '급식 새로고침':\r\n lunch = []\r\n dinner = []\r\n foodie('Mon', 1)\r\n \r\n return JsonResponse(\r\n {\r\n 'message': {\r\n 'text': \"새로고침되었습니다.\"\r\n\r\n },\r\n 'keyboard': {\r\n 'type': 'buttons',\r\n 'buttons': ['구암고 급식안내', '내 등굣길 버스안내', '내 하굣길 버스안내', '등하교 버스안내', '내 등하굣길 설정하기', '도움말', '급식 새로고침']\r\n }\r\n }\r\n )\r\n" }, { "alpha_fraction": 0.6195651888847351, "alphanum_fraction": 0.72826087474823, "avg_line_length": 22, "blob_id": "0e82f2492a26f341a3ec884629444021195af99d", "content_id": "e7a431b3a9627156c79afeeaca4f337a316e1880", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 170, "license_type": "no_license", "max_line_length": 46, "num_lines": 4, "path": "/README.md", "repo_name": "donghoony/guahmchatbot", "src_encoding": "UTF-8", "text": "# guahmchatbot\n2018년 구암고등학교의 급식 / 버스 정보 안내를 위해 만들어진 챗봇 소스입니다.\n\n2018학년도 졸업생 / KONKUK '19 이동훈\n" } ]
4
ArtDark/app-ideas-python
https://github.com/ArtDark/app-ideas-python
b57a353b63c56ffdaf8de9089be9663368cef246
1387db6c781b52a2293702fb770702b384b4bf6d
8e13006d7a19a89a218e93b4f66f367bb495236b
refs/heads/master
2020-07-31T01:32:44.374942
2019-09-26T18:48:44
2019-09-26T18:48:44
210,434,872
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4063670337200165, "alphanum_fraction": 0.41385766863822937, "avg_line_length": 22.2608699798584, "blob_id": "77b4ce55ae7c5a5d2d84d52d90f7d5fb5620346f", "content_id": "8024d50d2bb5a01c5a7c087f245180c3af0f8bd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 534, "license_type": "no_license", "max_line_length": 60, "num_lines": 23, "path": "/Bin2Dec.py", "repo_name": "ArtDark/app-ideas-python", "src_encoding": "UTF-8", "text": "print(\"This program convert binary numbers to decimal.\")\n\ndef main():\n while True:\n try:\n num = input('Enter up to 8 binary digits: ')\n if len(num) > 8:\n print(\"Please, enter up to 8 binary digits\")\n \n else: \n bin_num = int(num, 2)\n print(\"In Dec: \",bin_num)\n break\n \n except ValueError:\n print(\"\\nWrong digit!\\n\")\n \n \n \n\n\nif __name__ == \"__main__\":\n main()" } ]
1
Openmail/pytaboola
https://github.com/Openmail/pytaboola
7c58aaea58969727649667749cf333a23024202f
957fc516c946ab12d2ad34958a640f43763d8b4a
de81a020145542ec275932f16644cdd781e95103
refs/heads/master
2022-11-03T22:41:26.950829
2022-10-17T15:25:49
2022-10-17T15:25:49
189,670,565
0
0
MIT
2019-05-31T23:43:48
2022-10-13T14:55:47
2022-10-17T15:25:49
Python
[ { "alpha_fraction": 0.5994590520858765, "alphanum_fraction": 0.5994590520858765, "avg_line_length": 33.17647171020508, "blob_id": "68ffac9f3a1863e4d7e9e593c7cd239208a80a26", "content_id": "2a1e04d099216e199d058572cfca32be0e2724ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4067, "license_type": "permissive", "max_line_length": 86, "num_lines": 119, "path": "/pytaboola/services/report.py", "repo_name": "Openmail/pytaboola", "src_encoding": "UTF-8", "text": "import logging\nfrom datetime import datetime, date\n\nfrom pytaboola.services.base import AccountScopedService\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ReportService(AccountScopedService):\n report_name = None\n\n allowed_dimensions = ()\n\n allowed_filters = ()\n\n def __prepare_filters(self, start, end, **filters):\n assert isinstance(start, (datetime, date)), \\\n \"Start date filter must be a date/datetime instance\"\n assert isinstance(end, (datetime, date)), \\\n \"End date filter must be a date/datetime instance\"\n\n f = {'start_date': start.isoformat(),\n 'end_date': end.isoformat()}\n\n for key, value in filters.items():\n if key in self.allowed_filters:\n f[key] = value\n else:\n logger.debug('%s is not allowed as a filter for %s',\n key, self.__class__.__name__)\n return f\n\n def build_uri(self, dimension=None):\n endpoint = '{}/reports/{}/dimensions/{}'.format(\n self.account_id, self.report_name, dimension)\n return super().build_uri(endpoint)\n\n def fetch(self, dimension, start_date, end_date, **filters):\n if not self.report_name:\n raise NotImplementedError('ReportService must be subclassed')\n if dimension not in self.allowed_dimensions:\n raise ValueError('Dimension %s is not allowed for %s. '\n 'Must be one of %s' % (dimension,\n self.__class__.__name__,\n self.allowed_dimensions))\n\n real_filters = self.__prepare_filters(start_date, end_date, **filters)\n\n return self.execute('GET', self.build_uri(dimension),\n query_params=real_filters)\n\n\nclass CampaignSummaryReport(ReportService):\n report_name = 'campaign-summary'\n\n allowed_dimensions = (\n 'day', 'week', 'month', 'by_hour_of_day', 'content_provider_breakdown',\n 'campaign_breakdown', 'site_breakdown', 'country_breakdown',\n 'platform_breakdown', 'campaign_day_breakdown', 'campaign_hour_breakdown',\n 'campaign_site_day_breakdown',\n )\n\n allowed_filters = ('campaign', 'platform', 'country', 'site')\n\n\nclass TopCampaignContentReport(ReportService):\n report_name = 'top-campaign-content'\n\n allowed_dimensions = ('item_breakdown', )\n\n allowed_filters = ('campaign', )\n\n\nclass RevenueSummaryReport(ReportService):\n report_name = 'revenue-summary'\n\n allowed_dimensions = (\n 'day', 'week', 'month', 'page_type_breakdown',\n 'placement_breakdown', 'site_breakdown', 'country_breakdown',\n 'platform_breakdown', 'day_site_placement_breakdown',\n 'day_site_placement_country_platform_breakdown',\n 'day_site_page_type_country_platform_breakdown',\n )\n\n allowed_filters = ('page_type', 'placement', 'country', 'platform')\n\n\nclass VisitValueReport(ReportService):\n report_name = 'visit-value'\n\n allowed_dimensions = (\n 'day', 'week', 'month', 'by_referral', 'landing_page_breakdown',\n 'platform_breakdown', 'country_breakdown', 'page_type_breakdown',\n 'day_referral_landing_page_breakdown', 'by_source_medium',\n 'by_campaign', 'by_custom_tracking_code',\n 'by_referral_and_tracking_code',\n )\n\n allowed_filters = (\n 'referral_domain', 'landing_page', 'country',\n 'platform', 'campaign_source', 'campaign_medium',\n 'campaign_term', 'campaign_content', 'campaign_name',\n 'custom_key', 'custom_value', 'page_type',\n )\n\n\nclass RecirculationSummaryReport(ReportService):\n report_name = 'recirc-summary'\n\n allowed_dimensions = (\n 'day', 'week', 'month', 'page_type_breakdown',\n 'placement_breakdown', 'site_breakdown', 'country_breakdown',\n 'platform_breakdown', 'day_site_placement_breakdown',\n )\n\n allowed_filters = (\n 'page_type', 'placement', 'country', 'platform',\n )\n" }, { "alpha_fraction": 0.7391139268875122, "alphanum_fraction": 0.7467198967933655, "avg_line_length": 28.88068199157715, "blob_id": "7484c907ff529b560cf537672c2f2ed84acf107f", "content_id": "8891ba5157d96e535c34cc3de0e700e1a047ab44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5259, "license_type": "permissive", "max_line_length": 140, "num_lines": 176, "path": "/README.md", "repo_name": "Openmail/pytaboola", "src_encoding": "UTF-8", "text": "# pytaboola\nPython client for Taboola API (https://github.com/taboola/Backstage-API).\nBefore any use of this client, you must have gotten your API client ID and client secret from your Taboola account manager.\n\nClient ID is required for any usage.\n\n\n## Authentication and authorization\n\nThis client supports both access_token/refresh_token and\nclient_id/client_secret OAuth2 authorization methods.\n\nThe access_token/refresh_token method is the recommended one, but\nfollowing examples will use the other one as it is easier to implement.\n\n\n### Simple Connection\nExample of a simple connection using client_id/client_secret.\n```python\nCLIENT_ID = 'XXXXX'\nCLIENT_SECRET = 'YYYYY'\n\nfrom pytaboola import TaboolaClient\nclient = TaboolaClient(CLIENT_ID, client_secret=CLIENT_SECRET)\nclient.token_details\n> {'account_id': 'my-taboola-account',\n 'expires_in': 43189,\n 'full_name': 'User Name',\n 'username': '[email protected]'}\n```\n\n## Services\nHere is a quick description of the services provided by this client.\n\n### Account listing\nA service with only one method, allowing to list advertiser accounts linked to your main Taboola account.\nThis service is read-only. \n\n```python\nCLIENT_ID = 'XXXXX'\nCLIENT_SECRET = 'YYYYY'\n\nfrom pytaboola import TaboolaClient\nfrom pytaboola.services import AccountService\nclient = TaboolaClient(CLIENT_ID, client_secret=CLIENT_SECRET)\nservice = AccountService(client)\nservice.list()\n>>> {'results': [{'account_id': 'my-first-acount',\n 'campaign_types': ['PAID'],\n 'id': 1111111,\n 'name': 'My First Taboola Account',\n 'partner_types': ['ADVERTISER'],\n 'type': 'PARTNER'},\n {'account_id': 'my-other-account',\n 'campaign_types': ['PAID'],\n 'id': 2222222,\n 'name': 'My Other Taboola Account',\n 'partner_types': ['ADVERTISER'],\n 'type': 'PARTNER'}]}\n```\n\n### Campaign CRUD\n\nSimple CRUD service implementing listing, access, creation, edition.\nAll requests are scoped by account. So, it is impossible to list campaigns cross accounts.\n\n\nService is instanciated as follow.\n```python\nCLIENT_ID = 'XXXXX'\nCLIENT_SECRET = 'YYYYY'\n\nfrom pytaboola import TaboolaClient\nfrom pytaboola.services import CampaignService\nclient = TaboolaClient(CLIENT_ID, client_secret=CLIENT_SECRET)\nservice = CampaignService(client, 'my-account-id')\n```\n\n#### Methods\n##### List all campaigns for an account :\n```\nservice.list()\n```\n\n##### Get a campaign :\n```\nservice.get('my-campaign-id')\n```\n\n##### Update a campaign :\n```\nservice.get('my-campaign-id', **attrs)\n```\nPlease note that update is partial. To delete a field, you will have to set it at None explicitly (if this attribute is nullable obviously).\n\n##### Create a campaign :\n```\nservice.create(**attrs)\n```\n\nIn these last examples, ```attrs``` is a dict containing attributes of the campaign.\nFor more information on campaign attributes, please see the Backstage API documentation at\nhttps://github.com/taboola/Backstage-API/blob/master/Backstage%20API%20-%20Campaigns.pdf\n\n\n### Campaign Item CRUD\nAs with Campaign CRUD service, this is a simple CRUD service implementing listing, access, creation, edition. \nAll requests are scoped by campaign.\n\n```python\nCLIENT_ID = 'XXXXX'\nCLIENT_SECRET = 'YYYYY'\n\nfrom pytaboola import TaboolaClient\nclient = TaboolaClient(CLIENT_ID, client_secret=CLIENT_SECRET)\nservice = CampaignItemService(client, 'my-account-id', 'my-campaign-id')\nservice.list()\n```\n\n#### Methods\nBasic CRUD methods have the same signature as the ones of the campaign service.\n\n##### List all RSS Children for this campaign :\n```\nservice.children()\n```\n\n##### Get a child item by its ID :\n```\nservice.child('my-child-id')\n```\n\n##### Update a child :\n```\nservice.child('my-child-id', **attrs)\n```\nFor more information on campaign item attributes and what RSS Children are, please see the Backstage API documentation at\nhttps://github.com/taboola/Backstage-API/blob/master/Backstage%20API%20-%20Campaign%20Items.pdf\n\n### Reports\n\nAll report services have only a fetch method, with the following signature :\n\n```python\ndef fetch(self, dimension, start_date, end_date, **filters)\n```\nwhere dimension is the aggregation view of the report, start_date and end_date delimitate the period to fetch the report on,\n and filters are ways to narrow down your report data.\n\nFor more information, please refer to the Backstage API documentation :\nhttps://github.com/taboola/Backstage-API/blob/master/Backstage%20API%20-%20Reports.pdf\n\nAvailable services are :\n * CampaignSummaryReport\n * TopCampaignContentReport\n * RevenueSummaryReport\n * VisitValueReport\n * RecirculationSummaryReport\n\n\n## Todo:\n### Resource services\nResource services are available in this client, but not all endpoints are available.\nAlso, they are not properly documented.\n\n### Testing\nThere is not much intelligence in this wrapper,\nbut all utility functions (such as response parsing) and authentication /\nrefresh workflow should be tested to avoid regressions.\n\n### Data validators\nAs for now, all data validation is delegated to the Taboola API. It may be useful to had a small bit of data type checking before any call.\n\n### Authentication\nuser/password authentication method is not implemented. It should be useless in any production environment,\nbut may be used as a fast POC/testing authentication system.\n" }, { "alpha_fraction": 0.9047619104385376, "alphanum_fraction": 0.9047619104385376, "avg_line_length": 42, "blob_id": "6f35a688fe9b291d4bac0681f2e73d3971cca2b5", "content_id": "91a50c39cf3d401ee6a7a290edb9d36a330b0540", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 42, "license_type": "permissive", "max_line_length": 42, "num_lines": 1, "path": "/pytaboola/__init__.py", "repo_name": "Openmail/pytaboola", "src_encoding": "UTF-8", "text": "from pytaboola.client import TaboolaClient" }, { "alpha_fraction": 0.5744949579238892, "alphanum_fraction": 0.5753366947174072, "avg_line_length": 31.108108520507812, "blob_id": "0a58c7e4b664500162e0d370ec218e13b7188f7e", "content_id": "e05423b857ee1eb60708dd68779009e910a2ff8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2376, "license_type": "permissive", "max_line_length": 81, "num_lines": 74, "path": "/pytaboola/services/service.py", "repo_name": "Openmail/pytaboola", "src_encoding": "UTF-8", "text": "import logging\nfrom pytaboola.services.base import CrudService, BaseService\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdvertiserService(BaseService):\n '''\n Only return advertisers under a container to handle\n situations where account permissions overlap or\n are shared across multiple users.\n '''\n\n def __init__(self, client, container_id):\n super().__init__(client)\n self.container_id = container_id\n\n def build_uri(self, endpoint=None):\n return '{}/{}/advertisers'.format(self.endpoint, self.container_id)\n\n def list(self):\n return self.execute('GET', self.build_uri())\n\n\nclass AccountService(BaseService):\n endpoint = '{}/{}'.format(BaseService.endpoint,\n 'users/current/allowed-accounts/')\n\n def __init__(self, client):\n super().__init__(client)\n\n def list(self):\n return self.execute('GET', self.build_uri())\n\n\nclass CampaignService(CrudService):\n\n def build_uri(self, endpoint=None):\n base_endpoint = '{}/{}/campaigns/'.format(self.endpoint, self.account_id)\n if not endpoint:\n return base_endpoint\n while endpoint.startswith('/'):\n endpoint = endpoint[1:]\n return '{}/{}'.format(base_endpoint, endpoint)\n\n\nclass CampaignItemService(CrudService):\n\n def __init__(self, client, account_id, campaign_id):\n super().__init__(client, account_id)\n self.campaign_id = campaign_id\n\n def build_uri(self, endpoint=None):\n base_endpoint = '{}/{}/campaigns/{}/items/'.format(self.endpoint,\n self.account_id,\n self.campaign_id)\n if not endpoint:\n return base_endpoint\n while endpoint.startswith('/'):\n endpoint = endpoint[1:]\n if not endpoint.endswith('/'):\n endpoint += '/'\n return '{}/{}'.format(base_endpoint, endpoint)\n\n def children(self):\n return self.execute('GET', self.build_uri('children'))\n\n def child(self, item_id):\n return self.execute('GET', self.build_uri('children/{}'.format(item_id)))\n\n def update_child(self, item_id, **attrs):\n return self.execute('POST',\n self.build_uri('children/{}'.format(item_id)),\n **attrs)\n" }, { "alpha_fraction": 0.5061728358268738, "alphanum_fraction": 0.5226337313652039, "avg_line_length": 16.780487060546875, "blob_id": "8e7c48feb5c7dcdcf470335d9bbb8ce89833e74c", "content_id": "58881ccb71c4d435efca566947d2adece0ffb31a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "permissive", "max_line_length": 62, "num_lines": 41, "path": "/pytaboola/errors.py", "repo_name": "Openmail/pytaboola", "src_encoding": "UTF-8", "text": "class TaboolaError(BaseException):\n \"\"\"\n Base error class for handling Taboola backstage API errors\n \"\"\"\n\n def __init__(self, error, response):\n self.error = error\n self.response = response\n\n def __str__(self):\n return '{} [{}]: {}'.format(self.__class__.__name__,\n self.response.status_code,\n self.error)\n\n\nclass BadRequest(TaboolaError):\n \"\"\"\n 400 HTTP Errors\n \"\"\"\n pass\n\n\nclass Unauthorized(TaboolaError):\n \"\"\"\n 401 HTTP Errors\n \"\"\"\n pass\n\n\nclass NotFound(TaboolaError):\n \"\"\"\n 404 HTTP Errors\n \"\"\"\n pass\n\n\nclass ServerError(TaboolaError):\n \"\"\"\n 500 HTTP Errors\n \"\"\"\n pass\n" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.6875, "avg_line_length": 28.913043975830078, "blob_id": "14be64d6c29712b26063c4c8ad1f6e57aa2608bd", "content_id": "c1e3540a435acb6f262c41edb19724adeec42357", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1376, "license_type": "permissive", "max_line_length": 92, "num_lines": 46, "path": "/pytaboola/services/resource.py", "repo_name": "Openmail/pytaboola", "src_encoding": "UTF-8", "text": "import logging\n\nfrom pytaboola.services.base import BaseService\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ResourcesService(BaseService):\n endpoint = '{}/{}'.format(BaseService.endpoint, 'resources')\n\n def list(self):\n return self.execute('GET', self.build_uri())\n\n\nclass PlatformResourcesService(ResourcesService):\n endpoint = '{}/{}'.format(ResourcesService.endpoint, 'platforms')\n\n\nclass CountryResourcesService(ResourcesService):\n endpoint = '{}/{}'.format(ResourcesService.endpoint, 'countries')\n\n def _elements(self, country, element):\n return self.execute('GET', self.build_uri('{}/{}'.format(country.upper(), element)))\n\n def regions(self, country):\n return self._elements(country, 'regions')\n\n def postal_codes(self, country):\n return self._elements(country, 'postal_codes')\n\n def dmas(self):\n return self._elements('US', 'postal_codes')\n\n\nclass CampaignPropertiesResourcesService(ResourcesService):\n endpoint = '{}/{}'.format(ResourcesService.endpoint, 'campaigns_properties')\n\n def elements(self, item):\n return self.execute('GET', self.build_uri(item))\n\n def item_properties(self):\n return self.execute('GET', self.build_uri('items_properties'))\n\n def item_property_elements(self, item):\n return self.execute('GET', self.build_uri('items_properties/{}'.format(item)))\n" }, { "alpha_fraction": 0.6356877088546753, "alphanum_fraction": 0.640644371509552, "avg_line_length": 30.038461685180664, "blob_id": "a5ef464b1bd583e51d6857bd3186b4b1c65ae7fb", "content_id": "8c7aa255fa11834baf3e4e3b38629f754e857876", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 807, "license_type": "permissive", "max_line_length": 73, "num_lines": 26, "path": "/setup.py", "repo_name": "Openmail/pytaboola", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(\n name='pytaboola',\n version='0.1.1',\n packages=['pytaboola', 'pytaboola.utils', 'pytaboola.services'],\n url='https://github.com/dolead/pytaboola',\n keywords='taboola api',\n license='MIT',\n author='Antoine Francais',\n author_email='[email protected]',\n maintainer=\"Dolead\",\n maintainer_email=\"[email protected]\",\n description='Python client for Taboola API',\n long_description=long_description,\n long_description_content_type='text/markdown',\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"License :: OSI Approved :: MIT License\"],\n install_requires=['requests', 'python-dateutil']\n)\n" }, { "alpha_fraction": 0.7866666913032532, "alphanum_fraction": 0.7866666913032532, "avg_line_length": 36.5, "blob_id": "e8f930540b76da731884549dc38f63c14c1b4d1e", "content_id": "d257315ba0e89c367f09be73f7de34b2a42cc761", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 450, "license_type": "permissive", "max_line_length": 72, "num_lines": 12, "path": "/pytaboola/services/__init__.py", "repo_name": "Openmail/pytaboola", "src_encoding": "UTF-8", "text": "from pytaboola.services.service import (\n CampaignService,\n AccountService, CampaignItemService\n)\nfrom pytaboola.services.report import (\n CampaignSummaryReport, RecirculationSummaryReport,\n TopCampaignContentReport, RevenueSummaryReport, VisitValueReport\n)\nfrom pytaboola.services.resource import (\n CampaignPropertiesResourcesService, CountryResourcesService,\n PlatformResourcesService, ResourcesService\n)\n" }, { "alpha_fraction": 0.5506557822227478, "alphanum_fraction": 0.5517865419387817, "avg_line_length": 34.94308853149414, "blob_id": "8e12865a485b295f005a5d1d573b779c38ecbe3a", "content_id": "bfcfa09cb923bca6fe3ea47976126f740c3e6f50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4422, "license_type": "permissive", "max_line_length": 104, "num_lines": 123, "path": "/pytaboola/client.py", "repo_name": "Openmail/pytaboola", "src_encoding": "UTF-8", "text": "import json\nimport logging\nimport requests\nimport tenacity\nfrom requests.exceptions import ReadTimeout, ConnectTimeout\n\nfrom pytaboola.errors import Unauthorized\nfrom pytaboola.utils import parse_response\n\nlogger = logging.getLogger(__name__)\n\n\nclass TaboolaClient:\n \"\"\"\n\n \"\"\"\n\n base_url = 'https://backstage.taboola.com'\n\n def __init__(self, client_id, client_secret=None,\n access_token=None, refresh_token=None,\n timeout=None):\n \"\"\"\n timeout (in seconds) will be passed to requests.request().\n If timeout is not set, then default to None. Which will wait forever.\n \"\"\"\n\n assert client_secret or access_token, \"Must provide either the client secret or an access token\"\n self.access_token = access_token\n self.refresh_token = refresh_token\n self.client_id = client_id\n self.client_secret = client_secret\n self.timeout = timeout\n\n if not self.access_token:\n self.refresh()\n\n @property\n def oauth_uri(self):\n return 'backstage/oauth/token'.format(self.base_url)\n\n def __authenticate_secret(self):\n logger.debug('Requesting access token with '\n 'client_id(%s)/client_secret', self.client_id)\n\n result = self.execute('POST', self.oauth_uri,\n allow_refresh=False,\n raw=True,\n authenticated=False,\n client_id=self.client_id,\n client_secret=self.client_secret,\n grant_type='client_credentials')\n\n logger.debug('Response is %s', result)\n self.access_token = result.get('access_token')\n\n def __authenticate_refresh(self):\n if not (self.refresh_token and self.client_secret):\n return\n\n logger.debug('Requesting access token with '\n 'client_id(%s)/refresh token(%s)',\n self.client_id, self.refresh_token)\n\n result = self.execute('POST', self.oauth_uri,\n allow_refresh=False,\n raw=True,\n authenticated=False,\n client_id=self.client_id,\n client_secret=self.client_secret,\n refresh_token=self.refresh_token,\n grant_type='refresh_token')\n\n logger.debug('Response is %s', result)\n self.access_token = result.get('access_token')\n\n def refresh(self):\n if self.refresh_token:\n self.__authenticate_refresh()\n if not self.access_token and self.client_secret:\n self.__authenticate_secret()\n\n @property\n def authorization_header(self):\n if not self.access_token:\n raise Exception\n return {\n 'Authorization': 'Bearer {}'.format(self.access_token)\n }\n\n @property\n def token_details(self):\n return self.execute('GET', 'backstage/api/1.0/token-details/')\n\n @tenacity.retry(\n stop=tenacity.stop_after_attempt(6),\n wait=tenacity.wait_exponential(multiplier=1, exp_base=2),\n retry=tenacity.retry_if_exception_type((ReadTimeout, ConnectTimeout)),\n before_sleep=tenacity.before_sleep_log(logger, logging.INFO),\n )\n def execute(self, method, uri, query_params=None,\n allow_refresh=True, raw=False, authenticated=True,\n **payload):\n url = '{}/{}'.format(self.base_url, uri)\n headers = self.authorization_header if authenticated else {}\n if method.upper() in ('POST', 'PUT') and not raw:\n headers['Content-Type'] = 'application/json'\n\n try:\n data = None\n if payload:\n data = payload if raw else json.dumps(payload)\n result = requests.request(method, url, data=data,\n params=query_params,\n headers=headers,\n timeout=self.timeout)\n return parse_response(result)\n except Unauthorized:\n if not allow_refresh:\n raise\n self.refresh()\n return self.execute(method, uri, query_params=query_params,\n raw=raw, allow_refresh=False, **payload)\n\n" }, { "alpha_fraction": 0.6070865988731384, "alphanum_fraction": 0.6094487905502319, "avg_line_length": 24.399999618530273, "blob_id": "a03e889475a49ad336f793070824d19052529714", "content_id": "0eef59e3a81396d644f23c9d75b42974e3a74b11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1270, "license_type": "permissive", "max_line_length": 72, "num_lines": 50, "path": "/pytaboola/services/base.py", "repo_name": "Openmail/pytaboola", "src_encoding": "UTF-8", "text": "import logging\nfrom datetime import date, datetime\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseService:\n \"\"\"\n Service class, expose calls\n\n \"\"\"\n endpoint = 'backstage/api/1.0/'\n\n def __init__(self, client):\n self.client = client\n\n def build_uri(self, endpoint=None):\n if not endpoint:\n return self.endpoint\n while endpoint.startswith('/'):\n endpoint = endpoint[1:]\n return '{}/{}'.format(self.endpoint, endpoint)\n\n\n def execute(self, method, uri, query_params=None, **payload):\n return self.client.execute(method, uri,\n query_params=query_params, **payload)\n\n\nclass AccountScopedService(BaseService):\n\n def __init__(self, client, account_id):\n super().__init__(client)\n self.account_id = account_id\n\n\nclass CrudService(AccountScopedService):\n\n def list(self):\n return self.execute('GET', self.build_uri())['results']\n\n def get(self, element_id):\n return self.execute('GET', self.build_uri(element_id))\n\n def create(self, **attrs):\n return self.execute('POST', self.build_uri(), **attrs)\n\n def update(self, element_id, **attrs):\n return self.execute('POST', self.build_uri(element_id), **attrs)\n" } ]
10
lucbettaieb/Babby
https://github.com/lucbettaieb/Babby
e75835fb6d98aa9e33f5d42857d8d43d68627980
3eafc7b638e5a764fbe48523160cb5ea55e43124
78313232819b83582b62a8805e672c51fac8d531
refs/heads/master
2018-12-31T20:32:00.103583
2018-10-31T20:44:50
2018-10-31T20:44:50
15,647,392
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7455036044120789, "alphanum_fraction": 0.7491007447242737, "avg_line_length": 34.870967864990234, "blob_id": "2f356be603c7217326c083c6791f78951eaa2b9c", "content_id": "7511e57bc092ac5d5b96f340e91377cf1cb09762", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1113, "license_type": "no_license", "max_line_length": 238, "num_lines": 31, "path": "/README.md", "repo_name": "lucbettaieb/Babby", "src_encoding": "UTF-8", "text": "## Babby\nA bunch of code to make Babby alive\n\n---\n\nBabby comes alive with code! Babby is a robot that was originally built at MHacks II. While it didn't get much movement except for some kicking, its currently under development!\n\nBabby is and will be a simple version of the NASA ATHLETE rover platform. Check out more info and some pics here: https://seelio.com/w/b0o/babby\n\n\n### What is a Babby?\n\n\nA Babby is a small robot which moves in a manner similar to that of NASA's ATHLETE. Right now, a Babby (hopefully) works by building a terrain map from an range finder module and moving its legs via servo motors to correct for slopes etc.\n\n### How is babby formed?\n\nRight now, our babby is constructed with the following:\n\n - A Raspberry Pi (Model B (Perhaps being removed))\n - An Arduino board (Yún)\n - 4 DC Motors\n - 2 Dual Channel Serial Motor Controllers (Perhaps going to be replaced with a simpler H-Bridge)\n - 4 Servo Motors\n - A LASER-cut wooden frame\n - An ultrasonic range finder\n\n### What is the status of the project?\n\nThe current status of our babby project is:\n In progress; not yet functional\n" }, { "alpha_fraction": 0.5768057107925415, "alphanum_fraction": 0.6012207269668579, "avg_line_length": 32.169490814208984, "blob_id": "d8beea4dfc6f36d72036faa9ca94c1f366f97e0b", "content_id": "09515a978a9aec82eb9d1bace52dab69d5b5adc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1966, "license_type": "no_license", "max_line_length": 103, "num_lines": 59, "path": "/babby/resources/Servo.py", "repo_name": "lucbettaieb/Babby", "src_encoding": "UTF-8", "text": "#Servo Motor Module\n#Andrew M. Blasius\n\n'''\nServos Expect to receive a pulse every 20 ms => 50 times/sec => 50Hz\n -0 degrees corresponds to a pulse width of 1 ms => on for 5 % => DC = 5\n -90 degrees corresponds to a pulse width of 1.5ms => on for 7.5% => DC = 7.5\n -180 degrees corresponds to a pulse width of 2 ms => on for 10.0% => DC = 10.0\n'''\n\nimport time\nimport RPi.GPIO as GPIO\nimport gc\n\nclass servo:\n \n def __init__(self,pin,initalAngle,minPulseTime,maxPulseTime,freq=50.0,angularOffset=0):\n '''minPulseTime and maxPulseTime are the pulse widths (in milliseconds)\n which correspond to 0 degrees and 180 degrees, respectively\n ANGLES SHOULD BE KEPT IN DEGREES'''\n \n GPIO.setup(pin,GPIO.OUT)\n self.pulseTime = 1.0/freq * (10**3) #Total Pulse [milliseconds]\n \n self.lower = minPulseTime / self.pulseTime\n self.upper = maxPulseTime / self.pulseTime\n \n self.angularOffset = angularOffset\n \n self.pin = GPIO.PWM(pin,freq) #Declare PWM pin\n\n #Initialization\n self.cycle = getCycle(initialAngle)\n self.angle = initialAngle\n self.pin.start( self.cycle ) \n \n gc.collect() #Collect Garbage\n \n \n def getCycle(self,angle):\n #Uses affine map to calculate duty cycle from lower limit, upper limit and position\n cycle = 100 * ( self.lower + (self.upper - self.lower) * self.angle / 180.0 ) / self.pulseTime \n gc.collect() #Collect Garbage\n return cycle\n \n \n def setPosition(self,angle):\n if (degree < self.lower) or (degree > self.upper):\n print 'Position outside of range'\n return\n else:\n self.angle = angle - self.angularOffset\n self.cycle = self.getCycle(angle)\n self.pin.ChangeDutyCycle(self.cycle)\n \n \n def end(self):\n self.pin.stop()\n gc.collect() #Collect Garbage\n \n" }, { "alpha_fraction": 0.5390127301216125, "alphanum_fraction": 0.5406050682067871, "avg_line_length": 22.716981887817383, "blob_id": "f9e5c4c20f63ebda6822c301d72296b1488a39f0", "content_id": "edad539c5a4ed012cb4898cd7f43b4e7160ca21b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1256, "license_type": "no_license", "max_line_length": 85, "num_lines": 53, "path": "/src/BabbyDad/CommandSender.java", "repo_name": "lucbettaieb/Babby", "src_encoding": "UTF-8", "text": "package babbydad;\n\nimport java.io.*;\nimport java.net.*;\n\n/**\n * @author Luc A. Bettaieb\n * Class for sending chars over socket to the python server.\n */\n\npublic class CommandSender {\n String host;\n int portnum;\n PrintWriter out;\n \n Socket dataSocket;\n \n public CommandSender(String server, int port){\n host = server;\n portnum = port;\n \n System.out.println(\"Connecting...\");\n dataSocket = null;\n out = null;\n \n try {\n dataSocket = new Socket(host, portnum);\n out = new PrintWriter(dataSocket.getOutputStream(), true);\n \n } catch(UnknownHostException e){\n System.err.println(\"The host is messed up, check: \"+host);\n System.exit(1);\n } catch(IOException e){\n System.err.println(\"Couldn't get IO for \"+host);\n System.exit(1);\n }\n \n System.out.println(\"..connected!\");\n }\n \n public void send(String input){\n out.println(input);\n }\n \n public void close(){\n out.close();\n try{\n dataSocket.close();\n } catch(IOException e){\n System.err.println(\"Something went wrong with closing the data socket.\");\n }\n }\n}" }, { "alpha_fraction": 0.569523811340332, "alphanum_fraction": 0.5885714292526245, "avg_line_length": 17.13793182373047, "blob_id": "7972fd2e1a91abb19ebb876d5d15e13d5d994a04", "content_id": "d68e6128b7eaabeee6b03c7cfdc601c6dcb51297", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 525, "license_type": "no_license", "max_line_length": 53, "num_lines": 29, "path": "/server/server.py", "repo_name": "lucbettaieb/Babby", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#Server to run to accept various commands via socket.\n\nimport socket\n\nhost = ''\nport = 50000\nbacklog = 5\nsize = 256\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((host,port))\ns.listen(backlog)\n\nclient, address = s.accept()\n\nwhile 1:\n\n data = client.recv(size)\n\n if (data == \"w\\n\"):\n print(\"W received\")\n if (data == \"a\\n\"):\n print(\"A received\") \n\tif (data == \"s\\n\"):\n print(\"S received\")\n if (data == \"d\\n\"):\n print(\"D received\")\n\nclient.close()" }, { "alpha_fraction": 0.774193525314331, "alphanum_fraction": 0.774193525314331, "avg_line_length": 31, "blob_id": "3e004edec3b2618d19cb96bf1fdc89ceda7d2c35", "content_id": "1402d188ecedac912d8a556f69fb56fe97fa8e5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31, "license_type": "no_license", "max_line_length": 31, "num_lines": 1, "path": "/babby/resources/__init__.py", "repo_name": "lucbettaieb/Babby", "src_encoding": "UTF-8", "text": "import Servo, Motor, Angle, Map" }, { "alpha_fraction": 0.5709901452064514, "alphanum_fraction": 0.5837506055831909, "avg_line_length": 34.99418640136719, "blob_id": "689b0aef8f097c752317a4ba0acf676ed7dfbacf", "content_id": "286a4f91819a9d607005c805f902753d7a4d6fa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6191, "license_type": "no_license", "max_line_length": 124, "num_lines": 172, "path": "/babby/babby1.py", "repo_name": "lucbettaieb/Babby", "src_encoding": "UTF-8", "text": "#Main file for babby\n#Andrew M. Blasius\n\nfrom math import abs,cos,acos,radians\nfrom resources import Map,Servo,Motor,Angle\nfrom Map import search,initMap\nfrom Servo import servo\nfrom Motor import motor\nfrom Angle import switchAngle,convert\nimport RPi.GPIO as GPIO\n\nclass babby:\n def __init__(self,speed,maxspeed,legdistance,baseHeight,strutHeight\n s1,s2,s3,s4,m1,m2,m3,m4,\n minPulseTime,maxPulseTime,initAngle=90,\n serPort='/dev/ttyAMA0',baud=9600,tolerance=.01):\n ''' speed should be given in units [distance]/sec and legdistance should be consistent. \n s1 through s4 (as inputs) are the pin numbers of the pins controlling the servo motors. (INT)\n m1 through m4 (as inputs) are the pin numbers of the pins controlling the DC motors. (INT)\n speed is the initial speed of Babby (given in units of {distance}/sec). (FLOAT)\n maxspeed is the maximum speed of the motors. This is used to calculate the duty cycle of the PWM output. (FLOAT)\n legdistance is the distance between Babby's Legs. (FLOAT)\n baseHeight is the height returned by the ARDUINO when measuring ground with a slope m=0. (FLOAT)\n strutHeight is the height (not length) of the static strut. (FLOAT)\n minPulseTime is the minimum angular position (in degrees) to which the servos can sweep (INT)\n maxPulseTime is the maximum angular position (in degrees) to which the servos can sweep (INT)\n initAngle is the initial position of the servo motors. (INT)\n serPort is a string representing the address of the Rasperry Pi's serial port (STR)\n baud is the baudrate for the Raspberry Pi's serial port (INT)\n tolerance is the error allowed in computing the movement of babby's legs (FLOAT)\n '''\n \n #Servo Setup \n self.s1 = servo(s1,initAngle,minPulseTime,maxPulseTime)\n self.s2 = servo(s2,initAngle,minPulseTime,maxPulseTime)\n self.s3 = servo(s3,initAngle,minPulseTime,maxPulseTime)\n self.s4 = servo(s4,initAngle,minPulseTime,maxPulseTime)\n \n self.maxSpeed = maxspeed\n self.speed = speed\n self.dt = dt\n self.timeSeparation = float(legdistance)/self.speed #Calculate the initial time separation\n \n #DC Motor Setup\n self.cycle = (float(speed)/maxspeed) * 100\n self.m1 = motor(m1,cycle=self.cycle)\n self.m2 = motor(m2,cycle=self.cycle)\n self.m3 = motor(m3,cycle=self.cycle)\n self.m4 = motor(m4,cycle=self.cycle)\n \n #Serial Setup\n self.ser = serial.begin(serPort,baud) #Should add something to initialize handshaking\n \n #Map Setup\n self.map = initMap(timeSeparation,dt)\n self.heightSum = 0\n self.baseHeight= baseHeight\n self.frontHeight = 0\n self.backHeight = 0\n self.tol = tolerance\n \n #Leg x-coordinate setup\n self.frontX = 0\n self.backX = -legSeparation\n \n #Constant, intrinsic babby properties\n self.L = strutHeight\n \n #Handshake with ARDUINO \n self.handshake()\n \n\n def handshake(self):\n '''Checks to make sure that we're connected to the ARDUINO, and sends our timestep dt'''\n print 'Handshaking in progress...'\n self.ser.write('!')\n print 'Sent character:\\'!\\'\\nAwaiting response...'\n recByte = ser.readline()\n if recByte == '!':\n print 'Response received! Ready to proceed!\\nSending dt'\n self.ser.write(str(dt))\n print 'Waiting for response...'\n recByte = ser.readline()\n if recByte == '!':\n print 'Ready to go!'\n return\n \n \n def getHeights(self):\n self.dx = self.dt * self.speed\n self.frontX += self.dx\n self.backX += self.dx\n \n #Getting back height\n if self.backX <= 0:\n self.backHeight = 0 + self.L * cos(radians(self.angle)) #ANGLE NEEDS TO BE FIXED\n else:\n height = map.search(self.map,self.backX,self.tol)\n self.backHeight = height + self.L * cos(radians(self.angle)) #ANGLE NEEDS TO BE FIXED\n \n #Getting front height\n reading = self.ser.readline()\n self.heightSum += self.dx * reading\n self.map.appendright((self.frontX,self.heightSum)) \n self.frontHeight = self.heightSum\n \n \n def moveLegs(self):\n '''Needs Revision!'''\n difference = self.FrontHeight - self.BackHeight\n if abs(difference) < self.tol:\n pass\n try:\n s1.angle = acos(cos( radians(self.s3.angle) ) - difference/self.L) #ANGLE NEEDS TO BE FIXED\n s2.angle = self.switchAngle(self.s1.angle)\n except:\n try:\n s3.angle = acos(cos( radians(s1.angle) ) + difference/self.L) #ANGLE NEEDS TO BE FIXED\n s4.angle = self.convertAngle(self.s3.angle)\n except:\n print 'Can\\'t move legs!'\n raise \n \n \n def run(self):\n while True:\n self.getHeights()\n self.moveLegs()\n \n \n def end(self):\n '''Closes up open ports.'''\n #Close servos\n self.s1.end()\n self.s2.end()\n self.s3.end()\n self.s4.end()\n \n #Close DC motors\n self.m1.end()\n self.m2.end()\n self.m3.end()\n self.m4.end()\n \n #Close serial and cleanup\n self.ser.close()\n GPIO.cleanup()\n \n \nif __name__ == '__main__':\n GPIO.setmode(GPIO.BOARD)\n initSpeed = #\n maxSpeed = #Set by motor specs\n legDistance = #\n baseHeight = #\n strutHeight = #\n s1 = #\n s2 = #\n s3 = #\n s4 = #\n m1 = #\n m2 = #\n m3 = #\n m4 = #\n minPulseTime = #Set by servo specs\n maxPulseTime = #Set by servo specs\n tolerance = #\n Babby = babby(initSpeed,maxSpeed,legDistance,baseHeight,strutHeight\n s1,s2,s3,s4,m1,m2,m3,m4,\n minPulseTime,maxPulseTime,tolerance)\n Babby.run()\n Babby.end()\n" }, { "alpha_fraction": 0.4878612756729126, "alphanum_fraction": 0.5017340779304504, "avg_line_length": 24.636363983154297, "blob_id": "6adf27b5e8fff90fdbaf42e2f656a728a936dfc6", "content_id": "373cd0edf7f5a02478b8b229343197eeff757aee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 865, "license_type": "no_license", "max_line_length": 75, "num_lines": 33, "path": "/babby/resources/Motor.py", "repo_name": "lucbettaieb/Babby", "src_encoding": "UTF-8", "text": "#Module for controlling simple motors with PWM\n#Andrew M. Blasius\n\n'''Assumes we have a PWM pin hooked up to a PNP/NPN transistor as follows:\n Collector Emitter\n 0 ------- PNP/NPN ---------0\n |\n |\n |\n Pinout >0\n Base\n'''\n\nimport RPi.GPIO as GPIO\nimport time\n\nclass motor:\n def __init__(self,pin,cycle=0,freq=50): #Initially off with freq = 50Hz\n GPIO.setup(pin,GPIO.OUT)\n self.pin = GPIO.PWM(pin,freq)\n self.pin.start(cycle)\n \n def setSpeed(self,speed):\n #Speed should range from 0% to 100%\n try:\n self.pin.ChangeDutyCycle(speed)\n except:\n print 'Speed outside acceptable range'\n return\n \n def end(self)\n self.pin.stop()\n print 'PWM ended'\n \n \n " }, { "alpha_fraction": 0.603715181350708, "alphanum_fraction": 0.6068111658096313, "avg_line_length": 19.0625, "blob_id": "1fa819a8a8e586e9efe09658cff199da7ce4bfaf", "content_id": "b32ab7d34d0a7253c50ff4766c2ab7cb62d36731", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 55, "num_lines": 16, "path": "/babby/resources/Map.py", "repo_name": "lucbettaieb/Babby", "src_encoding": "UTF-8", "text": "#Map module\n#Andrew M. Blasius\n\nfrom llist import sllist\nfrom math import abs\n\ndef search(map,position,tol):\n '''Searches for an x-position in the linked list'''\n while True:\n entry = map.popleft()\n if abs(entry[0] - position) < tol:\n return entry \n\ndef initMap():\n map = sllist()\n return map\n\n\n" }, { "alpha_fraction": 0.6575682163238525, "alphanum_fraction": 0.6873449087142944, "avg_line_length": 30, "blob_id": "34ad7ee24d948b673aa4e61493132dba7ca77b77", "content_id": "04bb77380f531b726086d9b0a5361d1543a6c698", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "no_license", "max_line_length": 74, "num_lines": 13, "path": "/babby/resources/Angle.py", "repo_name": "lucbettaieb/Babby", "src_encoding": "UTF-8", "text": "#Angular conversion for babby\n\ndef switchAngle(angle):\n '''Switches angle from servo to servo\n ie. an angle of 100 degrees at one servo (s1)\n will correspond to an angle of 80 degrees at the opposite servo (s2)\n '''\n return 180 - angle\n \ndef convert(angle):\n '''Converts the angle fed into the servo into an angle that works with\n the cosine calculation'''\n return angle - 90 " }, { "alpha_fraction": 0.41951218247413635, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 23.220338821411133, "blob_id": "263770a7e1bafe26b57f1b18c1fdd84c52dc7850", "content_id": "07caabc728ddf959ddec6074a411f82dd14d4bee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1435, "license_type": "no_license", "max_line_length": 80, "num_lines": 59, "path": "/src/BabbyDad/BabbyDad.java", "repo_name": "lucbettaieb/Babby", "src_encoding": "UTF-8", "text": "package babbydad;\n\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\nimport java.io.*;\n\nimport javax.swing.JFrame;\n\n/**\n * @author Luc A. Bettaieb\n * \n * BabbyDad gets input from the keyboard and sends it over socket to the server.\n * \n */\n\npublic class BabbyDad {\n\n public static void main(String[] args) throws IOException {\n JFrame frame = new JFrame(\"Key Listener\");\n \n \n KeyListener listener;\n listener = new KeyListener() {\n CommandSender cs = new CommandSender(\"10.0.1.147\",50000);\n \n public void keyTyped(KeyEvent e) {\n if(e.getKeyChar() == 'w'){\n cs.send(\"w\");\n }\n \n if(e.getKeyChar() == 'a'){\n cs.send(\"a\");\n }\n \n if(e.getKeyChar() == 's'){\n cs.send(\"s\");\n }\n \n if(e.getKeyChar() == 'd'){\n cs.send(\"d\");\n } \n \n if(e.getKeyChar() == 'q'){\n cs.close();\n System.exit(0);\n }\n }\n\n public void keyPressed(KeyEvent e) {}\n public void keyReleased(KeyEvent e) {}\n };\n \n frame.addKeyListener(listener);\n \n frame.pack();\n frame.setVisible(true);\n\n }\n}\n\n \n" } ]
10
lfr4704/Intro-Python-II
https://github.com/lfr4704/Intro-Python-II
4880139282252f07677fc5d62e7029b508fa5ee8
a08bcb23d361e202f3c1ad27241cd104c99fd919
138c7226ccc92aa611d01d185c90a083845eabb6
refs/heads/master
2022-12-30T07:10:28.672500
2020-09-11T01:48:33
2020-09-11T01:48:33
293,986,335
0
0
null
2020-09-09T02:55:12
2020-07-14T03:32:18
2020-09-09T02:52:11
null
[ { "alpha_fraction": 0.6008403301239014, "alphanum_fraction": 0.6092436909675598, "avg_line_length": 13.875, "blob_id": "96c13b4ee4953c39134076cb85206ffd37fa1925", "content_id": "d5781c11bb3cd88bf19f48f6f1d2bf6e9a817798", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 238, "license_type": "no_license", "max_line_length": 42, "num_lines": 16, "path": "/src/Items.py", "repo_name": "lfr4704/Intro-Python-II", "src_encoding": "UTF-8", "text": "\"\"\"\nItems for RPG\n\"\"\"\n\nfrom Fortuna import dice\n\nclass Item:\n\n def __init__(self, name, description):\n self.name = name\n self.description = description\n\nclass Weapon(Item):\n\n def damage(self):\n return dice(1,6)\n" } ]
1
gaurav14111/Python-API
https://github.com/gaurav14111/Python-API
cb7bcc123f02fd8bd00d8e7cdeddc8706086304b
3de50d2afd41fef390b747bf38d3d7b5bc1b9964
3c4a3f6823ae195a22656eabad095ad9bf813fbf
refs/heads/master
2020-05-03T19:18:05.471458
2019-09-17T17:37:57
2019-09-17T17:37:57
178,781,855
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6142857074737549, "alphanum_fraction": 0.8285714387893677, "avg_line_length": 34, "blob_id": "ae6888fd8332cf93dc6987d622452384e68aa7c0", "content_id": "ac1b87f38634d2859bc8f007fc232d56c600735f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 70, "license_type": "no_license", "max_line_length": 44, "num_lines": 2, "path": "/starter_code/api_keys.py", "repo_name": "gaurav14111/Python-API", "src_encoding": "UTF-8", "text": "# OpenWeatherMap API Key\napi_key = \"e16c51aee2dc6af579aad79da42fc40c\"\n" } ]
1
jonelr/workrequest
https://github.com/jonelr/workrequest
26cc7aeb8b7eae30a6abc7235932377ea16281f8
4212e6914fcdda38fe8ef9d5f6c4e5760fc1aee9
8887cc0983e1d9290894c8a35a7f6a3ee05d1833
refs/heads/master
2021-05-13T18:35:27.855355
2018-01-15T23:40:16
2018-01-15T23:40:16
116,869,171
0
0
null
2018-01-09T20:48:19
2018-01-09T20:52:06
2018-01-15T23:40:17
Python
[ { "alpha_fraction": 0.4832826852798462, "alphanum_fraction": 0.5775076150894165, "avg_line_length": 18.352941513061523, "blob_id": "8f4b8587b8625185f1546db301d97f8a67f751c8", "content_id": "4c916413486c30dd645a7eda6fbb8f8f5762e340", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 329, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/myapp/migrations/0012_auto_20180110_1322.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-10 19:22\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0011_auto_20180110_1320'),\n ]\n\n operations = [\n migrations.RenameModel(\n old_name='SqlLogs',\n new_name='SqlLog',\n ),\n ]\n" }, { "alpha_fraction": 0.5344827771186829, "alphanum_fraction": 0.5437420010566711, "avg_line_length": 35.8470573425293, "blob_id": "cc4a1ffb8bfc451aaacf26a4b0dfb4adc9a10067", "content_id": "47ffcc15e7e11fe3a71e2a3ac945191a6bf6e66c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3132, "license_type": "no_license", "max_line_length": 120, "num_lines": 85, "path": "/myapp/migrations/0002_auto_20180109_1544.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-09 21:44\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Area',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=50)),\n ],\n ),\n migrations.CreateModel(\n name='BusinessUnit',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=50)),\n ],\n ),\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=50)),\n ],\n options={\n 'verbose_name_plural': 'Categories',\n },\n ),\n migrations.CreateModel(\n name='Plant',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=50)),\n ],\n ),\n migrations.CreateModel(\n name='Status',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=50)),\n ],\n options={\n 'verbose_name_plural': 'Statuses',\n },\n ),\n migrations.AddField(\n model_name='workrequest',\n name='area',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='myapp.Area'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='workrequest',\n name='business_unit',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='myapp.BusinessUnit'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='workrequest',\n name='category',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='myapp.Category'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='workrequest',\n name='plant',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='myapp.Plant'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='workrequest',\n name='status',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='myapp.Status'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.6478545069694519, "alphanum_fraction": 0.6478545069694519, "avg_line_length": 31.484848022460938, "blob_id": "6d5aa63647e46fceedb0a634e296f1abce4b548e", "content_id": "4ff30fc3aed2cccb6203e4c5a5ccf71875b30e7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2144, "license_type": "no_license", "max_line_length": 82, "num_lines": 66, "path": "/myapp/admin.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import WorkRequest, Area, Plant, Category, \\\n Status, BusinessUnit, Hours, TimeSheet, \\\n SqlVersion, OsVersion, SqlServer, SqlLog\n\n# Register your models here.\nadmin.site.register({Area, Plant, Category, Status, BusinessUnit,\n SqlVersion, OsVersion, })\n\n\[email protected](TimeSheet)\nclass TimeSheetAdmin(admin.ModelAdmin):\n list_display = ('account', 'week_ending', 'hours')\n list_filter = ('account',)\n date_hierarchy = 'week_ending'\n\n\[email protected](WorkRequest)\nclass WorkRequestAdmin(admin.ModelAdmin):\n list_display = ('id', 'title', 'date', 'status', 'area', 'business_unit')\n list_filter = ('status', 'business_unit', 'area')\n search_fields = ('title',)\n fields = ('title', ('business_unit', 'category'), ('status', 'plant', 'area'))\n\n\[email protected](Hours)\nclass HoursAdmin(admin.ModelAdmin):\n date_hierarchy = 'week_ending'\n list_display = ('workrequest', 'week_ending', 'hours')\n list_filter = ('account',)\n fields = (('workrequest'), ('week_ending', 'hours'), 'notes')\n\n def save_model(self, request, obj, form, change):\n if not obj.account:\n obj.account = request.user\n super(HoursAdmin, self).save_model(request, obj, form, change)\n\n def get_queryset(self, request):\n qs = super(HoursAdmin, self).get_queryset(request)\n if request.user.is_superuser:\n return qs\n return qs.filter(account=request.user)\n\n\nclass SqlLogInline(admin.TabularInline):\n model = SqlLog\n\n\[email protected](SqlLog)\nclass SqlLogAdmin(admin.ModelAdmin):\n list_display = ('title', 'date', 'account')\n list_filter = ('servers', 'account',)\n exclude = ('account', )\n filter_horizontal = ('servers',)\n\n def save_model(self, request, obj, form, change):\n if not obj.account:\n obj.account = request.user\n super(SqlLogAdmin, self).save_model(request, obj, form, change)\n\n\[email protected](SqlServer)\nclass SqlServerAdmin(admin.ModelAdmin):\n list_display = ('name', 'os', 'version', 'cpu', 'ram', 'mes', 'sap')\n list_filter = ('version', 'sap', 'mes')\n" }, { "alpha_fraction": 0.5275590419769287, "alphanum_fraction": 0.5826771855354309, "avg_line_length": 20.16666603088379, "blob_id": "b5312095d14043c8f255d0adbdea7b988e9228c3", "content_id": "da201da9e12b43bd22fb6220e94a2575e327d0e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 381, "license_type": "no_license", "max_line_length": 50, "num_lines": 18, "path": "/myapp/migrations/0020_auto_20180112_1220.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-12 18:20\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0019_sqllog_account'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='sqllog',\n name='account',\n field=models.CharField(max_length=50),\n ),\n ]\n" }, { "alpha_fraction": 0.646558403968811, "alphanum_fraction": 0.646558403968811, "avg_line_length": 30.536584854125977, "blob_id": "633a3e907f01f8db5f9ddca81fcf615890e22e70", "content_id": "53b096c1de51bf142455182f99d7002e04dcecaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1293, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/mynotes/admin.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import Training, TimeOff\n\n\n# Register your models here.\[email protected](Training)\nclass TrainingAdmin(admin.ModelAdmin):\n list_display = ('title', 'date_taken', 'account')\n list_filter = ('account',)\n search_fields = ('title',)\n exclude = ('account',)\n\n def save_model(self, request, obj, form, change):\n if not obj.account:\n obj.account = request.user\n super(TrainingAdmin, self).save_model(request, obj, form, change)\n\n def get_queryset(self, request):\n qs = super(TrainingAdmin, self).get_queryset(request)\n if request.user.is_superuser:\n return qs\n return qs.filter(account=request.user)\n\n\[email protected](TimeOff)\nclass TimeOffAdmin(admin.ModelAdmin):\n list_filter = ('account',)\n list_display = ('account', 'date_taken', 'hours')\n exclude = ('account', )\n\n def save_model(self, request, obj, form, change):\n if not obj.account:\n obj.account = request.user\n super(TimeOffAdmin, self).save_model(request, obj, form, change)\n\n def get_queryset(self, request):\n qs = super(TimeOffAdmin, self).get_queryset(request)\n if request.user.is_superuser:\n return qs\n return qs.filter(account=request.user)\n" }, { "alpha_fraction": 0.6867284178733826, "alphanum_fraction": 0.6975308656692505, "avg_line_length": 27.173913955688477, "blob_id": "235292a33f8f39f2515fe0fac9998d312a974b53", "content_id": "8ee320ba7cd416c11016698f2c80f9d98b64c613", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 648, "license_type": "no_license", "max_line_length": 68, "num_lines": 23, "path": "/mynotes/models.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "from datetime import datetime\n\nfrom django.db import models\n\n\n# Create your models here.\nclass Training(models.Model):\n title = models.CharField(max_length=50)\n description = models.TextField(blank=True, null=True)\n date_taken = models.DateField(default=datetime.now)\n account = models.CharField(max_length=50, null=True, blank=True)\n\n def __str__(self):\n return self.title\n\n\nclass TimeOff(models.Model):\n date_taken = models.DateField(default=datetime.now)\n hours = models.IntegerField(default=8)\n account = models.CharField(max_length=50)\n\n def __str__(self):\n return '%s:%s' % (self.account, self.hours)\n" }, { "alpha_fraction": 0.6769504547119141, "alphanum_fraction": 0.6846632957458496, "avg_line_length": 26.185483932495117, "blob_id": "c39c2b66c7d69a7c9c06fd89c910178457b7a3b6", "content_id": "66e4aa1fc5ba228da4cc7e9e745a56f837974d23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3371, "license_type": "no_license", "max_line_length": 93, "num_lines": 124, "path": "/myapp/models.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "from datetime import datetime\n\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\n\n# Create your models here.\n\nclass Area(models.Model):\n title = models.CharField(max_length=50)\n\n def __str__(self):\n return self.title\n\n\nclass Plant(models.Model):\n title = models.CharField(max_length=50)\n\n def __str__(self):\n return self.title\n\n\nclass Status(models.Model):\n class Meta:\n verbose_name_plural = \"Statuses\"\n\n title = models.CharField(max_length=50)\n\n def __str__(self):\n return self.title\n\n\nclass BusinessUnit(models.Model):\n title = models.CharField(max_length=50)\n\n def __str__(self):\n return self.title\n\n\nclass Category(models.Model):\n class Meta:\n verbose_name_plural = \"Categories\"\n\n title = models.CharField(max_length=50)\n\n def __str__(self):\n return self.title\n\n\nclass WorkRequest(models.Model):\n title = models.CharField(max_length=50)\n date = models.DateTimeField(auto_now=True)\n business_unit = models.ForeignKey(BusinessUnit, on_delete=models.CASCADE)\n category = models.ForeignKey(Category, on_delete=models.CASCADE)\n status = models.ForeignKey(Status, on_delete=models.CASCADE)\n plant = models.ForeignKey(Plant, on_delete=models.CASCADE)\n area = models.ForeignKey(Area, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.title\n\n\nclass Hours(models.Model):\n class Meta:\n verbose_name_plural = \"Hours\"\n\n # user = models.OneToOneField(User, on_delete=models.CASCADE)\n account = models.CharField(max_length=50, blank=True, null=True)\n workrequest = models.ForeignKey(WorkRequest, on_delete=models.CASCADE)\n week_ending = models.DateField(default=datetime.now)\n hours = models.IntegerField(default=8)\n notes = models.TextField(blank=True, null=True)\n\n def __str__(self):\n return 'Record %s' % self.id\n\n\nclass TimeSheet(models.Model):\n account = models.ForeignKey(User, on_delete=models.CASCADE)\n week_ending = models.DateField(default=datetime.now)\n hours = models.IntegerField()\n\n def __str__(self):\n return '%s - %s:%d' % (self.week_ending, self.account, self.hours)\n\n\nclass SqlVersion(models.Model):\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.name\n\n\nclass OsVersion(models.Model):\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.name\n\n\nclass SqlServer(models.Model):\n name = models.CharField(max_length=50)\n cpu = models.IntegerField(default=4)\n ram = models.IntegerField()\n date_added = models.DateField(auto_now=True)\n version = models.ForeignKey(SqlVersion, on_delete=models.CASCADE, related_name='servers')\n os = models.ForeignKey(OsVersion, on_delete=models.CASCADE, related_name='servers')\n sap = models.BooleanField(default=False)\n mes = models.BooleanField(default=False)\n\n def __str__(self):\n return self.name\n\n\nclass SqlLog(models.Model):\n title = models.CharField(max_length=50)\n date = models.DateField(default=datetime.now)\n description = models.TextField(blank=True, null=True)\n # servers = models.ForeignKey(SqlServer, on_delete=models.CASCADE, related_name='logs')\n servers = models.ManyToManyField(SqlServer)\n account = models.CharField(max_length=50, )\n\n def __str__(self):\n return self.title\n" }, { "alpha_fraction": 0.5025773048400879, "alphanum_fraction": 0.5824742317199707, "avg_line_length": 20.55555534362793, "blob_id": "fb4007e64c12e6dde549470d81033faf3b1ef61a", "content_id": "e30ea80fde301a6893c3d534a72efaff575d6c7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 388, "license_type": "no_license", "max_line_length": 58, "num_lines": 18, "path": "/myapp/migrations/0013_hours_notes.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-10 19:59\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0012_auto_20180110_1322'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='hours',\n name='notes',\n field=models.TextField(blank=True, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5782414078712463, "avg_line_length": 28.173913955688477, "blob_id": "a39a8e3fc57d949e14b7bead77f63797ca6f3338", "content_id": "c2be95c1a8d305b163c5d2fa1b6634dc1af3c91e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 671, "license_type": "no_license", "max_line_length": 114, "num_lines": 23, "path": "/mynotes/migrations/0003_timeoff.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-12 17:23\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('mynotes', '0002_training_account'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='TimeOff',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('date_taken', models.DateField(default=datetime.datetime.now)),\n ('hours', models.IntegerField(default=8)),\n ('account', models.CharField(max_length=50)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5365426540374756, "alphanum_fraction": 0.5540481209754944, "avg_line_length": 37.72881317138672, "blob_id": "1fc099ebd03f270a8667d397fb29b70deaf0b93c", "content_id": "c8510d2b33d814fd980cecba1f8c5cce0cebc5c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2285, "license_type": "no_license", "max_line_length": 133, "num_lines": 59, "path": "/myapp/migrations/0011_auto_20180110_1320.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-10 19:20\n\nimport datetime\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0010_auto_20180110_1144'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='OsVersion',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50)),\n ],\n ),\n migrations.CreateModel(\n name='SqlLogs',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=50)),\n ('date', models.DateField(default=datetime.datetime.now)),\n ('description', models.TextField(blank=True, null=True)),\n ],\n ),\n migrations.CreateModel(\n name='SqlServer',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50)),\n ('cpu', models.IntegerField(default=4)),\n ('ram', models.IntegerField()),\n ('date_added', models.DateField(auto_now=True)),\n ('os', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='servers', to='myapp.OsVersion')),\n ],\n ),\n migrations.CreateModel(\n name='SqlVersion',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50)),\n ],\n ),\n migrations.AddField(\n model_name='sqlserver',\n name='version',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='servers', to='myapp.SqlVersion'),\n ),\n migrations.AddField(\n model_name='sqllogs',\n name='servers',\n field=models.ManyToManyField(related_name='logs', to='myapp.SqlServer'),\n ),\n ]\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.6101694703102112, "avg_line_length": 31.18181800842285, "blob_id": "479f694720c2e48a41e779cb5f05b2c60f16e2ef", "content_id": "67b9e42eed7542e583e441b45363c951c17ea2c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 116, "num_lines": 22, "path": "/myapp/migrations/0016_logserver.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-12 16:16\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0015_sqlserver_mes'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='LogServer',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('log', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp.SqlLog')),\n ('sqlserver', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp.SqlServer')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.47834646701812744, "alphanum_fraction": 0.539370059967041, "avg_line_length": 20.16666603088379, "blob_id": "5d99c26ac81100efd431266cdce1610879c0ad6c", "content_id": "ef81e3403b589b3d231e245bf3f4e8000eb23153", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 508, "license_type": "no_license", "max_line_length": 47, "num_lines": 24, "path": "/myapp/migrations/0018_auto_20180112_1123.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-12 17:23\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0017_auto_20180112_1020'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='logserver',\n name='log',\n ),\n migrations.RemoveField(\n model_name='logserver',\n name='sqlserver',\n ),\n migrations.DeleteModel(\n name='LogServer',\n ),\n ]\n" }, { "alpha_fraction": 0.5317460298538208, "alphanum_fraction": 0.5820105671882629, "avg_line_length": 20, "blob_id": "14011c8ce8f371ceb0104998133bc3d03fa4c595", "content_id": "3b93ba0f55bacfc161f4e1ed3b9d7aec7f3de928", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 378, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/myapp/migrations/0014_sqlserver_sap.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-11 14:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0013_hours_notes'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='sqlserver',\n name='sap',\n field=models.BooleanField(default=False),\n ),\n ]\n" }, { "alpha_fraction": 0.4767801761627197, "alphanum_fraction": 0.5727553963661194, "avg_line_length": 18, "blob_id": "be18b8a9d5c9034f9b120fe0bef20b5d04da3b7b", "content_id": "0b56c31e3962fad3a86e7214348ac545b97f76fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/myapp/migrations/0008_remove_hours_user.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-10 00:33\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0007_auto_20180109_1831'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='hours',\n name='user',\n ),\n ]\n" }, { "alpha_fraction": 0.513131320476532, "alphanum_fraction": 0.5535353422164917, "avg_line_length": 21.5, "blob_id": "e1ddd4ec7b2df3210f148d6432ba7a1e1c7ad2a2", "content_id": "a281541ba729aefbfd491a1637b4be2761a7767e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 495, "license_type": "no_license", "max_line_length": 53, "num_lines": 22, "path": "/myapp/migrations/0005_auto_20180109_1629.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-09 22:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0004_hours'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='hours',\n options={'verbose_name_plural': 'Hours'},\n ),\n migrations.AddField(\n model_name='hours',\n name='hours',\n field=models.IntegerField(default=8),\n ),\n ]\n" }, { "alpha_fraction": 0.7047970294952393, "alphanum_fraction": 0.7490774989128113, "avg_line_length": 19.923076629638672, "blob_id": "061cca85213d274686223b817eabe991ca489038", "content_id": "fc7e00a1e8cdb525af3957f537152febd337948b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 271, "license_type": "no_license", "max_line_length": 51, "num_lines": 13, "path": "/notes.md", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "### Todo\n\n1. Add server and changes to server functionality\n\n### Changes\n\n1. Add initial workrequest creation\n1. Add hours creation based on workrequest\n1. Filter hours listing by currently logged in user\n\n### Gunicorn\n\n$ gunicorn --bind 0.0.0.0:8000 --reload mysite.wsgi" }, { "alpha_fraction": 0.5363408327102661, "alphanum_fraction": 0.5889724493026733, "avg_line_length": 21.16666603088379, "blob_id": "e591c0ef3f89859884d22231c2d92b2a55e9841d", "content_id": "6e0d1144f0b315671a963c445dfdfc4fbdfcf9e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 399, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/mynotes/migrations/0002_training_account.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-11 20:38\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('mynotes', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='training',\n name='account',\n field=models.CharField(blank=True, max_length=50, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5089974403381348, "alphanum_fraction": 0.5886889696121216, "avg_line_length": 20.61111068725586, "blob_id": "28b3e62f5e5fc7d910be08e10450a80530805f85", "content_id": "ff8d5a9d91d3e07f40587e2b1de62a3d53d5c97f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 389, "license_type": "no_license", "max_line_length": 54, "num_lines": 18, "path": "/myapp/migrations/0003_workrequest_date.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-09 21:45\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0002_auto_20180109_1544'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='workrequest',\n name='date',\n field=models.DateTimeField(auto_now=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5619999766349792, "avg_line_length": 21.727272033691406, "blob_id": "52911298b59ec79d548db6a7eaa91806e62106d8", "content_id": "c23791f624cec928938e5010536084359285f724", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 500, "license_type": "no_license", "max_line_length": 63, "num_lines": 22, "path": "/myapp/migrations/0021_auto_20180113_1438.py", "repo_name": "jonelr/workrequest", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-13 20:38\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myapp', '0020_auto_20180112_1220'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='sqllog',\n name='servers',\n ),\n migrations.AddField(\n model_name='sqllog',\n name='servers',\n field=models.ManyToManyField(to='myapp.SqlServer'),\n ),\n ]\n" } ]
19
drewbwarren/ROSpong
https://github.com/drewbwarren/ROSpong
70c9d6e2a7d83a8ec203e3a3be4942cf47d958c0
67ea2b46a0ed421942fa3dc51b400d2d498b4c1b
795835f58b0c796c50f8a780e3dd22bc99f891a2
refs/heads/master
2021-01-23T21:27:30.901429
2017-04-20T04:42:58
2017-04-20T04:42:58
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5794497728347778, "alphanum_fraction": 0.6413999795913696, "avg_line_length": 31.192771911621094, "blob_id": "ca0f3d6a58b0c8f8f1a832ecb9432e3c5e476a12", "content_id": "a9efa2e32fdcda232188903e2fb8555065296e0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5343, "license_type": "permissive", "max_line_length": 82, "num_lines": 166, "path": "/src/game/src/my_pong.py", "repo_name": "drewbwarren/ROSpong", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n#\t\tIt's my first actual game-making attempt. I know code could be much better \n#\t\twith classes or defs but I tried to make it short and understandable with very \n#\t\tlittle knowledge of python and pygame(I'm one of them). Enjoy.\n\nimport pygame\nfrom pygame.locals import *\nfrom sys import exit\nimport random\nimport rospy\nfrom sensor_msgs.msg import Joy\n\nclass game():\n\n\tdef __init__(self):\n\t\t\n\t\t# ROS Subscribers\n\t\tjoy1 = rospy.Subscriber(\"/joy\", Joy, self.joy1_callback)\n\t\tself.axes = 0.\n\n\t\tpygame.init()\n\n\t\tself.screen=pygame.display.set_mode((640,480),0,32)\n\t\tpygame.display.set_caption(\"Pong Pong!\")\n\n\t\t#Creating 2 bars, a ball and background.\n\t\tself.back = pygame.Surface((640,480))\n\t\tself.background = self.back.convert()\n\t\tself.background.fill((0,0,0))\n\t\tself.bar = pygame.Surface((10,50))\n\t\tself.bar1 = self.bar.convert()\n\t\tself.bar1.fill((0,0,255))\n\t\tself.bar2 = self.bar.convert()\n\t\tself.bar2.fill((255,0,0))\n\t\tself.circ_sur = pygame.Surface((15,15))\n\t\tself.circ = pygame.draw.circle(self.circ_sur,(0,255,0),(15/2,15/2),15/2)\n\t\tself.circle = self.circ_sur.convert()\n\t\tself.circle.set_colorkey((0,0,0))\n\n\t\t# some definitions\n\t\tself.bar1_x, self.bar2_x = 10. , 620.\n\t\tself.bar1_y, self.bar2_y = 215. , 215.\n\t\tself.circle_x, self.circle_y = 307.5, 232.5\n\t\tself.bar1_move, self.bar2_move = 0. , 0.\n\t\tself.speed_x, self.speed_y, self.speed_circ = 250., 250., 250.\n\t\tself.bar1_score, self.bar2_score = 0,0\n\t\t#clock and font objects\n\t\tself.clock = pygame.time.Clock()\n\t\tself.font = pygame.font.SysFont(\"calibri\",40)\n\t\tself.ai_speed = 0.\n\n\tdef joy1_callback(self,msg):\n\t\t# Macbook motion joy\n\t\tself.axes = float(msg.axes[1])\n\t\tprint self.axes\n\t\t# print self.axes\n\n\tdef animate(self):\n\t\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == QUIT:\n\t\t\t\texit()\n\t\t\t# if event.type == KEYDOWN:\n\t\t\t# \tif event.key == K_UP:\n\t\t\t# \t\tself.bar1_move = -self.self.ai_speed\n\t\t\t# \telif event.key == K_DOWN:\n\t\t\t# \t\tself.bar1_move = self.ai_speed\n\t\t\t# elif event.type == KEYUP:\n\t\t\t# \tif event.key == K_UP:\n\t\t\t# \t\tself.bar1_move = 0.\n\t\t\t# \telif event.key == K_DOWN:\n\t\t\t# \t\tself.bar1_move = 0.\n\t\t# print self.ai_speed\n\t\t# print type(self.ai_speed)\n\t\tself.bar1_move = -2*self.ai_speed*self.axes\n\t\t\n\t\tscore1 = self.font.render(str(self.bar1_score), True,(255,255,255))\n\t\tscore2 = self.font.render(str(self.bar2_score), True,(255,255,255))\n\n\t\tself.screen.blit(self.background,(0,0))\n\t\tframe = pygame.draw.rect(self.screen,(255,255,255),Rect((5,5),(630,470)),2)\n\t\tmiddle_line = pygame.draw.aaline(self.screen,(255,255,255),(330,5),(330,475))\n\t\tself.screen.blit(self.bar1,(self.bar1_x,self.bar1_y))\n\t\tself.screen.blit(self.bar2,(self.bar2_x,self.bar2_y))\n\t\tself.screen.blit(self.circle,(self.circle_x,self.circle_y))\n\t\tself.screen.blit(score1,(250.,210.))\n\t\tself.screen.blit(score2,(380.,210.))\n\n\t\tself.bar1_y += self.bar1_move\n\t\t\n\t# movement of circle\n\t\ttime_passed = self.clock.tick(30)\n\t\ttime_sec = time_passed / 1000.0\n\t\t\n\t\tself.circle_x += self.speed_x * time_sec\n\t\tself.circle_y += self.speed_y * time_sec\n\t\tself.ai_speed = self.speed_circ * time_sec\n\t#AI of the computer.\n\t\tif self.circle_x >= 305.:\n\t\t\tif not self.bar2_y == self.circle_y + 7.5:\n\t\t\t\tif self.bar2_y < self.circle_y + 7.5:\n\t\t\t\t\tself.bar2_y += self.ai_speed\n\t\t\t\tif self.bar2_y > self.circle_y - 42.5:\n\t\t\t\t\tself.bar2_y -= self.ai_speed\n\t\t\telse:\n\t\t\t\tself.bar2_y == self.circle_y + 7.5\n\t\t\n\t\tif self.bar1_y >= 420.: self.bar1_y = 420.\n\t\telif self.bar1_y <= 10. : self.bar1_y = 10.\n\t\tif self.bar2_y >= 420.: self.bar2_y = 420.\n\t\telif self.bar2_y <= 10.: self.bar2_y = 10.\n\t#since i don't know anything about collision, ball hitting bars goes like this.\n\t\tif self.circle_x <= self.bar1_x + 10.:\n\t\t\tif self.circle_y >= self.bar1_y - 7.5 and self.circle_y <= self.bar1_y + 42.5:\n\t\t\t\tself.circle_x = 20.\n\t\t\t\tself.speed_x = -self.speed_x\n\t\tif self.circle_x >= self.bar2_x - 15.:\n\t\t\tif self.circle_y >= self.bar2_y - 7.5 and self.circle_y <= self.bar2_y + 42.5:\n\t\t\t\tself.circle_x = 605.\n\t\t\t\tself.speed_x = -self.speed_x\n\t\tif self.circle_x < 5.:\n\t\t\tself.bar2_score += 1\n\t\t\tself.circle_x, self.circle_y = 320., 232.5\n\t\t\tself.bar1_y,self.bar_2_y = 215., 215.\n\t\telif self.circle_x > 620.:\n\t\t\tself.bar1_score += 1\n\t\t\tself.circle_x, self.circle_y = 307.5, 232.5\n\t\t\tself.bar1_y, self.bar2_y = 215., 215.\n\t\tif self.circle_y <= 10.:\n\t\t\tself.speed_y = -self.speed_y\n\t\t\tself.circle_y = 10.\n\t\telif self.circle_y >= 457.5:\n\t\t\tself.speed_y = -self.speed_y\n\t\t\tself.circle_y = 457.5\n\n\t\tpygame.display.update()\n\n##############################\n#### Main Function to Run ####\n##############################\nif __name__ == '__main__':\n\t# Initialize Node\n\trospy.init_node('PongGame')\n\n\t# set rate\n\thz = 100.0\n\trate = rospy.Rate(hz)\n\n\t# init path_manager_base object\n\tpong = game()\n\n\t# Loop\n\twhile not rospy.is_shutdown():\n\t\tpong.animate()\n\t\trate.sleep()" } ]
1
blukaz/shop-robo
https://github.com/blukaz/shop-robo
10a63293f0e0e96acb9a1c86551eaaf90650955b
f723d3fe3e50042185636ba5dc4069818c529d28
26375bd966d71a2a74199afc6e8382e2eda601f0
refs/heads/master
2021-03-27T10:10:25.531560
2017-06-21T09:36:22
2017-06-21T09:36:22
87,103,020
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7428571581840515, "alphanum_fraction": 0.75, "avg_line_length": 16.45833396911621, "blob_id": "6ec68d7d9233a4bbe0e81092251f6e641b7d19b5", "content_id": "44d85d19f1570634f1648af3ef0af44e641d8f1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 420, "license_type": "no_license", "max_line_length": 54, "num_lines": 24, "path": "/qr_tracker/CMakeLists.txt", "repo_name": "blukaz/shop-robo", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(qr_tracker)\n\nfind_package(catkin REQUIRED COMPONENTS\n rospy\n geometry_msgs\n std_msgs\n)\n\nfind_package(OpenCV REQUIRED)\n\ncatkin_package(\n# INCLUDE_DIRS include\n# LIBRARIES qr_tracker\n# CATKIN_DEPENDS rospy std_msgs\n# DEPENDS system_lib\n)\n\ninclude_directories(\n ${catkin_INCLUDE_DIRS}\n ${OpenCV_INCLUDE_DIRS}\n)\n\n#target_link_libraries(qr_tracker ${OpenCV_LIBRARIES})\n\n" }, { "alpha_fraction": 0.5331236720085144, "alphanum_fraction": 0.6047478914260864, "avg_line_length": 28.86969757080078, "blob_id": "64a651f8e623f10a5f887c30aa0df77a134141fa", "content_id": "c89be8e06b2f5b40342f56ebdb49bb058fdd21d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9857, "license_type": "no_license", "max_line_length": 165, "num_lines": 330, "path": "/qr_tracker/src/qr_tracker.py", "repo_name": "blukaz/shop-robo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport cv2\nimport math\nimport time\nimport copy\nfrom matplotlib import pyplot as plt\nfrom numpy.linalg import inv\nimport roslib\nimport rospy\nfrom geometry_msgs.msg import Pose2D\nfrom std_msgs.msg import Float32\nimport numpy as np;\n \n# Read image\n\nhd_cam = 0\n\ncap = cv2.VideoCapture(hd_cam)\n\n#fourcc = cv2.VideoWriter_fourcc(*'DIVX')\n#out = cv2.VideoWriter('QR_tracking.avi',fourcc, 10.0, (1280,720))\n\ncap.set(3,640)\ncap.set(4,480)\ncap.set(12,0.64)\ncap.set(16,1.0)\nif hd_cam == 1:\n\tcap.set(3,640)\n\tcap.set(4,480)\n\ncap.set(10,0.5)\n\nwidth = 640\nheight = 480\n\n# initialization for template matching\ntemplate = cv2.imread('/home/bare/catkin_ros/src/shop-robo/qr_tracker/src/qr_match.png', 0) # change image path to avoid error\n\nw, h = template.shape[::-1]\ntemplate_2 = template.copy()\n\n### KALMAN FILTER initializations ###\nTs = 0.02\n\nPk = np.eye(4,k=0,dtype=float)*100\n\nxk_ = np.transpose(np.matrix([width/2,height/2,0,0]))\nxk = xk_\n\nFI = np.matrix([[1,0,Ts,0],\n\t\t[0,1,0,Ts],\n\t\t[0,0,1,0],\n\t\t[0,0,0,1]])\n\nH = np.matrix([\t[1,0,0,0],\n\t\t[0,1,0,0]])\n\nQ = np.eye(4,k=0,dtype=float)*1\n\nR = np.eye(2,k=0,dtype=float)*1\n \nlast_yk = np.matrix([width/2, height/2])\nyk = np.matrix([width/2, height/2])\n\nlast_qr_center = []\nqr_center = []\nqr_template_coor = []\nqr_template_coor_last = []\ntemplate_vel_diff = [0,0]\nscale = 1\ni = 0\nim_avg = 0\n\n# initialization of pose2d msg \nqr_pose2d = Pose2D()\n\nqr_scale = Float32()\n\nwhile not rospy.is_shutdown():\n\n \tpub_pose = rospy.Publisher('qr_pose2d', Pose2D, queue_size=0)\n \tpub_scale = rospy.Publisher('qr_scale', Float32, queue_size=0)\n \trospy.init_node('qr_pose2d', anonymous=True)\n \trate = rospy.Rate(int(1/Ts)) # 50hz\n\n\t#i = i+1\n\n\t### frame grabbing and preprocessing ###\t\n\n\t# take frame from camera\n\t_, im = cap.read()\n\n\n\t# copy original frame for KF result representation\n\tim2 = im.copy()\n\n\t# filter image a\n\timg = cv2.medianBlur(im,5)\n\t\n\t# convert BGR to GRAY\n \tgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\t# smooth frame with gaussian filter - noise compensation\n\timg = cv2.GaussianBlur(gray,(7,7),2)\n\n\n\t# threshold image to get black and white image\n\tret_simple, th_simple = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\t# try experimenting with threshold value ; e.g. >200\n\n\tkernel = np.ones((5,5),np.uint8)\n#\terosion = cv2.erode(th_simple,kernel,iterations = 1)\n\n\tclosing = cv2.morphologyEx(th_simple, cv2.MORPH_CLOSE, kernel)\n\tth_simple = closing\n\n#\tcv2.imshow('dilate',closing)\n\n\t# template resizing\n\ttemplate_2 = cv2.resize(template,None,fx=scale, fy=scale, interpolation = cv2.INTER_LINEAR)\n\tw, h = template_2.shape[::-1]\n#\tcv2.imshow('template',template_2)\t\n\n\t### QR-code marker detection ###\n\t# find contours in the image\n\t_, contours, hierarchy = cv2.findContours(th_simple,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\t\n\tcentroids = []\n\t\n\t# get centroids of all contours\n\tfor i in range(0,len(contours)-1):\n\t\tcnt = contours[i]\n\t\tM = cv2.moments(cnt)\n\t\tif M['m00'] != 0:\n\t\t\tcx = int(M['m10']/M['m00'])\n\t\t\tcy = int(M['m01']/M['m00'])\n#\t\t\tcv2.circle(im,(cx,cy), 2, (0,0,255), -1)\n\t\t\tcentroids.append([cx,cy])\n\t\t\n\tqr_pose = []\n\tcont_no = []\n\n\t# find centroids of QR markers : QR-code markers consists of concetrical squares => their contours have same centroids\n\tfor i in range(0,len(centroids)-1):\n\t\tM = cv2.moments(contours[i])\n\t\tfor j in range(0,len(centroids)-1):\n\t\t\tif i != j:\n\t\t\t\tif (centroids[i][0] == centroids[j][0] and centroids[i][1] == centroids[j][1]):\n\t\t\t\t\tqr_pose.append([centroids[i],i])\n\t\t\t\t\tcont_no.append(i)\n\n\tmax_dist = math.sqrt(pow(width-0,2) + pow(height-0,2))\n\tlu = [width,height]\n\tru = [0,height]\n\tld = [width,0]\n\n\t### determine the position of the markers respect to the QR-code ###\n\t# qr marker extrapolation \t\t\n\tfor i in range(0,len(qr_pose)):\n\t\tif math.sqrt(pow(qr_pose[i][0][0]-0,2) + pow(qr_pose[i][0][1]-0,2)) < math.sqrt(pow(0-lu[0],2) + pow(0-lu[1],2)):\n\t\t\tlu = [qr_pose[i][0][0],qr_pose[i][0][1]]\n\n\t\tif math.sqrt(pow(qr_pose[i][0][0]-width,2) + pow(qr_pose[i][0][1]-0,2)) < math.sqrt(pow(width-ru[0],2) + pow(0-ru[1],2)):\n\t\t\tru = [qr_pose[i][0][0],qr_pose[i][0][1]]\n\n\t\tif math.sqrt(pow(qr_pose[i][0][0]-0,2) + pow(qr_pose[i][0][1]-height,2)) < math.sqrt(pow(0-ld[0],2) + pow(height-ld[1],2)):\n\t\t\tld = [qr_pose[i][0][0],qr_pose[i][0][1]]\n\t\n\t# image averaging\n\tim_avg = im2*10\n\tim_avg[int(xk[1,0]-h):int(xk[1,0]+h),int(xk[0,0]-w):int(xk[0,0]+w),:] = im2[int(xk[1,0]-h):int(xk[1,0]+h),int(xk[0,0]-w):int(xk[0,0]+w),:] \n\n\n\t# draw the position of the markers in the image\n\tif lu == ru or lu == ld:\n\t\tif (ru[0]-ld[0]) == 0:\n\t\t\tk = float('inf')\n\t\telse:\n\t\t\tk = abs(float((ru[1]-ld[1]))/float((ru[0]-ld[0])))\n\n\t\tif k <= 0.5:\n\t\t\tld = [lu[0], lu[1]+int(math.sqrt(pow(lu[0]-ru[0],2) + pow(lu[1]-ru[1],2)))]\n\t\telif k >= 5:\n\t\t\tru = [lu[0] + int(math.sqrt(pow(lu[0]-ld[0],2) + pow(lu[1]-ld[1],2))), lu[1]]\n\t\telif k > 0.5 and k < 5:\n\t\t\tlu = [ld[0], ru[1]]\n\tif lu == ru and ru == ld:\n\t\tim_avg[int(lu[1]-h):int(lu[1]+h),int(lu[0]-w):int(lu[0]+w),:] = im2[int(lu[1]-h):int(lu[1]+h),int(lu[0]-w):int(lu[0]+w),:]\n\n#\tcv2.imshow('im_avg',im_avg)\n\t\n\t# filter image a\n\tim_avg = cv2.medianBlur(im_avg,5)\n\n\t# convert BGR to GRAY\n\tim_avg_gray = cv2.cvtColor(im_avg, cv2.COLOR_BGR2GRAY)\n\n\t\n\t# smooth frame with gaussian filter - noise compensation\n\tim_avg_blur = cv2.GaussianBlur(im_avg_gray,(7,7),2)\n\n\t\n\t### template match ###\n\tres = cv2.matchTemplate(im_avg_blur,template_2,5)\n\tmin_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n#\tprint max_val\n#\tcv2.imshow('template',res)\n#\tcv2.imshow('img',im_avg_blur)\n\ttop_left = max_loc\n\tbottom_right = (top_left[0] + w, top_left[1] + h)\n\tcv2.rectangle(im,top_left, bottom_right, 255, 2)\n\tqr_template_coor_last = qr_template_coor\n\tqr_template_coor = [top_left[0] + w/2, top_left[1] + h/2]\n\tcv2.circle(im,(top_left[0] + w/2,top_left[1] + h/2), 6, (0,0,255), -1)\n\tif qr_template_coor_last != []:\n\t\ttemplate_vel_diff = [qr_template_coor_last[0] - qr_template_coor[0] + template_vel_diff[0], qr_template_coor_last[1] - qr_template_coor[1] + template_vel_diff[1]]\n#\t\tprint template_vel_diff\n\n\t\n\tif lu[0] != width and lu[1] != height:\n\t\tcv2.circle(im,(lu[0],lu[1]), 6, (0,0,255), -1)\n\n\tif ru[0] != 0 and ru[1] != height and ru != lu:\n\t\tcv2.circle(im,(ru[0],ru[1]), 6, (0,0,255), -1)\n\n\tif ld[0] != width and ld[1] != 0 and ld != lu and ld != ru:\n\t\tcv2.circle(im,(ld[0],ld[1]), 6, (0,0,255), -1)\t\n\n\tif lu[0] != width and lu[1] != height and ru[0] != 0 and ru[1] != height and ld[0] != width and ld[1] != 0:\n\t\tcv2.line(im,(lu[0],lu[1]),(ru[0],ru[1]),(0,255,0),2)\n\t\tcv2.line(im,(lu[0],lu[1]),(ld[0],ld[1]),(0,255,0),2)\n\t\tcv2.line(im,(ld[0],ld[1]),(ru[0],ru[1]),(0,255,0),2)\n\n\t# check if 3 unique markers are detected\n\tif lu != ru and lu != ld and ru != ld:\n\t\tqr_markers_3 = True\n\telse:\n\t\tqr_markers_3 = False\n\n\t# find the centroid of the QR-code based on the found markers\n\tif lu != [] and ru != [] and ld != []:\n\t\tqr_area = abs(ld[1] - ru[1])*abs(ld[0] - ru[0])\n\t\tqr_a = pow(qr_area,0.5)\n#\t\tprint float(qr_area)/float((1280*720))*100, '%'\n\t\tlast_qr_center = qr_center\n\t\tqr_center = [abs(ld[0] + ru[0])/2 , abs(ld[1] + ru[1])/2]\n\t\tcv2.circle(im,(qr_center[0],qr_center[1]), 6, (255,0,0),-1)\n\t\n\t# display the result\n#\tcv2.imshow('threshold', th_simple)\n\tcv2.imshow('result without KF',im)\n\t\n\tif last_qr_center == []:\n\t\tcontinue\n\n\t### KALMAN FILTER : 2D QR-code tracking ###\n\t\n\t# prediction based on model \n\txk_ = np.dot(FI, xk_)\n\tPk = np.dot(FI, np.dot(Pk, FI.transpose())) + Q\n\tKk = np.dot(Pk, np.dot(H.transpose(), inv(np.dot(H, np.dot(Pk, H.transpose())) + R)))\n\n\t## Additional qr-marker algorithm used for measurements ##\n\n\t\n\t\n\t##########################################################\n\n\t# measurement\n\tif lu != ld and lu != ru and lu != [width,height] and ru != [0,height] and ld != [width,0]:\t\n\t\tlast_yk = yk\n\t\tyk = np.matrix([float(qr_center[0]), float(qr_center[1])])\n\t\tscale = (float(qr_a)/float(200))*1.5\n\t\tR = np.eye(2,k=0,dtype=float)*1\n\t\tprint scale\n\t\tqr_scale.data = float(qr_area)/float((width*height))*100\n\t\tpub_scale.publish(qr_scale)\n\t\t\n\t\tif abs((math.sqrt(pow(lu[0]-ru[0],2) + pow(lu[1]-ru[1],2)))/(math.sqrt(pow(lu[0]-ld[0],2) + pow(lu[1]-ld[1],2)))) <= 1:\n\t\t\tqr_pose2d.theta = (180/3.14)*math.acos((math.sqrt(pow(lu[0]-ru[0],2) + pow(lu[1]-ru[1],2)))/(math.sqrt(pow(lu[0]-ld[0],2) + pow(lu[1]-ld[1],2))))\n\t\t\n\telif abs(template_vel_diff[0]) < 100 and abs(template_vel_diff[1]) < 100:\n\t\tlast_yk = yk\n\t\tyk = np.matrix([float(qr_template_coor[0]), float(qr_template_coor[1])])\n\t\tR = np.eye(2,k=0,dtype=float)*10\n\telse:\n\t\tlast_yk = yk\n\t\tyk = np.transpose(np.dot(H, xk_))\n\n\n\t# korection based on measurement\n\txk = xk_ + np.dot(Kk, (np.transpose(yk) - np.dot(H, xk_)))\n\tPk = np.dot((np.eye(4,k=0,dtype=float) - np.dot(Kk,H)), Pk)\n\txk_[2,0] = (yk[0,0]-last_yk[0,0])/1\n\txk_[3,0] = (yk[0,1]-last_yk[0,1])/1\n\txk_[0,0] = xk[0,0]\n\txk_[1,0] = xk[1,0]\n\n#\tprint \"KF center: \", [xk[0,0], xk[1,0]]\n#\tprint \"measured center: \", qr_center\n#\tprint xk\n\n\n#\tcv2.circle(im2,(qr_center[0],qr_center[1]), 8, (0,255,255), -1)\n\tcv2.circle(im2,(int(xk[0,0]),int(xk[1,0])), 20, (255,0,255), -1)\n\n\tif int(xk[2,0]) > 0:\n\t\tcv2.line(im2,(int(xk[0,0]),int(xk[1,0])),(int(xk[2,0])+int(xk[0,0]),int(xk[1,0])),(0,255,0),2)\n\telse:\n\t\tcv2.line(im2,(int(xk[0,0]),int(xk[1,0])),(int(xk[2,0])+int(xk[0,0]),int(xk[1,0])),(0,0,255),2)\n\tif int(xk[3,0]) > 0:\n\t\tcv2.line(im2,(int(xk[0,0]),int(xk[1,0])),(int(xk[0,0]),int(xk[3,0])+int(xk[1,0])),(0,255,0),2)\n\telse:\n\t\tcv2.line(im2,(int(xk[0,0]),int(xk[1,0])),(int(xk[0,0]),int(xk[3,0])+int(xk[1,0])),(0,0,255),2)\n\n\tcv2.ellipse(img,(int(xk[0,0]),int(xk[1,0])),(int(Pk[0,0]),int(Pk[1,1])),0,0,360,(255,0,255),2)\n\tcv2.imshow('result with KF',im2)\n#\tout.write(im2)\n\n\t# fill and publish 2D pose msg of QR code\n\tqr_pose2d.x = xk[0,0]\n\tqr_pose2d.y = xk[1,0]\n#\tqr_pose2d.theta = 0\n\tpub_pose.publish(qr_pose2d)\n rate.sleep()\n\n\tif cv2.waitKey(1) & 0xFF == ord('q'):\n\t\tbreak\n\ncap.release()\ncv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.6175017356872559, "alphanum_fraction": 0.6450247168540955, "avg_line_length": 19.83823585510254, "blob_id": "e0e7ccf4731650d089a8de8674515d6a676839f4", "content_id": "7a19df57bc4cb19336e7e6c4e8cc473061d93350", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1417, "license_type": "no_license", "max_line_length": 80, "num_lines": 68, "path": "/qr_follower/src/qr_follower.py", "repo_name": "blukaz/shop-robo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport math\nimport time\nimport copy\nimport roslib\nimport rospy\nfrom geometry_msgs.msg import Pose2D\nfrom geometry_msgs.msg import Twist\nfrom std_msgs.msg import Float32\n\nglobal camera_width\ncamera_width = 640\n\ndef call_qr_pose(data):\n\tr = rospy.Rate(50);\n\tpub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)\n\t\n\tturn_cmd = Twist()\n\n\tif ((data.x - camera_width/2) > -50 and (data.x - camera_width/2) < 50):\n\t\trospy.loginfo(\"in deadzone\")\n\telse:\n\t\tturn_cmd.angular.z = math.pi/10 * ((data.x - camera_width/2)/(camera_width/2))\n\t\tpub.publish(turn_cmd)\n\t\tr.sleep()\n\t\trospy.loginfo(\"outside deadzone\")\n\n\ndef call_qr_scale(data):\n\n\n\tr = rospy.Rate(20);\n\t\n\tpub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)\n\n\tmove_cmd = Twist()\n\n\trospy.loginfo(\"scale: %f\", data.data)\n\t\n\tif ( data.data > 2 ):\n\t\tmove_cmd.linear.x = 0.0\n\t\tpub.publish(move_cmd)\n\t\tr.sleep()\t\t\n\t\trospy.loginfo(\"hold position\")\n\telif ( (data.data < 2) and (data.data > 1) ):\n\t\tmove_cmd.linear.x = 1.0*(2 - data.data)\n\t\tpub.publish(move_cmd)\n\t\tr.sleep()\t\t\n\t\trospy.loginfo(\"hold distance\")\n\telif ( data.data < 1 ):\n\t\tmove_cmd.linear.x = 1.0\n\t\tpub.publish(move_cmd)\n\t\tr.sleep()\t\t\n\t\trospy.loginfo(\"keep up\")\t\t\n \n\n\n\ndef run():\n rospy.init_node('follow_qr')\n rospy.Subscriber(\"/qr_pose2d\", Pose2D, call_qr_pose)\n rospy.Subscriber(\"/qr_scale\", Float32, call_qr_scale)\n\n rospy.spin()\n\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.7843137383460999, "alphanum_fraction": 0.7908496856689453, "avg_line_length": 37.25, "blob_id": "2871da205f1b5d7bd142d48553171c60b79e09b5", "content_id": "912a22450a4dbe65ea1866ae6d0af5a9846d4637", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 153, "license_type": "no_license", "max_line_length": 109, "num_lines": 4, "path": "/README.md", "repo_name": "blukaz/shop-robo", "src_encoding": "UTF-8", "text": "# shop-robo\n### QR detection and tracking\n\nImplementation of modified Kalman Filter for QR detection and tracking in a 2D image retreived from a camera.\n" } ]
4
annasupergirl/Todo
https://github.com/annasupergirl/Todo
a90e85dbcb947082d15b6c216b6efd207b414af9
5add981633ff225d8964d13b56d16fd918eaa306
92360c7993f61a4a6ebb3389556dfd4984360ada
refs/heads/master
2021-01-12T10:04:23.682644
2016-12-16T12:58:23
2016-12-16T14:38:51
76,349,094
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6047047972679138, "alphanum_fraction": 0.6143911480903625, "avg_line_length": 25.439023971557617, "blob_id": "b843897a70d5849f596f1a51e50876a7b8c72151", "content_id": "653896ab98e5976a5a3358f046706e033ecff903", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2168, "license_type": "no_license", "max_line_length": 96, "num_lines": 82, "path": "/index.py", "repo_name": "annasupergirl/Todo", "src_encoding": "UTF-8", "text": "import pymongo, json\n\nfrom flask import Flask, render_template, jsonify, request\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\nfrom bson import json_util\n\napp = Flask(__name__)\nmongo = MongoClient()\n\ndb = mongo.todo_database\n\ndef make_error(status_code, message):\n response = jsonify({\n 'status': 'ERROR',\n 'message': message\n })\n response.status_code = status_code\n\n return response\n\[email protected]('/')\ndef index():\n return render_template(\"start.html\")\n\[email protected]('/todo',methods=['GET'])\ndef getTaskList():\n try:\n tasks = db.todo_list.find()\n\n return json_util.dumps(tasks)\n except Exception,e:\n return make_error(503, str(e))\n\[email protected]('/todo/<string:task_id>',methods=['GET'])\ndef getTask(task_id):\n try:\n task = db.todo_list.find_one({'_id':ObjectId(task_id)})\n\n if task:\n return json_util.dumps(task)\n else:\n return make_error(404, \"404: Not Found\")\n\n except Exception,e:\n return make_error(503, str(e))\n\[email protected]('/todo',methods=['POST'])\ndef addTask():\n try:\n json_data = json.loads(request.data) \n title = json_data['task']\n done = json_data['done']\n\n db.todo_list.insert_one({ 'title': title, 'done': done })\n return jsonify(status='OK',message='inserted successfully')\n\n except Exception,e:\n return make_error(503, str(e))\n\[email protected]('/todo/<string:task_id>',methods=['PATCH'])\ndef updateTask(task_id):\n try:\n taskInfo = json.loads(request.data)\n title = taskInfo['task']\n done = taskInfo['done']\n\n db.todo_list.update_one({'_id':ObjectId(task_id)},{'$set':{'title':title, 'done':done}})\n return jsonify(status='OK',message='updated successfully')\n except Exception, e:\n return make_error(503, str(e))\n\[email protected]('/todo/<string:task_id>',methods=['DELETE'])\ndef deleteTask(task_id):\n try:\n db.todo_list.delete_one({'_id':ObjectId(task_id)})\n return jsonify(status='OK',message='deletion successful')\n except Exception, e:\n return make_error(503, str(e))\n\nif __name__ == \"__main__\":\n app.run()\n" }, { "alpha_fraction": 0.6567164063453674, "alphanum_fraction": 0.7044776082038879, "avg_line_length": 19.9375, "blob_id": "6bd6f81f80a0bda0cc8d677bf8f179008f61b703", "content_id": "3c0e691a3d52e73125613b230ab7262098c84ebc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 363, "license_type": "no_license", "max_line_length": 71, "num_lines": 16, "path": "/README.md", "repo_name": "annasupergirl/Todo", "src_encoding": "UTF-8", "text": "## Установка зависимостей\n\n[Python 2.7](https://www.python.org/download/releases/2.7/)\n\n[Flask](http://flask.pocoo.org/)\n\n[Mongo](https://docs.mongodb.com/v3.0/administration/install-on-linux/)\n\n[PyMongo](https://docs.mongodb.com/getting-started/python/client/)\n\n## Start todo\n```\npython index.py\n```\n\nБраузер - http://127.0.0.1:5000/\n" }, { "alpha_fraction": 0.514126718044281, "alphanum_fraction": 0.514126718044281, "avg_line_length": 23.589473724365234, "blob_id": "bf2a19fcdddc6d049d059257b233b09ed513ad94", "content_id": "f952e785d6a9a8b8b85107448b13f9f6c8d05608", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2336, "license_type": "no_license", "max_line_length": 61, "num_lines": 95, "path": "/static/js/app.js", "repo_name": "annasupergirl/Todo", "src_encoding": "UTF-8", "text": "(function() {\n 'use strict';\n\n angular.module('app', ['ngRoute'])\n\t\t.config(config)\n\t\t.controller('TodoCtrl', TodoCtrl)\n\t\t.controller('UpdateCtrl', UpdateCtrl);\n\n\tfunction config($routeProvider) {\n\t\t$routeProvider\n \t\t.when('/', {\n \t\t\tcontroller:'TodoCtrl',\n \t\t\tcontrollerAs: 'todoVm',\n\t \t\ttemplateUrl:'static/views/todo.html'\n \t\t})\n\t\t\t.when('/edit/:taskId', {\n \t\t\tcontroller:'UpdateCtrl',\n \t\t\tcontrollerAs: 'updateVm',\n \t\t\ttemplateUrl:'static/views/update.html'\n\t \t\t})\n \t\t.otherwise({\n\t\t\t\tredirectTo: '/'\n\t\t\t});\n\t}\n\n function TodoCtrl($http) {\n \tvar vm = this;\n\n \tvm.showlist = showlist;\n \tvm.addTask = addTask;\n \tvm.deleteTask = deleteTask;\n\n \tvm.showlist();\n\n \tfunction showlist() {\n\t\t\treturn $http.get('/todo')\n\t\t\t\t.then(function(response) { vm.tasks = response.data; })\n \t\t.catch(function(error) { console.log(error); });\n\t\t}\n\n \tfunction addTask() {\n \t$http({\n \tmethod: 'POST',\n\t url: '/todo',\n data: {\n \t task: vm.title,\n \t done: false\n },\n\t headers: {'Content-Type': 'application/json'}\n \t })\n \t.then(function() { vm.title = ''; })\n \t.catch(function(error) { console.log(error); });\n\n vm.showlist();\n }\n\n\t\tfunction deleteTask(id) {\n\t\t\t$http.delete('/todo/' + id)\n\t\t\t\t.then(function(response) { console.log(response); })\n \t\t.catch(function(error) { console.log(error); });\n\n \t\tvm.showlist();\n\t\t}\n \t}\n\n function UpdateCtrl($http, $routeParams, $location) {\n \tvar vm = this,\n \t taskId = $routeParams.taskId;\n\n \tvm.getTask = getTask;\n \tvm.updateTask = updateTask;\n\n \tvm.getTask(taskId);\n\n\t function getTask(id) {\n\t\t\treturn $http.get('/todo/' + id)\n \t\t\t.then(function(response) { vm.task = response.data; })\n \t\t.catch(function(error) { console.log(error); });\n \t}\n\n \tfunction updateTask(id) {\n\t\t\treturn $http({\n \t\tmethod: 'PATCH',\n\t \t\turl: '/todo/' + id,\n \t\tdata: {\n \t task: vm.task.title,\n \t done: vm.task.done\n \t},\n\t headers: {'Content-Type': 'application/json'}\n\t\t\t})\n\t\t\t.then(function() { $location.path('/'); })\n \t.catch(function(error) { console.log(error); });\n\t\t}\n }\n})();\n" } ]
3
Sachka/OrangesOrLemons
https://github.com/Sachka/OrangesOrLemons
1aba6d370c7f2a1e65a3a390b8d6eaee3cfbe953
90ff06e066c9bc102ed25fb737718b796ecf4939
839e21fabdbaac77a44a25c496fead42c0e5966a
refs/heads/master
2016-09-14T13:07:56.582221
2016-05-13T15:33:05
2016-05-13T15:33:05
58,645,604
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5615866184234619, "alphanum_fraction": 0.5939457416534424, "avg_line_length": 31.466102600097656, "blob_id": "956d71e50ca20e3202e7c0dfed577c089d1d1688", "content_id": "432e26f85a2d26fd900b67f9c33a6a9415790d56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3843, "license_type": "no_license", "max_line_length": 115, "num_lines": 118, "path": "/rechercheKNN.py", "repo_name": "Sachka/OrangesOrLemons", "src_encoding": "UTF-8", "text": "#!usr /bin/env python\n# -*- coding: utf -8 -*-\n\nimport math\n\nclass Instance:\n\t\"\"\"definition d'une classe instance\"\"\"\n\n\tdef __init__(self, categorie, coords):\n\t self.cat = categorie\n\t self.coords = coords\n\n\tdef __str__(self):\n\t return \"Instance de catégorie '{}' et de coordonnées '{}'\".format(self.cat, self.coords)\n\n\t# Calcul de la distance entre l'instance et un autre point\n\tdef distance(self, other):\n\t produit = 0\n\t for i in range(len(self.coords)):\n\t\tproduit += math.pow(self.coords[i] - other.coords[i], 2)\n\t return math.sqrt(produit)\n \n\t# Méthode retournant les k plus proches voisins de l'instance\n \"\"\"\n @param k : nombre de comparaison, à définir\n @param listeInstances : liste contenant des objets Instances\n \"\"\"\n\tdef knn(self, k, listeInstances):\n\t # retourne la liste des k inst dont les distances par rapport à self sont les plus petites\n\t # les inst sont prises de listeInstances\n\t # dist : calculé avec Instance.distance\n\t return [inst for (dist,inst) in sorted([(Instance.distance(self, inst),inst) for inst in listeInstances])][:k]\n\n ############\ndef most_common(listeInstances):\n cat=[]\t\t\t\t\t#Liste\n for inst in listeInstances:\n cat.append(inst.cat) \t\t\t# Ajout des catégories seulement parmi les inst de listeInstances \n return max(set(cat), key=cat.count)\t\t# retour de la catégorie la plus fréquente\n\n ############\ndef classify(k, instance, all_instance):\n return most_common(Instance.knn(instance,k,all_instance)) #retour la plus fréquente \n\n ############\ndef read_instance(filename):\n listeInstances = []\n fichier = open(filename, 'r')\n lignes = fichier.readlines() \n fichier.close()\n for inst in lignes:\n listeInstances.append(Instance(inst.split()[0], (inst.split()[1:])))\n return listeInstances\n\n ############\ndef pred_liste(listeInstancesConnues, listeInstancesInconnues): \n\tk = 0\n\tif len(listeInstancesConnues) % 2 == 0:\n\t\tk = len(listeInstancesConnues) - 1\n\telse:\n\t\tk = len(listeInstancesConnues)\n\tfor inst in range(len(listeInstancesInconnues)):\n \tif listeInstancesInconnues[inst].cat == \"\":\n \t listeInstancesInconnues[inst].cat = classify(3,listeInstancesInconnues[inst],listeInstancesConnues)\n\tfor inst in listeInstancesInconnues:\n\t\tprint inst\n\n ############\ndef eval_classif(ref_instances, pred_instances):\n if len(ref_instances) == len(pred_instances):\n i=0\n l1 = list(ref_instances)\n l2 = list(pred_instances)\n for j in range(len(l1)):\n for k in range(len(l2)):\n if l1[j].cat == l2[k].cat and l1[j].coords == l2[k].coords:\n i+=1\n del l2[k]\n break\n return (100*i)/len(ref_instances)\n else:\n return \"taille liste erreur\"\n\n ############\n \n \n#############################################\n ######### PROGRAMME PRINCIPAL ######### \n\na = Instance(\"citron\", (1.5, 3.5))\nb = Instance(\"citron\", (4.5, 2.5))\nc = Instance(\"orange\", (4.5, 4.5))\nd = Instance(\"orange\", (4.5, 3.5))\ne = Instance(\"orange\", (4.5, 3.6))\nf = Instance(\"orange\", (4.5, 3.7))\nh = Instance(\"orange\", (4.5, 5.5))\ni = Instance(\"citron\", (1.5, 3.6))\nk = Instance(\"citron\", (1.5, 3.6))\nj = Instance(\"citron\", (1.5, 3.7))\nL = [a, b, c, d, e, f, h, i, j, k]\n\n\na2 = Instance(\"citron\", (1.5, 3.5))\nb2 = Instance(\"citron\", (4.5, 2.5))\nc2 = Instance(\"orange\", (4.5, 4.5))\nd2 = Instance(\"orange\", (4.5, 3.5))\ne2 = Instance(\"citron\", (4.5, 3.6))\nf2 = Instance(\"citron\", (4.5, 3.7))\nh2 = Instance(\"citron\", (4.5, 5.5))\ni2 = Instance(\"citron\", (1.5, 3.6))\nk2 = Instance(\"citron\", (1.5, 3.6))\nj2 = Instance(\"orange\", (1.5, 3.7))\n\nM = [a2, b2, c2, d2, e2, f2, h2, i2, j2, k2]\n\n\nliste = read_instance('orangesorlemons')\nprint eval_classif(L, M)\n\n" }, { "alpha_fraction": 0.6039215922355652, "alphanum_fraction": 0.7450980544090271, "avg_line_length": 62.75, "blob_id": "933085eda214feb0c38095bdd1886b77ddee155a", "content_id": "451303a09ecfe2b063cb6adeb36ec1967b41c8a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 255, "license_type": "no_license", "max_line_length": 83, "num_lines": 4, "path": "/README.md", "repo_name": "Sachka/OrangesOrLemons", "src_encoding": "UTF-8", "text": "# OrangesOrLemons\nMost lemons: weight 2.87oz to 3.27oz, lenght 1.86in to 2.83in, yellow, green\nMost apples: weight 6.70oz to 9.00oz, lenght 2.10in to 3.10in, yellow, green or red\nMost oranges: weight 3.90oz to 6.30, lenght 2.75in to 3.25in, orange, green\n" }, { "alpha_fraction": 0.6322503685951233, "alphanum_fraction": 0.6408212184906006, "avg_line_length": 38.1953125, "blob_id": "0c1156a10c76f15a811def22e322eb338bbc8f4b", "content_id": "d3e2bc5c4ccc2941ddbb56dee6d264e9e9bfd4da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5030, "license_type": "no_license", "max_line_length": 198, "num_lines": 128, "path": "/knn.py", "repo_name": "Sachka/OrangesOrLemons", "src_encoding": "UTF-8", "text": "#!usr /bin/env python3\n# -*- coding: utf -8 -*-\n\nimport math\nimport sys\n\nclass Fruit:\n\n \"\"\"\n A Fruit is made of a species name (ex: \"apple\") and its attributes (weight, size and color).\n Attributes are made of a list of real numbers each corresponding to a specific attribute.\n There are exactly 3 attributes, weight, size and color.\n \"\"\"\n def __init__(self, species, attributes):\n self.species = species\n self.attributes = attributes\n def __str__(self):\n return \"Fruit de catégorie '{}' et de coordonnées '{}'\".format(self.species, self.attributes)\n\n # 'distance(self, another_fruit)' measures the distance or \"difference\" between two Fruit.\n def distance(self, another_fruit):\n return math.sqrt((self.attributes[0] - another_fruit.attributes[0]) **2 + (self.attributes[1] - another_fruit.attributes[1]) **2 + (self.attributes[2] - another_fruit.attributes[2]) **2)\n\n # k Nearest-Neightbor return method.\n def knn(self, k, fruit_list):\n return [fruit for (distance, fruit) in sorted([(Fruit.distance(self, fruit), fruit) for fruit in fruit_list])][:k]\n\"\"\"\n@param fruit_list\n\"\"\"\n# Most similar Fruit from fruit_list return method.\ndef most_similar_fruit(fruit_list):\n species = []\n for fruit in fruit_list:\n species.append(fruit.species)\n return max(set(species), key=species.count)\n\n# Method for assigning a species name to a Friut by looking at its k nearest neightbors.\ndef classify_fruit(k, fruit, all_fruits):\n return most_similar_fruit(Fruit.knn(fruit, k, all_fruits))\n\n# Method for reading lines from a text file.\ndef read_lines(filename):\n data_file = open(filename, 'r')\n lines = data_file.readlines()\n data_file.close()\n return lines\n #return data_file = open(filename, 'r').readlines.close()\n\n# Method for retrieving knowledge (learned Fruit) from a text file.\ndef retrieve_knowledge(knowledge_filename):\n knowledge_list = []\n lines = read_lines(knowledge_filename)\n for line in lines:\n # A species name and exactly 3 attributes are retrieved.\n knowledge_list.append(Fruit(line.split()[0],(float(line.split()[1]),float(line.split()[2]),float(line.split()[3]))))\n return knowledge_list\n\n# Method for retrieving an unknow or uncategorised set of fruits.\ndef retrieve_unknown_data(unknown_data_filename):\n fruit_list = []\n lines = read_lines(unknown_data_filename)\n for line in lines:\n # Species name is intentionally not retrieved, a \"?\" is assigned instead, 3 attributes are retrieved.\n fruit_list.append(Fruit(\"?\", (float(line.split()[1]), float(line.split()[2]), float(line.split()[3]))))\n return fruit_list\n'''\n@param k: Number of k-nearest-neightbors used to determine a Fruit.species\n@param unknown_fruit_list: une liste dont toute les instances ne sont pas toutes catégorisées.\n@param knowledge_fruit_list: knowledge used to classify a Fruit.\nLa fonction catégorise les instances qui ne le sont pas.\n'''\ndef predict_fruit(k, unknown_fruit_data, knowledge_fruit_list):\n unknown_fruit_list = retrieve_unknown_data(unknown_fruit_data)\n for fruit in range(len(unknown_fruit_list)):\n unknown_fruit_list[fruit].species = classify_fruit(k, unknown_fruit_list[fruit], knowledge_fruit_list)\n return unknown_fruit_list\n\ndef eval_classif(ref_instances, pred_instances):\n if len(ref_instances) == len(pred_instances):\n i=0\n l1 = list(ref_instances)\n l2 = list(pred_instances)\n for j in range(len(l1)):\n for k in range(len(l2)):\n if l1[j].species == l2[k].species:\n i+=1\n del l2[k]\n break\n return (100*i)/len(ref_instances)\n else:\n print(\"taille liste erreur\")\n################Test#########################################\n\n\n\n\ndef main():\n usage = \"Hello\"\n while True:\n try:\n break\n except (IOError, ValueError, IndexError):\n print(usage)\n sys.exit(0)\n print (\"Le fichier avec les instances non catégorisé:\")\n for elt in retrieve_unknown_data(\"unknownfruits\"):\n print(elt)\n print(\"\\n\")\n\n print(\"On lance le processus de catégorisation par rapport a 10 voisins (k=10)\")\n print(\"Catégorisation terminé, voici le fichier:\")\n for elt in predict_fruit(10, \"unknownfruits\", retrieve_knowledge(\"orangesorlemons\")):\n print(elt)\n print(\"\\n\")\n\n print(\"Le fichier d'origine:\")\n for elt in retrieve_knowledge(\"orangesorlemons\"):\n print(elt)\n print(\"\\n\")\n\n print(\"On lance le processus d'évaluation de la pertinance des prediction faites:\")\n print(\"Processus terminé, voici le résultat: \")\n print(\"%d pourcent\" % eval_classif(retrieve_knowledge(\"unknownfruits\"), predict_fruit(10, \"unknownfruits\", retrieve_knowledge(\"orangesorlemons\"))))\n print(\"\\n\")\n sys.exit(0)\n\nif __name__ == '__main__':\n main()\n" } ]
3
srikanya659qwe/sri
https://github.com/srikanya659qwe/sri
16a701c7160b3c2cd0ed2bb8db044814728d55b6
cf41135619d95030a761c220d90c2d9737be506c
4cab447ed645f76338d98c746fc236c78c1eed4a
refs/heads/master
2020-09-16T21:54:11.118282
2019-11-25T08:31:16
2019-11-25T08:31:16
223,897,878
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7931034564971924, "alphanum_fraction": 0.7931034564971924, "avg_line_length": 13.5, "blob_id": "eb259a08b8f8979d4086eb4e8b12a291ceb21a28", "content_id": "e513143f6b66066f59924dcf2a5951afee6dc8d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 29, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/README.md", "repo_name": "srikanya659qwe/sri", "src_encoding": "UTF-8", "text": "# sri\nregarding django files\n" }, { "alpha_fraction": 0.7460317611694336, "alphanum_fraction": 0.7571428418159485, "avg_line_length": 30.5, "blob_id": "78bfc787f62a5f542454c43b9e3c7800936c52a5", "content_id": "c4a0ee580469807931abe8cad4c4e85362b8960a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 55, "num_lines": 20, "path": "/samplepro/mystore/views.py", "repo_name": "srikanya659qwe/sri", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nimport datetime\ndef showmsg(request):\n\treturn HttpResponse(\"<h1>hai this is srikanya</h1>\")\n\ndef index(request):\n\ttm=datetime.datetime.now()\n\treturn HttpResponse(\"<h2>hai time now is %s</h2>\" %tm)\n\ndef signup(request):\n\treturn render(request,'mystore/signup.html')\ndef register(request):\n\treturn render(request,'mystore/register.html')\ndef sri1(request):\n\tcontent={'name':'srikanya'}\n\treturn render(request,'mystore/name.html',content)\ndef sri2(request):\n\tcontent={'name':'srikanya','dist':'srikakulam'}\n\treturn render(request,'mystore/name2.html',content)\n" }, { "alpha_fraction": 0.6782132983207703, "alphanum_fraction": 0.6918869614601135, "avg_line_length": 36.82758712768555, "blob_id": "94edc2d648039a4a0cbaa46268917e6431f294a4", "content_id": "6d0968c021c52c262de2ac67c57982e82473cc84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1097, "license_type": "no_license", "max_line_length": 77, "num_lines": 29, "path": "/samplepro/samplepro/urls.py", "repo_name": "srikanya659qwe/sri", "src_encoding": "UTF-8", "text": "\"\"\"samplepro URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom mystore import views as ms_view\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('sri/',ms_view.showmsg,name='showmsg'),\n path('index/',ms_view.index,name='index'),\n path('signup/',ms_view.signup,name='mysignup'),\n path('register/',ms_view.register,name='myregister'),\n path('sris/sri1',ms_view.sri1,name='my-sri1'),\n path('sris/sri12',ms_view.sri2,name='my-sri2')\n\n]\n" } ]
3
xenon-middleware/xenon-tutorial
https://github.com/xenon-middleware/xenon-tutorial
704cd25920ab008d88a6c605fa77ebcf135e782f
92e4e4037ab2bc67c8473ac4366ff41326a7a41c
81e3d8772ec2b1cc95530fe87d7794cb080f49cf
refs/heads/master
2022-02-26T08:01:22.225051
2019-09-12T15:50:25
2019-09-12T15:50:25
46,869,552
0
0
Apache-2.0
2015-11-25T15:19:36
2019-09-11T14:00:02
2019-09-12T06:57:21
Java
[ { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.7883597612380981, "avg_line_length": 46.25, "blob_id": "2d609d49bfab0e78ee1d2337e2363dbb562bda3f", "content_id": "20a57d90acd765286e03276f41755eef20bc35b9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 189, "license_type": "permissive", "max_line_length": 100, "num_lines": 4, "path": "/readthedocs/code-tabs/bash/SlurmQueuesGetter.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat queues\n# returns:\n# Available queues: mypartition, otherpartition\n# Default queue: mypartition\n" }, { "alpha_fraction": 0.6639973521232605, "alphanum_fraction": 0.6863530278205872, "avg_line_length": 35.10843276977539, "blob_id": "f3574f1cbc508bc756350fe580a84ed6080c5689", "content_id": "b74331e4ef6e5d494bfaa1870b7de5a883539156", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2997, "license_type": "permissive", "max_line_length": 153, "num_lines": 83, "path": "/consistent-versions-test.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/bin/env bash\n\nXENON_VERSION=3.0.4\nXENON_CLI_VERSION=3.0.4\nXENON_ADAPTORS_CLOUD_VERSION=3.0.2\n\nVERBOSE=1\n\ntest () {\n if [ \"$VERBOSE\" -eq 1 ]\n then\n echo \"actual = $actual\"\n echo \"expected = $expected\"\n echo\n fi\n if [ \"$actual\" == \"$expected\" ]; then\n # good\n return 0\n else\n # bad\n return 1\n fi\n}\n\n\necho \"checking .travis.yml\"\n\nactual=$(head --lines=+14 .travis.yml | tail --lines=1)\nexpected=\" - \\\"wget https://github.com/xenon-middleware/xenon-cli/releases/download/v$XENON_CLI_VERSION/xenon-cli-shadow-$XENON_CLI_VERSION.tar\\\"\"\ntest $actual $expected || exit 1\n\nactual=$(head --lines=+15 .travis.yml | tail --lines=1)\nexpected=\" - \\\"tar -xvf xenon-cli-shadow-$XENON_CLI_VERSION.tar\\\"\"\ntest $actual $expected || exit 1\n\nactual=$(head --lines=+17 .travis.yml | tail --lines=1)\nexpected=\" - \\\"mv xenon-cli-shadow-$XENON_CLI_VERSION /home/travis/.local/bin/xenon/\\\"\"\ntest $actual $expected || exit 1\n\nactual=$(head --lines=+20 .travis.yml | tail --lines=1)\nexpected=\" - \\\"echo 'PATH=\\$PATH:/home/travis/.local/bin/xenon/xenon-cli-shadow-$XENON_CLI_VERSION/bin' >> /home/travis/.bashrc\\\"\"\ntest $actual $expected || exit 1\n\necho \"checking readthedocs/code-tabs/java/build.gradle\"\n\nactual=$(head --lines=+12 readthedocs/code-tabs/java/build.gradle | tail --lines=1)\nexpected=\" implementation 'nl.esciencecenter.xenon:xenon:$XENON_VERSION'\"\ntest $actual $expected || exit 1\n\nactual=$(head --lines=+13 readthedocs/code-tabs/java/build.gradle | tail --lines=1)\nexpected=\" implementation 'nl.esciencecenter.xenon.adaptors:xenon-adaptors-cloud:$XENON_ADAPTORS_CLOUD_VERSION'\"\ntest $actual $expected || exit 1\n\necho \"checking readthedocs/tutorial.rst\"\n\nactual=$(head --lines=+38 readthedocs/tutorial.rst | tail --lines=1)\nexpected=\" Xenon CLI v$XENON_CLI_VERSION, Xenon library v$XENON_VERSION, Xenon cloud library v$XENON_ADAPTORS_CLOUD_VERSION\"\ntest $actual $expected || exit 1\n\nactual=$(head --lines=+640 readthedocs/tutorial.rst | tail --lines=1)\nexpected=\"__ http://xenon-middleware.github.io/xenon/versions/$XENON_VERSION/javadoc\"\ntest $actual $expected || exit 1\n\necho \"checking vm-prep/README.md\"\n\nactual=$(head --lines=+126 vm-prep/README.md | tail --lines=1)\nexpected=\" wget https://github.com/xenon-middleware/xenon-cli/releases/download/v$XENON_CLI_VERSION/xenon-cli-shadow-$XENON_CLI_VERSION.tar\"\ntest $actual $expected || exit 1\n\nactual=$(head --lines=+127 vm-prep/README.md | tail --lines=1)\nexpected=\" tar -xvf xenon-cli-shadow-$XENON_CLI_VERSION.tar\"\ntest $actual $expected || exit 1\n\nactual=$(head --lines=+129 vm-prep/README.md | tail --lines=1)\nexpected=\" mv xenon-cli-shadow-$XENON_CLI_VERSION ~/.local/bin/xenon/\"\ntest $actual $expected || exit 1\n\nactual=$(head --lines=+133 vm-prep/README.md | tail --lines=1)\nexpected=\" echo 'PATH=\\$PATH:~/.local/bin/xenon/xenon-cli-shadow-$XENON_CLI_VERSION/bin' >> ~/.bashrc\"\ntest $actual $expected || exit 1\n\necho 'all passed'\nexit 0\n" }, { "alpha_fraction": 0.8245614171028137, "alphanum_fraction": 0.8245614171028137, "avg_line_length": 57, "blob_id": "dc16948dbde52ac2fed0c36a570cc584944033fd", "content_id": "2b54f9dcd835d9c1a8eaf47c67e8b3321eeb5db5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 57, "license_type": "permissive", "max_line_length": 57, "num_lines": 1, "path": "/readthedocs/code-tabs/bash/DirectoryListingShowHidden.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "xenon filesystem file list --hidden /home/travis/fixtures" }, { "alpha_fraction": 0.6810747385025024, "alphanum_fraction": 0.6962617039680481, "avg_line_length": 24.939393997192383, "blob_id": "e0943df01b5534a5253dde7077f74f360f46bb28", "content_id": "e7a3c36b304e519fb23bec4fff6e3d0a8b4ac306", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 856, "license_type": "permissive", "max_line_length": 94, "num_lines": 33, "path": "/readthedocs/code-tabs/java/build.gradle", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "plugins {\n id 'base'\n id 'java'\n id 'eclipse'\n}\n\nrepositories {\n jcenter()\n}\n\ndependencies {\n implementation 'nl.esciencecenter.xenon:xenon:3.0.4'\n implementation 'nl.esciencecenter.xenon.adaptors:xenon-adaptors-cloud:3.0.2'\n testCompile 'junit:junit:4.12'\n testCompile 'org.testcontainers:testcontainers:1.11.3'\n}\n\neclipse {\n classpath {\n\n // also download sources and Javadoc for dependencies jars:\n downloadSources = true\n downloadJavadoc = true\n }\n}\n\ntask run(type: JavaExec) {\n description 'Run main class found in `main` project property'\n group 'Application tasks'\n classpath = sourceSets.main.runtimeClasspath\n main = project.findProperty('main') ?: 'nl.esciencecenter.xenon.tutorial.DirectoryListing'\n systemProperties.put('loglevel', project.findProperty('loglevel') ?: 'WARN')\n}\n" }, { "alpha_fraction": 0.7636363506317139, "alphanum_fraction": 0.7636363506317139, "avg_line_length": 23.33333396911621, "blob_id": "bd0603eff9972eb56d8239ae7b87786a8b08873c", "content_id": "b18cf04988f1c3aa392032b459e178a531199628", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "permissive", "max_line_length": 68, "num_lines": 9, "path": "/readthedocs/code-tabs/python/tests/test_copy_file_local_to_local_absolute_paths.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pytest\n\n\nfrom pyxenon_snippets import copy_file_local_to_local_absolute_paths\n\n\ndef test_copy_file_local_to_local_absolute_paths():\n copy_file_local_to_local_absolute_paths.run_example()\n\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 60, "blob_id": "ccc417411f461a9f02bd7b0496dad9bd51d23946", "content_id": "8b0471780079c8061d664161c30345ff92e4a6d5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 60, "license_type": "permissive", "max_line_length": 60, "num_lines": 1, "path": "/readthedocs/code-tabs/bash/DirectoryListingRecursive.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "xenon filesystem file list --recursive /home/travis/fixtures" }, { "alpha_fraction": 0.7400000095367432, "alphanum_fraction": 0.7400000095367432, "avg_line_length": 17.625, "blob_id": "b7d3e634105b847e0e8ef2e009710fff7623065b", "content_id": "01b25a0fc2a800eda7c17a20cd7eb0cf8d118e9e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "permissive", "max_line_length": 45, "num_lines": 8, "path": "/readthedocs/code-tabs/python/tests/test_all_together_now.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pytest\n\nfrom pyxenon_snippets import all_together_now\n\n\ndef test_all_together_now():\n all_together_now.run_example()\n\n" }, { "alpha_fraction": 0.6901639103889465, "alphanum_fraction": 0.6954917907714844, "avg_line_length": 39.66666793823242, "blob_id": "9f2f878ad089ec931a4ed74f83d5216db04971e5", "content_id": "361b76f1df1782724cef1b1a520171d2dcec39ed", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2440, "license_type": "permissive", "max_line_length": 103, "num_lines": 60, "path": "/readthedocs/code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/DownloadFileSftpToLocalAbsolutePaths.java", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "package nl.esciencecenter.xenon.tutorial;\n\nimport nl.esciencecenter.xenon.XenonException;\nimport nl.esciencecenter.xenon.credentials.PasswordCredential;\nimport nl.esciencecenter.xenon.filesystems.CopyMode;\nimport nl.esciencecenter.xenon.filesystems.CopyStatus;\nimport nl.esciencecenter.xenon.filesystems.FileSystem;\nimport nl.esciencecenter.xenon.filesystems.Path;\n\npublic class DownloadFileSftpToLocalAbsolutePaths {\n\n public static void main(String[] args) throws XenonException {\n\n String host = \"localhost\";\n String port = \"10022\";\n runExample(host, port);\n }\n\n public static void runExample(String host, String port) throws XenonException {\n\n\n // use the sftp file system adaptor to create a file system representation; the remote\n // filesystem requires credentials to log in, so we'll have to create those too.\n String adaptorRemote = \"sftp\";\n String location = host + \":\" + port;\n String username = \"xenon\";\n char[] password = \"javagat\".toCharArray();\n PasswordCredential credential = new PasswordCredential(username, password);\n FileSystem filesystemRemote = FileSystem.create(adaptorRemote, location, credential);\n\n // define which file to download\n Path fileRemote = new Path(\"/home/xenon/sleep.stdout.txt\");\n\n // use the local file system adaptor to create a file system representation\n String adaptorLocal = \"file\";\n FileSystem filesystemLocal = FileSystem.create(adaptorLocal);\n\n // define what file to download to\n Path fileLocal = new Path(\"/home/travis/sleep.stdout.txt\");\n\n // create the destination file only if the destination path doesn't exist yet\n CopyMode mode = CopyMode.CREATE;\n\n // no need to recurse, we're just downloading a file\n boolean recursive = false;\n\n // perform the copy/download and wait 1000 ms for the successful or otherwise\n // completion of the operation\n String copyId = filesystemRemote.copy(fileRemote, filesystemLocal, fileLocal, mode, recursive);\n long timeoutMilliSecs = 1000;\n CopyStatus copyStatus = filesystemRemote.waitUntilDone(copyId, timeoutMilliSecs);\n\n // print any exceptions\n if (copyStatus.getException() != null) {\n System.out.println(copyStatus.getException().getMessage());\n } else {\n System.out.println(\"Done\");\n }\n }\n}\n" }, { "alpha_fraction": 0.765625, "alphanum_fraction": 0.765625, "avg_line_length": 22.875, "blob_id": "9d9ce4a8e3c520f73f418297b880537ab312d476", "content_id": "5986ab42d0fea578ff26dd12eede16c65dc6e620", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 192, "license_type": "permissive", "max_line_length": 59, "num_lines": 8, "path": "/readthedocs/code-tabs/python/tests/test_slurm_queues_getter_with_props.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pytest\n\nfrom pyxenon_snippets import slurm_queues_getter_with_props\n\n\ndef test_slurm_queues_getter_with_props():\n slurm_queues_getter_with_props.run_example()\n\n" }, { "alpha_fraction": 0.6478873491287231, "alphanum_fraction": 0.6596243977546692, "avg_line_length": 30.55555534362793, "blob_id": "7afab30af207cb513f6eadb8b5eec9aa69930414", "content_id": "b0fdf31403dc57ed7100020c613c6474a520747a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 852, "license_type": "permissive", "max_line_length": 105, "num_lines": 27, "path": "/readthedocs/code-tabs/java/src/test/java/nl/esciencecenter/xenon/tutorial/AllTogetherNowWrongTest.java", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "package nl.esciencecenter.xenon.tutorial;\n\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.testcontainers.containers.FixedHostPortGenericContainer;\nimport org.testcontainers.containers.wait.strategy.Wait;\n\n\npublic class AllTogetherNowWrongTest {\n\n private final String image = \"xenonmiddleware/slurm:17\";\n private final String host = \"localhost\";\n private final String port = \"10022\";\n\n @Rule\n public FixedHostPortGenericContainer<?> slurm = new FixedHostPortGenericContainer<>(image)\n .withFixedExposedPort(Integer.parseInt(port), 22)\n .waitingFor(Wait.forHealthcheck());\n\n\n @Test(expected = Test.None.class)\n public void test1() throws Exception {\n AllTogetherNowWrong.runExample(host, port);\n }\n\n\n}\n" }, { "alpha_fraction": 0.4571428596973419, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 15.5, "blob_id": "a9121b17f914fe6756e727ecaab6ad8bfa02c7e8", "content_id": "9d8a315ff9a1ce55769e3b6998cdb145deb808ff", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 35, "license_type": "permissive", "max_line_length": 18, "num_lines": 2, "path": "/readthedocs/requirements.txt", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "Sphinx>=2.1.*\nsphinx-tabs>=1.1.*\n\n\n" }, { "alpha_fraction": 0.7469512224197388, "alphanum_fraction": 0.7591463327407837, "avg_line_length": 22.35714340209961, "blob_id": "eea98f67b11ddb3d3872a899b4516d98c28f124e", "content_id": "62d16d69b7358a5381599a8ceb779a70a6fadddd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 328, "license_type": "permissive", "max_line_length": 59, "num_lines": 14, "path": "/readthedocs/README.md", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "```bash\n# install pip3\nsudo apt install python3\nsudo apt install python3-pip\n\n# install the requirements for building the Sphinx tutorial\npip3 install --user -r requirements.txt\n\n# build the HTML documentation from sources\nsphinx-build -b html . build/\n\n# use a browser to look at the result, e.g.\nfirefox build/index.html\n```\n\n" }, { "alpha_fraction": 0.7542856931686401, "alphanum_fraction": 0.7828571200370789, "avg_line_length": 86.5, "blob_id": "940d0e770c9edcc3b18daecbb8b7d2a7887cf8b9", "content_id": "c52f30debcab94c26d0389e5282afe9c5b6742b8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 175, "license_type": "permissive", "max_line_length": 98, "num_lines": 2, "path": "/readthedocs/code-tabs/bash/SlurmJobListGetter.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat list\n# should have the job identifier in it that was printed on the command line\n" }, { "alpha_fraction": 0.740963876247406, "alphanum_fraction": 0.740963876247406, "avg_line_length": 17.33333396911621, "blob_id": "324a67593964afccaa0adb0f444e996c99ece6ef", "content_id": "76495f4204aa9e00a7b6216998f4318b37da4bd0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "permissive", "max_line_length": 50, "num_lines": 9, "path": "/readthedocs/code-tabs/python/tests/test_slurm_job_list_getter.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pytest\n\n\nfrom pyxenon_snippets import slurm_job_list_getter\n\n\ndef test_slurm_job_list_getter():\n slurm_job_list_getter.run_example()\n\n" }, { "alpha_fraction": 0.7665198445320129, "alphanum_fraction": 0.7797356843948364, "avg_line_length": 20.571428298950195, "blob_id": "a90a80304a010fdf99c68bab21a8da07e14a8fd0", "content_id": "28f143cd7e0561d6944d394cf674f6fd5f9a9774", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 454, "license_type": "permissive", "max_line_length": 55, "num_lines": 21, "path": "/readthedocs/code-tabs/python/README.md", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "\n```\n# install virtualenv from ubuntu repositories\nsudo apt install virtualenv\n\n# create a new virtual environment\nvirtualenv -p /usr/bin/python3.6 venv36\n\n# activate the new environment\nsource venv36/bin/activate\n\n# install the requirements and test requirements\npip install -r requirements.txt\npip install -r requirements-dev.txt\n\n# check if xenon-grpc can be found\nwhich xenon-grpc\n\n# run the tests (some may fail due to missing fixtures)\npytest\n\n```\n" }, { "alpha_fraction": 0.7680000066757202, "alphanum_fraction": 0.7680000066757202, "avg_line_length": 61.5, "blob_id": "4439b1be2c2f7a1317ea2e2defb5c95291fd4753", "content_id": "8eabb5fc798419dd8fa2a5e855f0858b557dfbef", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 125, "license_type": "permissive", "max_line_length": 89, "num_lines": 2, "path": "/readthedocs/code-tabs/bash/FTPDirectoryListing.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "# list the files on the ftp server\nxenon filesystem ftp --location test.rebex.net --username demo --password password list /\n" }, { "alpha_fraction": 0.7736842036247253, "alphanum_fraction": 0.7736842036247253, "avg_line_length": 20, "blob_id": "24e78e02d2d4c9a1174111d81a0b4c375ddfecb2", "content_id": "5582a9b9d89e91e3c81c7ecbadc752742196ebb2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "permissive", "max_line_length": 58, "num_lines": 9, "path": "/readthedocs/code-tabs/python/tests/test_directory_listing_show_hidden.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pytest\n\n\nfrom pyxenon_snippets import directory_listing_show_hidden\n\n\ndef test_directory_listing_show_hidden():\n directory_listing_show_hidden.run_example()\n\n" }, { "alpha_fraction": 0.6263048052787781, "alphanum_fraction": 0.6297842860221863, "avg_line_length": 33.975608825683594, "blob_id": "6d95413132b666396a139b179f10d58ee85a5513", "content_id": "abb469ad863db8bde8b92df4c2a4b0913379b0f2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1437, "license_type": "permissive", "max_line_length": 85, "num_lines": 41, "path": "/readthedocs/code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/SlurmQueuesGetter.java", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "package nl.esciencecenter.xenon.tutorial;\n\nimport nl.esciencecenter.xenon.XenonException;\nimport nl.esciencecenter.xenon.credentials.Credential;\nimport nl.esciencecenter.xenon.credentials.PasswordCredential;\nimport nl.esciencecenter.xenon.schedulers.Scheduler;\n\npublic class SlurmQueuesGetter {\n\n\n public static void main(String[] args) throws XenonException {\n\n String host = \"localhost\";\n String port = \"10022\";\n runExample(host, port);\n }\n\n public static void runExample(String host, String port) throws XenonException {\n\n String adaptor = \"slurm\";\n String location = \"ssh://\" + host + \":\" + port;\n\n // make the password credential for user 'xenon'\n String username = \"xenon\";\n char[] password = \"javagat\".toCharArray();\n Credential credential = new PasswordCredential(username, password);\n\n // create the SLURM scheduler\n try (Scheduler scheduler = Scheduler.create(adaptor, location, credential)) {\n // ask SLURM for its queues\n System.out.println(\"Available queues (starred queue is default):\");\n for (String queueName : scheduler.getQueueNames()) {\n if (queueName.equals(scheduler.getDefaultQueueName())) {\n System.out.println(queueName + \"*\");\n } else {\n System.out.println(queueName);\n }\n }\n }\n }\n}\n\n\n\n" }, { "alpha_fraction": 0.6442577242851257, "alphanum_fraction": 0.6442577242851257, "avg_line_length": 16.850000381469727, "blob_id": "5fc3c51775b604332ab70c37fe8316cb07d8154e", "content_id": "a478a3811a093891c9aaa41ed16a61257e4caa09", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "permissive", "max_line_length": 52, "num_lines": 20, "path": "/readthedocs/code-tabs/python/pyxenon_snippets/directory_listing_show_hidden.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "import xenon\nfrom xenon import Path, FileSystem\n\n\ndef run_example():\n xenon.init()\n\n filesystem = FileSystem.create(adaptor='file')\n path = Path(\"/home/travis/fixtures\")\n\n listing = filesystem.list(path, recursive=False)\n\n for entry in listing:\n print(entry.path)\n\n filesystem.close()\n\n\nif __name__ == '__main__':\n run_example()\n" }, { "alpha_fraction": 0.608016312122345, "alphanum_fraction": 0.6120923757553101, "avg_line_length": 33.23255920410156, "blob_id": "89167247b9e43179c0654ddf888f34fd205fee22", "content_id": "f2459b76063e5aeff1e27be67742534dc6e0b274", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1472, "license_type": "permissive", "max_line_length": 106, "num_lines": 43, "path": "/readthedocs/code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/SlurmJobListGetter.java", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "package nl.esciencecenter.xenon.tutorial;\n\nimport nl.esciencecenter.xenon.XenonException;\nimport nl.esciencecenter.xenon.credentials.PasswordCredential;\nimport nl.esciencecenter.xenon.schedulers.Scheduler;\n\npublic class SlurmJobListGetter {\n\n public static void main(String[] args) throws XenonException {\n\n String host = \"localhost\";\n String port = \"10022\";\n runExample(host, port);\n }\n\n public static void runExample(String host, String port) throws XenonException {\n\n\n String adaptor = \"slurm\";\n String location = \"ssh://\" + host + \":\" + port;\n\n // make the password credential for user 'xenon'\n String username = \"xenon\";\n char[] password = \"javagat\".toCharArray();\n PasswordCredential credential = new PasswordCredential(username, password);\n\n // create the SLURM scheduler\n Scheduler scheduler = Scheduler.create(adaptor, location, credential);\n\n // ask SLURM for its queues and list the jobs in each\n for (String queueName : scheduler.getQueueNames()) {\n System.out.println(\"List of jobs in queue '\" + queueName + \"' for SLURM at \" + location + \"\");\n String[] jobs = scheduler.getJobs(queueName);\n if (jobs.length == 0) {\n System.out.println(\"(No jobs)\");\n } else {\n for (String job : jobs) {\n System.out.println(job);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.626423716545105, "alphanum_fraction": 0.6628701686859131, "avg_line_length": 17.25, "blob_id": "d71539ef0ca350848659296a93ab2d7e7d20da1c", "content_id": "f114466085083bc771bb541647ba76f51d525db1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 439, "license_type": "permissive", "max_line_length": 76, "num_lines": 24, "path": "/readthedocs/index.rst", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": ".. xenon3 tutorial master file, created by\n sphinx-quickstart on Mon Aug 7 15:57:48 2017.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\n|\n|\n\n.. image:: _static/xenon-logo.png\n :scale: 50 %\n :alt: xenon-logo\n :align: center\n\n|\n|\n|\n\n.. toctree::\n\n.. contents:: xenon3 tutorial -- Table of Contents\n :backlinks: none\n :depth: 1\n\n.. include:: tutorial.rst\n\n" }, { "alpha_fraction": 0.8289473652839661, "alphanum_fraction": 0.8289473652839661, "avg_line_length": 76, "blob_id": "e91943e8fcf327a92324cb958e3168ba5dd197d8", "content_id": "929ea192654b5df77ba1c3ccee464c0da9d608f7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 76, "license_type": "permissive", "max_line_length": 76, "num_lines": 1, "path": "/readthedocs/code-tabs/bash/CopyFileLocalToLocalAbsolutePaths.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "xenon filesystem file copy /home/travis/thefile.txt /home/travis/thefile.bak" }, { "alpha_fraction": 0.7323750853538513, "alphanum_fraction": 0.7501711249351501, "avg_line_length": 111.38461303710938, "blob_id": "dc57675277f9f480814765f187d528f730300cd4", "content_id": "0639cf5f165e8d6c8ac96718a89be5b936fe6b04", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1461, "license_type": "permissive", "max_line_length": 287, "num_lines": 13, "path": "/README.md", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "# xenon-tutorial\n\n[![Documentation Status](https://readthedocs.org/projects/xenon-tutorial/badge/?version=latest)](https://xenon-tutorial.readthedocs.io/en/latest/?badge=latest) \n[![Build Status](https://travis-ci.org/xenon-middleware/xenon-tutorial.svg?branch=master)](https://travis-ci.org/xenon-middleware/xenon-tutorial)\n[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.1064653.svg)](https://doi.org/10.5281/zenodo.1064653)\n\nSource files for a [``xenon`` tutorial on ReadTheDocs](http://xenon-tutorial.readthedocs.io).\n\n- [``/readthedocs``](/readthedocs) contains all the source files for the tutorial text. It also contains a number of subdirectories with code snippets:\n - [``code-tabs/bash``](/readthedocs/code-tabs/bash) contains the Bash snippets using [``xenon-cli``](https://github.com/xenon-middleware/xenon-cli).\n - [``code-tabs/java``](/readthedocs/code-tabs/java) contains the Java snippets that use the [``xenon``](https://github.com/xenon-middleware/xenon) library directly. This directory can be run as a self-contained Java project.\n - [``code-tabs/python``](/readthedocs/code-tabs/python) contains the Python snippets that use [``pyxenon``](https://github.com/xenon-middleware/pyxenon) and [``xenon-grpc``](https://github.com/xenon-middleware/xenon-grpc). This directory can be run as a self-contained Python project.\n- [``/vm-prep``](/vm-prep) contains instructions for setting up the Virtual Machine, as used during the tutorial.\n" }, { "alpha_fraction": 0.6497151255607605, "alphanum_fraction": 0.6520363092422485, "avg_line_length": 35.4538459777832, "blob_id": "8030e29cce79ecd7a7a2156d2c75517d0c2acbe8", "content_id": "541151262452d5032e945fed5438cd546c3d20a7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4739, "license_type": "permissive", "max_line_length": 111, "num_lines": 130, "path": "/readthedocs/code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/AllTogetherNow.java", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "package nl.esciencecenter.xenon.tutorial;\n\nimport nl.esciencecenter.xenon.XenonException;\nimport nl.esciencecenter.xenon.credentials.PasswordCredential;\nimport nl.esciencecenter.xenon.filesystems.CopyMode;\nimport nl.esciencecenter.xenon.filesystems.CopyStatus;\nimport nl.esciencecenter.xenon.filesystems.FileSystem;\nimport nl.esciencecenter.xenon.filesystems.Path;\nimport nl.esciencecenter.xenon.schedulers.JobDescription;\nimport nl.esciencecenter.xenon.schedulers.JobStatus;\nimport nl.esciencecenter.xenon.schedulers.Scheduler;\n\npublic class AllTogetherNow {\n\n public static void main(String[] args) throws XenonException {\n\n String host = \"localhost\";\n String port = \"10022\";\n\n runExample(host, port);\n }\n\n public static void runExample(String host, String port) throws XenonException {\n\n /*\n * step 1: upload input file(s)\n */\n\n // create the local filesystem representation\n String fileAdaptorLocal = \"file\";\n FileSystem filesystemLocal = FileSystem.create(fileAdaptorLocal);\n\n // the remote system requires credentials, create them here:\n String username = \"xenon\";\n char[] password = \"javagat\".toCharArray();\n PasswordCredential credential = new PasswordCredential(username, password);\n\n // create the remote filesystem representation and specify the executable's path\n String fileAdaptorRemote = \"sftp\";\n String filesystemRemoteLocation = host + \":\" + port;\n FileSystem filesystemRemote = FileSystem.create(fileAdaptorRemote,\n filesystemRemoteLocation, credential);\n\n // when waiting for jobs or copy operations to complete, wait indefinitely\n final long WAIT_INDEFINITELY = 0;\n\n {\n // specify the behavior in case the target path exists already\n CopyMode copyMode = CopyMode.REPLACE;\n\n // no recursion, we're just copying a file\n boolean recursive = false;\n\n // specify the path of the script file on the local and on the remote\n Path fileLocal = new Path(\"/home/travis/sleep.sh\");\n Path fileRemote = new Path(\"/home/xenon/sleep.sh\");\n\n // start the copy operation\n String copyId = filesystemLocal.copy(fileLocal, filesystemRemote, fileRemote, copyMode, recursive);\n\n // wait for the copy operation to complete (successfully or otherwise)\n CopyStatus status = filesystemLocal.waitUntilDone(copyId, WAIT_INDEFINITELY);\n\n // rethrow the Exception if we got one\n if (status.hasException()) {\n throw status.getException();\n }\n\n }\n\n\n\n /*\n * step 2: submit job and capture its job identifier\n */\n\n // create the SLURM scheduler representation\n String schedulerAdaptor = \"slurm\";\n String schedulerLocation = \"ssh://\" + host + \":\" + port;\n Scheduler scheduler = Scheduler.create(schedulerAdaptor, schedulerLocation, credential);\n\n // compose the job description:\n JobDescription jobDescription = new JobDescription();\n jobDescription.setExecutable(\"bash\");\n jobDescription.setArguments(\"sleep.sh\", \"60\");\n jobDescription.setStdout(\"sleep.stdout.txt\");\n\n String jobId = scheduler.submitBatchJob(jobDescription);\n\n // wait for the job to finish before attempting to copy its output file(s)\n JobStatus jobStatus = scheduler.waitUntilDone(jobId, WAIT_INDEFINITELY);\n\n // rethrow the Exception if we got one\n if (jobStatus.hasException()) {\n throw jobStatus.getException();\n }\n\n\n /*\n * step 3: download generated output file(s)\n */\n\n {\n // specify the behavior in case the target path exists already\n CopyMode copyMode = CopyMode.REPLACE;\n\n // no recursion, we're just copying a file\n boolean recursive = false;\n\n // specify the path of the stdout file on the remote and on the local machine\n Path fileRemote = new Path(\"/home/xenon/sleep.stdout.txt\");\n Path fileLocal = new Path(\"/home/travis/sleep.stdout.txt\");\n\n // start the copy operation\n String copyId = filesystemRemote.copy(fileRemote, filesystemLocal, fileLocal, copyMode, recursive);\n\n // wait for the copy operation to complete (successfully or otherwise)\n CopyStatus status = filesystemRemote.waitUntilDone(copyId, WAIT_INDEFINITELY);\n\n // rethrow the Exception if we got one\n if (status.hasException()) {\n throw status.getException();\n }\n\n }\n\n System.out.println(\"Done.\");\n\n }\n}\n" }, { "alpha_fraction": 0.7668161392211914, "alphanum_fraction": 0.7668161392211914, "avg_line_length": 23.66666603088379, "blob_id": "cdadc80e4594194bf3b4489ea5241e5ba27bc99b", "content_id": "e88040c50019e4b69cc226cc0ab1b2517deaa663", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "permissive", "max_line_length": 69, "num_lines": 9, "path": "/readthedocs/code-tabs/python/tests/test_upload_file_local_to_sftp_absolute_paths.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pytest\n\n\nfrom pyxenon_snippets import upload_file_local_to_sftp_absolute_paths\n\n\ndef test_upload_file_local_to_sftp_absolute_paths():\n upload_file_local_to_sftp_absolute_paths.run_example()\n\n" }, { "alpha_fraction": 0.5583941340446472, "alphanum_fraction": 0.5620437860488892, "avg_line_length": 16.125, "blob_id": "8b199e5e8ccd1bd5924c48ff72317295a0b8557b", "content_id": "98c4aab4e0df315d660970e68cf9a561b16f37fd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 274, "license_type": "permissive", "max_line_length": 37, "num_lines": 16, "path": "/vm-prep/print-ssh-permissions.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\ncheck_location () {\n stat -c \"%a %n\" $1\n}\n\nlocations=\"$HOME\n $HOME/.ssh\n $HOME/.ssh/authorized_keys\n $HOME/.ssh/config\n $HOME/.ssh/known_hosts\"\n\nfor location in $locations ; \ndo\n check_location $location\ndone\n" }, { "alpha_fraction": 0.7251461744308472, "alphanum_fraction": 0.7602339386940002, "avg_line_length": 56, "blob_id": "a6b286bc1ddfbde9f260df7b73e991944235ef17", "content_id": "b54c0e281f514e210d81907a2fce83ffb5ae7721", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 171, "license_type": "permissive", "max_line_length": 89, "num_lines": 3, "path": "/readthedocs/code-tabs/bash/UploadFileLocalToSftpAbsolutePaths.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "# step 1: upload input file(s)\nxenon filesystem sftp --location localhost:10022 --username xenon --password javagat \\\nupload /home/travis/sleep.sh /home/xenon/sleep.sh\n" }, { "alpha_fraction": 0.6202531456947327, "alphanum_fraction": 0.6329113841056824, "avg_line_length": 18.75, "blob_id": "f7dbc31a972795bd8891b1f089ea8beb006e237a", "content_id": "9a109e2aa319e6d198c5f612b23dc50a645bf674", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 79, "license_type": "permissive", "max_line_length": 26, "num_lines": 4, "path": "/readthedocs/code-tabs/bash/sleep.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\necho `date`': went to bed'\nsleep $1\necho `date`': woke up'\n" }, { "alpha_fraction": 0.5624178647994995, "alphanum_fraction": 0.5689881443977356, "avg_line_length": 25.241378784179688, "blob_id": "2a632b668d6824ed026b77db3bbb4b3543bc51ae", "content_id": "f4c2bb7e0a07c4fef080864f25ceb6ff51db8ac6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 761, "license_type": "permissive", "max_line_length": 66, "num_lines": 29, "path": "/readthedocs/code-tabs/python/pyxenon_snippets/slurm_queues_getter.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "import xenon\nfrom xenon import Scheduler, PasswordCredential\n\n\ndef run_example():\n\n xenon.init()\n\n credential = PasswordCredential(username='xenon',\n password='javagat')\n\n scheduler = Scheduler.create(adaptor='slurm',\n location='ssh://localhost:10022',\n password_credential=credential)\n\n default_queue = scheduler.get_default_queue_name()\n\n print(\"Available queues (starred queue is default):\")\n for queue_name in scheduler.get_queue_names():\n if queue_name == default_queue:\n print(\"{}*\".format(queue_name))\n else:\n print(queue_name)\n\n scheduler.close()\n\n\nif __name__ == '__main__':\n run_example()\n" }, { "alpha_fraction": 0.5396096706390381, "alphanum_fraction": 0.545350193977356, "avg_line_length": 26.21875, "blob_id": "e198f6ee589bcc415ac7127952ca8c3a3ed1bb48", "content_id": "eb79cfdd9c529a384e7a13de7d1a9d36fd03cde3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 871, "license_type": "permissive", "max_line_length": 74, "num_lines": 32, "path": "/readthedocs/code-tabs/python/pyxenon_snippets/slurm_job_list_getter.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "import xenon\nfrom xenon import PasswordCredential, Scheduler\n\n\ndef run_example():\n\n xenon.init()\n\n credential = PasswordCredential(username='xenon',\n password='javagat')\n\n location = 'ssh://localhost:10022'\n\n scheduler = Scheduler.create(adaptor='slurm',\n location=location,\n password_credential=credential)\n\n for queue_name in scheduler.get_queue_names():\n print(\"List of jobs in queue {queue_name} for SLURM at {location}\"\n .format(queue_name=queue_name, location=location))\n jobs = scheduler.get_jobs([queue_name])\n if not jobs:\n print(\"(No jobs)\")\n else:\n for job in jobs:\n print(\" {}\".format(job))\n\n scheduler.close()\n\n\nif __name__ == '__main__':\n run_example()\n" }, { "alpha_fraction": 0.8541666865348816, "alphanum_fraction": 0.8541666865348816, "avg_line_length": 48, "blob_id": "d9c0404441d79b4f805bdd505b5fc8635821f867", "content_id": "465a2630c477396500cadb5bba83548b0d66c1ea", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 48, "license_type": "permissive", "max_line_length": 48, "num_lines": 1, "path": "/readthedocs/code-tabs/bash/DirectoryListing.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "xenon filesystem file list /home/travis/fixtures" }, { "alpha_fraction": 0.7729257345199585, "alphanum_fraction": 0.7729257345199585, "avg_line_length": 24.33333396911621, "blob_id": "a215cffa8a8181d779b495152d903bde0852b649", "content_id": "2bd5cd756988d876941a6aa70e6835ddebb7268f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 229, "license_type": "permissive", "max_line_length": 71, "num_lines": 9, "path": "/readthedocs/code-tabs/python/tests/test_download_file_sftp_to_local_absolute_paths.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pytest\n\n\nfrom pyxenon_snippets import download_file_sftp_to_local_absolute_paths\n\n\ndef test_download_file_sftp_to_local_absolute_paths():\n download_file_sftp_to_local_absolute_paths.run_example()\n\n" }, { "alpha_fraction": 0.6469805836677551, "alphanum_fraction": 0.6565576195716858, "avg_line_length": 30.58823585510254, "blob_id": "1049c6e1ab6f79f0c798a17f9e36a405887be4fa", "content_id": "22b7503e6985675c7c726407d384ff9f6fc541b7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3759, "license_type": "permissive", "max_line_length": 89, "num_lines": 119, "path": "/readthedocs/code-tabs/python/pyxenon_snippets/all_together_now.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "import xenon\nfrom xenon import (FileSystem, PasswordCredential, CopyRequest,\n Path, CopyStatus, Scheduler, JobDescription, JobStatus)\n\n\ndef upload(local_fs=None, remote_fs=None):\n\n # define which file to upload\n local_file = Path('/home/travis/sleep.sh')\n remote_file = Path('/home/xenon/sleep.sh')\n\n # overwrite the destination file if the destination path exists\n mode = CopyRequest.REPLACE\n\n # no need to recurse, we're just uploading a file\n recursive = False\n\n # perform the copy/upload and wait 1000 ms for the successful or\n # otherwise completion of the operation\n copy_id = local_fs.copy(local_file, remote_fs, remote_file,\n mode=mode, recursive=recursive)\n\n copy_status = local_fs.wait_until_done(copy_id, timeout=5000)\n\n assert copy_status.done\n\n assert copy_status.error_type == CopyStatus.ErrorType.NONE, copy_status.error_message\n\n print('Done uploading.')\n\n\ndef submit(credential=None):\n\n description = JobDescription(executable='bash',\n arguments=['sleep.sh', '60'],\n stdout='sleep.stdout.txt')\n\n scheduler = Scheduler.create(adaptor='slurm',\n location='ssh://localhost:10022',\n password_credential=credential)\n\n job_id = scheduler.submit_batch_job(description)\n\n print('Done submitting.')\n\n # wait for the job to finish before attempting to copy its output file(s)\n job_status = scheduler.wait_until_done(job_id, 10*60*1000)\n\n assert job_status.done\n\n # rethrow the Exception if we got one\n assert job_status.error_type == JobStatus.ErrorType.NONE, job_status.error_message\n\n print('Done executing on the remote.')\n\n # make sure to synchronize the remote filesystem\n job_id = scheduler.submit_batch_job(JobDescription(executable='sync'))\n scheduler.wait_until_done(job_id)\n\n scheduler.close()\n\n\ndef download(remote_fs=None, local_fs=None):\n\n # define which file to download\n remote_file = Path('/home/xenon/sleep.stdout.txt')\n local_file = Path('/home/travis/sleep.stdout.txt')\n\n # create the destination file; overwrite local file\n mode = CopyRequest.REPLACE\n\n # no need to recurse, we're just uploading a file\n recursive = False\n\n # perform the copy/download and wait 1000 ms for the successful or\n # otherwise completion of the operation\n copy_id = remote_fs.copy(remote_file, local_fs, local_file,\n mode=mode, recursive=recursive)\n\n copy_status = remote_fs.wait_until_done(copy_id, timeout=5000)\n\n assert copy_status.done\n\n # rethrow the Exception if we got one\n assert copy_status.error_type == CopyStatus.ErrorType.NONE, copy_status.error_message\n\n print('Done downloading.')\n\n\ndef run_example():\n\n xenon.init()\n\n # use the local file system adaptor to create a file system representation\n local_fs = FileSystem.create(adaptor='file')\n\n # use the sftp file system adaptor to create another file system representation;\n # the remote filesystem requires credentials to log in, so we'll have to\n # create those too.\n credential = PasswordCredential(username='xenon',\n password='javagat')\n\n remote_fs = FileSystem.create(adaptor='sftp',\n location='localhost:10022',\n password_credential=credential)\n\n upload(local_fs=local_fs, remote_fs=remote_fs)\n submit(credential=credential)\n download(remote_fs=remote_fs, local_fs=local_fs)\n\n # remember to close the FileSystem instances\n remote_fs.close()\n local_fs.close()\n\n print('Done')\n\n\nif __name__ == '__main__':\n run_example()\n" }, { "alpha_fraction": 0.7145612239837646, "alphanum_fraction": 0.7328833341598511, "avg_line_length": 37.407405853271484, "blob_id": "3c57459feb37d2a578857a36e66600db3537bc17", "content_id": "b21b43e9bf64a922c1b682ce65cabefc353a16e4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1037, "license_type": "permissive", "max_line_length": 79, "num_lines": 27, "path": "/vm-prep/make-fixtures.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nif [ $CI ]; then\n echo \"Making fixtures in /home/travis\"\n FIXTURE_PREFIX=''\nelse\n echo \"Making fixtures in /home/<user>/tmp/home/travis\"\n FIXTURE_PREFIX=$HOME/tmp\nfi\n \n\n# files and directories for making directory listings\nmkdir -p $FIXTURE_PREFIX/home/travis/fixtures/dir1\nmkdir -p $FIXTURE_PREFIX/home/travis/fixtures/.dir2\necho 'dir1/file1.txt' > $FIXTURE_PREFIX/home/travis/fixtures/dir1/file1.txt\necho 'dir1/.file2.txt' > $FIXTURE_PREFIX/home/travis/fixtures/dir1/.file2.txt\necho '.dir2/file3.txt' > $FIXTURE_PREFIX/home/travis/fixtures/.dir2/file3.txt\necho '.dir2/.file4.txt' > $FIXTURE_PREFIX/home/travis/fixtures/.dir2/.file4.txt\n\n# file for copying locally\necho 'some content' > $FIXTURE_PREFIX/home/travis/thefile.txt\n\n# sleep script\necho '#!/usr/bin/env bash' > $FIXTURE_PREFIX/home/travis/sleep.sh\necho 'echo `date`: went to bed' >> $FIXTURE_PREFIX/home/travis/sleep.sh\necho 'sleep $1' >> $FIXTURE_PREFIX/home/travis/sleep.sh\necho 'echo `date`: woke up' >> $FIXTURE_PREFIX/home/travis/sleep.sh\n" }, { "alpha_fraction": 0.698051929473877, "alphanum_fraction": 0.7067099809646606, "avg_line_length": 28.80645179748535, "blob_id": "ed4d2d96419fd6cf3220f1fd091da58ffedabbd1", "content_id": "7087e4ffcbc396541131b5bec51a5ce59ca18af0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 924, "license_type": "permissive", "max_line_length": 107, "num_lines": 31, "path": "/readthedocs/code-tabs/python/pyxenon_snippets/copy_file_local_to_local_absolute_paths.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "import xenon\nfrom xenon import Path, FileSystem, CopyRequest, CopyStatus\n\n\ndef run_example():\n\n xenon.init()\n\n filesystem = FileSystem.create(adaptor='file')\n source_file = Path(\"/home/travis/thefile.txt\")\n dest_file = Path(\"/home/travis/thefile.bak\")\n\n # start the copy operation; no recursion, we're just copying a file\n copy_id = filesystem.copy(source_file, filesystem, dest_file, mode=CopyRequest.CREATE, recursive=False)\n\n # wait this many milliseconds for copy operations to complete\n wait_duration = 1000 * 60 * 10\n\n # wait for the copy operation to complete (successfully or otherwise)\n copy_status = filesystem.wait_until_done(copy_id, wait_duration)\n\n assert copy_status.done\n\n # rethrow the Exception if we got one\n assert copy_status.error_type == CopyStatus.ErrorType.NONE, copy_status.error_message\n\n filesystem.close()\n\n\nif __name__ == '__main__':\n run_example()\n" }, { "alpha_fraction": 0.7524752616882324, "alphanum_fraction": 0.7821782231330872, "avg_line_length": 66.33333587646484, "blob_id": "586d7407d66396c62b044374590b091a66c255cb", "content_id": "4cf7a08237a0817aed8e2313d1710d6d1a9b0214", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 202, "license_type": "permissive", "max_line_length": 89, "num_lines": 3, "path": "/readthedocs/code-tabs/bash/DownloadFileSftpToLocalAbsolutePaths.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "# step 3: download generated output file(s)\nxenon filesystem sftp --location localhost:10022 --username xenon --password javagat \\\ndownload /home/xenon/sleep.stdout.txt /home/travis/sleep.stdout.txt\n" }, { "alpha_fraction": 0.6488160490989685, "alphanum_fraction": 0.6615664958953857, "avg_line_length": 24.183486938476562, "blob_id": "c131751c94796597571f2cefe08c22842a08373e", "content_id": "1cc07cbe57178e01c6fcd5fc7333767c4dbc1f86", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2745, "license_type": "permissive", "max_line_length": 82, "num_lines": 109, "path": "/readthedocs/troubleshooting-ssh.rst", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": ":orphan:\n\nTroubleshooting ``SSH``\n=======================\n\n\nFile permissions\n----------------\n\nThe first thing to check is whether your system has the correct permissions on\nthe following files (you can check the octal representation of the file\npermission with: ``stat -c %a <filename>``):\n\n.. code-block::\n\n # client-side\n chmod go-w $HOME \n chmod 700 $HOME/.ssh\n chmod 600 $HOME/.ssh/config # (documentation varies 644, 600, 400)\n chmod 600 $HOME/.ssh/id_rsa # (private keys, rsa and other types)\n chmod 644 $HOME/.ssh/id_rsa.pub # (public keys, rsa and other types)\n chmod 600 $HOME/.ssh/known_hosts # (not documented)\n\n # server side:\n chmod 600 <other system's home dir>/.ssh/authorized_keys\n\nOwnership\n---------\n\nAll files and directories under ``~/.ssh``, as well as ``~/.ssh`` itself, should\nbe owned by the user with ``id`` ``$(id -u)``.\n\n.. code-block:: bash\n\n chown -R $(id -u):$(id -g) ~/.ssh\n\n\n``ssh`` from the command line\n-----------------------------\n\nCheck if you can access the remote system using OpenSSH instead of Xenon. On\nUbuntu-like systems, you can install OpenSSH with:\n\n.. code-block:: bash\n\n sudo apt install openssh-client\n\nIncrease ``ssh``'s verbosity using the ``-vvvv`` option (more ``v``'s means higher\nverbosity), e.g.\n\n.. code-block:: bash\n\n ssh -vvv user@host\n \nAnother useful option is to ask ``ssh`` for a list of its configuration options\nand their values with the ``-G`` option, e.g.\n\n.. code-block:: bash\n\n ssh -G anyhost\n ssh -G [email protected]\n\nSometimes, a connection cannot be set up because of a configuration problem on\nthe server side. If you have access to the server through another way, running \n\n.. code-block:: bash\n\n sshd -T\n\nmight help track the problem down. Note that the results may be user-dependent,\nfor example the result may be different for ``root`` or for a user.\n\nConfiguration settings\n----------------------\n\n#. client-side, user configuration: ``/etc/ssh/ssh_config``\n#. client-side, system configuration ``$HOME/.ssh/config``\n#. server-side, system configuration ``/etc/ssh/sshd_config``\n\n\n``known_hosts``\n---------------\n\n#. file permission\n#. host name hashed or not ``hashKnownHosts``\n#. removing a given host's key goes like this ``ssh-keygen -R [localhost]:10022``\n\nXenon with properties\n---------------------\n\nSee http://xenon-middleware.github.io/xenon/versions/3.0.1/javadoc/\n\n#. ``xenon.adaptors.schedulers.ssh.strictHostKeyChecking``\n#. ``xenon.adaptors.schedulers.ssh.loadKnownHosts``\n#. ``xenon.adaptors.schedulers.ssh.loadSshConfig``\n\nEncrypted ``/home``\n-------------------\n\nMight negatively affect things https://help.ubuntu.com/community/SSH/OpenSSH/Keys\n\n|\n|\n|\n\n:doc:`back to the tutorial</tutorial>`\n\n|\n|\n" }, { "alpha_fraction": 0.7250000238418579, "alphanum_fraction": 0.7607142925262451, "avg_line_length": 42.07692337036133, "blob_id": "47409307304d79aaa45a9a0cf37f012708d01b8e", "content_id": "b1b2273c55d606993296f96bd89f32e45dc80e2f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 560, "license_type": "permissive", "max_line_length": 95, "num_lines": 13, "path": "/readthedocs/code-tabs/bash/AllTogetherNowWrong.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# step 1: upload input file(s)\nxenon filesystem sftp --location localhost:10022 --username xenon --password javagat \\\nupload /home/travis/sleep.sh /home/xenon/sleep.sh\n\n# step 2: submit job\nxenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat \\\nsubmit --stdout sleep.stdout.txt bash sleep.sh 60\n\n# step 3: download generated output file(s)\nxenon filesystem sftp --location localhost:10022 --username xenon --password javagat \\\ndownload /home/xenon/sleep.stdout.txt /home/travis/sleep.stdout.txt\n" }, { "alpha_fraction": 0.6500586271286011, "alphanum_fraction": 0.6576787829399109, "avg_line_length": 31.80769157409668, "blob_id": "bca1496952e40037c134c181fbc27b119c0fb8d0", "content_id": "c2ca0529471fa6724eee15fe01943dcd288795f7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1706, "license_type": "permissive", "max_line_length": 89, "num_lines": 52, "path": "/readthedocs/code-tabs/python/pyxenon_snippets/download_file_sftp_to_local_absolute_paths.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "import xenon\nfrom xenon import FileSystem, PasswordCredential, CopyRequest, Path, CopyStatus\n\n\ndef run_example():\n\n xenon.init()\n\n # use the sftp file system adaptor to create a file system\n # representation; the remote filesystem requires credentials to log in,\n # so we'll have to create those too.\n credential = PasswordCredential(username='xenon',\n password='javagat')\n\n remote_fs = FileSystem.create(adaptor='sftp',\n location='localhost:10022',\n password_credential=credential)\n\n # use the local file system adaptor to create another file system representation\n local_fs = FileSystem.create(adaptor='file')\n\n # define which file to download\n remote_file = Path('/home/xenon/sleep.stdout.txt')\n local_file = Path('/home/travis/sleep.stdout.txt')\n\n # create the destination file only if the destination path doesn't exist yet\n mode = CopyRequest.CREATE\n\n # no need to recurse, we're just uploading a file\n recursive = False\n\n # perform the copy/download and wait 1000 ms for the successful or\n # otherwise completion of the operation\n copy_id = remote_fs.copy(remote_file, local_fs, local_file,\n mode=mode, recursive=recursive)\n\n copy_status = remote_fs.wait_until_done(copy_id, timeout=5000)\n\n assert copy_status.done\n\n # rethrow the Exception if we got one\n assert copy_status.error_type == CopyStatus.ErrorType.NONE, copy_status.error_message\n\n # remember to close the FileSystem instances\n remote_fs.close()\n local_fs.close()\n\n print('Done')\n\n\nif __name__ == '__main__':\n run_example()\n" }, { "alpha_fraction": 0.7243674993515015, "alphanum_fraction": 0.757656455039978, "avg_line_length": 43.235294342041016, "blob_id": "c880efb0cc9dfbf27b2e9703f649fb43252ab61d", "content_id": "ce613158d37b289af0f2bb2a0a944c98fdd0ff58", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 751, "license_type": "permissive", "max_line_length": 103, "num_lines": 17, "path": "/readthedocs/code-tabs/bash/AllTogetherNow.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# step 1: upload input file(s)\nxenon filesystem sftp --location localhost:10022 --username xenon --password javagat \\\nupload --replace /home/travis/sleep.sh /home/xenon/sleep.sh\n\n# step 2: submit job and capture its job identifier\nJOBID=$(xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat \\\nsubmit --stdout sleep.stdout.txt bash sleep.sh 60)\n\n# add blocking wait\nxenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat \\\nwait $JOBID\n\n# step 3: download generated output file(s)\nxenon filesystem sftp --location localhost:10022 --username xenon --password javagat \\\ndownload --replace /home/xenon/sleep.stdout.txt /home/travis/sleep.stdout.txt" }, { "alpha_fraction": 0.46666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 14, "blob_id": "7f8680ae46790435a0b2e0978253050e170acee2", "content_id": "f6b08613716665fd90866b2c43db110f53adb42c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 15, "license_type": "permissive", "max_line_length": 14, "num_lines": 1, "path": "/readthedocs/code-tabs/python/requirements.txt", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "pyxenon==3.0.1\n" }, { "alpha_fraction": 0.6206293702125549, "alphanum_fraction": 0.6206293702125549, "avg_line_length": 21.8799991607666, "blob_id": "b0a2d08b27cb1b8af63ad31c6e3af6bdfc2694c6", "content_id": "2bdf882126a6669bdb3c1ef02dbe9c9738bd2f67", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 572, "license_type": "permissive", "max_line_length": 108, "num_lines": 25, "path": "/readthedocs/code-tabs/python/pyxenon_snippets/ftp_directory_listing.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "import xenon\nfrom xenon import Path, FileSystem, PasswordCredential\n\n\ndef run_example():\n\n xenon.init()\n\n credential = PasswordCredential(username='demo',\n password='password')\n\n filesystem = FileSystem.create(adaptor='ftp', location='test.rebex.net', password_credential=credential)\n path = Path(\"/\")\n\n listing = filesystem.list(path, recursive=False)\n\n for entry in listing:\n if not entry.path.is_hidden():\n print(entry.path)\n\n filesystem.close()\n\n\nif __name__ == '__main__':\n run_example()\n" }, { "alpha_fraction": 0.6415228247642517, "alphanum_fraction": 0.674010157585144, "avg_line_length": 29.96855354309082, "blob_id": "5274f15302a03ff02ea6b9ea68e58dbbb932c532", "content_id": "b541e1ee318f1761c020c955a0a4c1947f004e74", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9852, "license_type": "permissive", "max_line_length": 268, "num_lines": 318, "path": "/vm-prep/README.md", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "# Installation\n\n\n1. Use VirtualBox for virtualization.\n - Windows: https://download.virtualbox.org/virtualbox/6.0.10/VirtualBox-6.0.10-132072-Win.exe\n - OS X: https://download.virtualbox.org/virtualbox/6.0.10/VirtualBox-6.0.10-132072-OSX.dmg\n - Linux: https://www.virtualbox.org/wiki/Linux_Downloads\n1. Create a virtual machine in VirtualBox using Ubuntu 18.04.03 as a base image. Get the .iso here http://releases.ubuntu.com/18.04/\n1. Configure the VM with at least 2 CPUs.\n1. Configure main memory to use 4 GB.\n1. Configure video memory to use the maximum of 128 MB.\n1. Call the user ``travis``\n1. Set his password to ``password``\n1. Update packages\n\n ```\n sudo apt update\n sudo apt upgrade\n ```\n\n1. Enable Bash completion from history\n\n ```\n echo '\"\\e[A\": history-search-backward # arrow up' >> ~/.inputrc\n echo '\"\\e[B\": history-search-forward # arrow down' >> ~/.inputrc\n echo 'set completion-ignore-case on' >> ~/.inputrc\n ```\n\n1. Install Java version 11\n\n ```\n sudo apt install openjdk-11-jre\n ```\n\n1. Get docker (instructions from here https://docs.docker.com/install/linux/docker-ce/ubuntu/#install-docker-ce)\n\n ```\n # Install packages to allow apt to use a repository over HTTPS:\n sudo apt-get install \\\n apt-transport-https \\\n ca-certificates \\\n curl \\\n gnupg-agent \\\n software-properties-common\n\n # Add Docker’s official GPG key:\n curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\n\n # Confirm you have the correct key ending in 0EBFCD88\n sudo apt-key fingerprint 0EBFCD88\n pub rsa4096 2017-02-22 [SCEA]\n 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88\n uid [ unknown] Docker Release (CE deb) <[email protected]>\n sub rsa4096 2017-02-22 [S]\n\n # add the correct repository depending on architecture and linux distribution:\n sudo add-apt-repository \\\n \"deb [arch=amd64] https://download.docker.com/linux/ubuntu \\\n $(lsb_release -cs) \\\n stable\"\n\n # update package index\n sudo apt-get update\n\n # install docker packages\n sudo apt-get install docker-ce docker-ce-cli containerd.io\n ```\n\n1. Configure the current user to allow running docker without asking for password\n\n ```\n # docker install should have created the docker group already, but just in case:\n sudo groupadd docker\n\n # add current user to docker group\n sudo usermod -aG docker $USER\n\n # start using the new settings (no sudo)\n # Note: I actually had to reboot to make this work.\n newgrp docker\n ```\n\n1. Install Git\n\n ```\n sudo apt install git\n ```\n\n1. Get a copy of the tutorial materials:\n\n ```\n git clone https://github.com/xenon-middleware/xenon-tutorial.git\n ```\n\n1. Install dependencies for generating the Sphinx documentation\n\n ```\n sudo apt install python3-pip\n cd ~/xenon-tutorial/readthedocs/\n pip3 install --user -r requirements.txt\n ```\n\n1. Add the user-space Python packages to the PATH\n\n ```\n echo '' >> ~/.bashrc\n echo '# add directory where python has user space packages, e.g. when installing' >> ~/.bashrc\n echo '# with pip3 install --user <package name>' >> ~/.bashrc\n echo 'PATH=$PATH:~/.local/bin' >> ~/.bashrc\n\n # enable the new settings\n source ~/.bashrc\n ```\n\n1. Generate the Sphinx documentation\n\n ```\n cd ~/xenon-tutorial/readthedocs/\n sphinx-build -b html . build/\n ```\n\n1. Get a copy of xenon cli, install it, add to PATH:\n\n ```\n cd ~/Downloads\n wget https://github.com/xenon-middleware/xenon-cli/releases/download/v3.0.4/xenon-cli-shadow-3.0.4.tar\n tar -xvf xenon-cli-shadow-3.0.4.tar\n mkdir -p ~/.local/bin/xenon\n mv xenon-cli-shadow-3.0.4 ~/.local/bin/xenon/\n\n echo '' >> ~/.bashrc\n echo '# add xenon-cli directory to PATH' >> ~/.bashrc\n echo 'PATH=$PATH:~/.local/bin/xenon/xenon-cli-shadow-3.0.4/bin' >> ~/.bashrc\n\n # enable the new settings\n source ~/.bashrc\n\n ```\n\n1. Check that the downloaded version of xenon-cli uses the same xenon as what is defined in ``readthedocs/code-tabs/java/build.gradle``.\n1. Check that the downloaded version of xenon-cli is the same as what is defined in ``.travis.yml``.\n1. Create filesystem fixtures\n\n ```\n mkdir -p /home/travis/fixtures/dir1\n mkdir -p /home/travis/fixtures/.dir2\n echo 'dir1/file1.txt' > /home/travis/fixtures/dir1/file1.txt\n echo 'dir1/.file2.txt' > /home/travis/fixtures/dir1/.file2.txt\n echo '.dir2/file3.txt' > /home/travis/fixtures/.dir2/file3.txt\n echo '.dir2/.file4.txt' > /home/travis/fixtures/.dir2/.file4.txt\n ```\n\n1. Install ``tree``\n\n ```\n sudo apt install tree\n ```\n\n1. Install simple editors: nano, others\n\n ```\n sudo apt install geany\n sudo apt install leafpad\n sudo apt install joe\n\n # choose which editor should be default (nano)\n sudo update-alternatives --config editor\n\n ```\n\n1. Install Eclipse\n\n ```\n # (from https://download.eclipse.org/eclipse/downloads/drops4/R-4.12-201906051800/)\n # download platform runtime binary\n cd ~/Downloads\n wget http://ftp.snt.utwente.nl/pub/software/eclipse//eclipse/downloads/drops4/R-4.12-201906051800/eclipse-platform-4.12-linux-gtk-x86_64.tar.gz\n tar -xzvf eclipse-platform-4.12-linux-gtk-x86_64.tar.gz\n\n mkdir -p ~/opt/eclipse/\n mv eclipse ~/opt/eclipse/eclipse-4.12\n ```\n\n ```\n mkdir -p $HOME/.local/share/applications/\n\n echo \"[Desktop Entry]\n Type=Application\n GenericName=Text Editor\n Encoding=UTF-8\n Name=Eclipse\n Comment=Java IDE\n Exec=$HOME/opt/eclipse/eclipse-4.12/eclipse\n Icon=$HOME/opt/eclipse/eclipse-4.12/icon.xpm\n Terminal=false\n Categories=GNOME;GTK;Utility;TextEditor;Development;\n MimeType=text/plain\" > $HOME/.local/share/applications/eclipse.desktop\n\n echo \"\n # Add directory containing eclipse to the PATH\n PATH=\\$PATH:$HOME/opt/eclipse/eclipse-4.12\n \" >> $HOME/.profile\n ```\n\n Configure Eclipse by installing _Help_ >> _Install New Software..._ >> (select _--All Available Sites--_) >> _Programming Languages_ >> _Eclipse Java Development Tools_ (see https://medium.com/@acisternino/a-minimal-eclipse-java-ide-d9ba75491418).\n\n Prepare Java snippets directory as an Eclipse Java project:\n\n ```\n cd $HOME/xenon-tutorial/readthedocs/code-tabs/java\n ./gradlew eclipse\n ```\n\n In Eclipse, _Import project_.\n\n1. Download Docker images\n\n ```\n docker pull xenonmiddleware/s3\n docker pull xenonmiddleware/slurm:17\n docker pull xenonmiddleware/ssh\n docker pull xenonmiddleware/webdav\n ```\n1. Generate the Sphinx documentation locally just in case there are network problems\n1. Configure OpenSSH\n\n ```\n sudo apt install openssh-client\n chmod go-w /home/travis\n chmod 700 /home/travis/.ssh\n cp vm-prep/.ssh/known_hosts /home/travis/.ssh/known_hosts\n chmod 644 /home/travis/.ssh/known_hosts\n cp vm-prep/.ssh/config /home/travis/.ssh/config\n chmod 600 /home/travis/.ssh/config\n chown -R travis:travis /home/.ssh\n ```\n\n1. Install python ``virtualenv``, make a virtual environment, activate it, and\ninstall ``pyxenon`` in it (pyxenon does not work outside a virtual environment).\n\n ```\n sudo apt install virtualenv\n cd ~/xenon-tutorial/readthedocs/code-tabs/python/\n virtualenv -p /usr/bin/python3.6 venv36\n source venv36/bin/activate\n pip3 install -r requirements.txt\n ```\n\n Also include the test framework\n\n ```\n pip3 install -r requirements-dev.txt\n ```\n\n Check that it works by\n\n ```\n which xenon-grpc\n ```\n and\n\n ```\n pytest tests/ --ignore=tests/test_upload_file_local_to_sftp_absolute_paths.py \\\n --ignore=tests/test_download_file_sftp_to_local_absolute_paths.py\n ```\n\n1. Export vm as ova\n1. Test the installation\n\n----\n\nThis here is @jmaassen's setup to avoid having to deal with intricacies related to an OS that is not your own. With this setup, you can ssh into the VM, then make edits there from the comfort of the terminal that you are used to, with the tooling that you are used to.\n\n1. Start the RSE2017 Fedora virtual machine from VirtualBox, log in as user ``tutorial`` using password ``tutorial``\n1. In the VM, open a terminal and type ``ifconfig``. Look for an entry that has an ``inet`` value starting with ``10.`` (mine is ``10.0.2.15``). We will use this value as Guest IP later.\n1. In the terminal, start the SSH server with ``sudo systemctl start sshd.service``\n1. In VirtualBox, change the port forwarding settings, as follows:\n 1. Go to menu item ``Machine``\n 1. Go to ``Settings``\n 1. Go to ``Network``\n 1. On tab ``Adaptor 1``, go to ``Advanced``, click on ``Port Forwarding``\n 1. Click the ``plus`` icon to add a rule\n 1. Under ``protocol`` fill in ``TCP``\n 1. Under ``Host IP`` fill in ``127.0.0.1``\n 1. Under ``Host Port`` fill in ``2222``\n 1. Under ``Guest IP`` fill in the value we got from ``ifconfig``\n 1. Under ``Guest Port`` fill in ``22``\n1. Outside the VM, open a terminal, type ``ssh -p 2222 [email protected]`` (type password ``tutorial`` when asked). You should now be logged in to the RSE2017 VM.\n\n\n----\n\nNot sure we still need any of this (from the rse17 tutorial)\n\n```\n\npreparations for the rse vm\n - virtualbox guest additions\n - number of cpus\n\nimport ovafile\nset number of cpus to 2\n# enable 3D hardware acceleration\n# set virtual memory to max, 128 MB\nstart fedora\n\nin terminal\nsudo dnf update kernel*\nreboot\nsudo dnf install gcc kernel-devel kernel-headers dkms make bzip2 perl\nKERN_DIR=/usr/src/kernels/`uname -r`\nexport KERN_DIR\nfrom top virtualbox dropdown menu, select devices, insert guest additions\nlet guest additions install from the autorun, shutdown afterwards\n# disable 3d acceleration again\nlogin\n\n```\n\n\n" }, { "alpha_fraction": 0.6487294435501099, "alphanum_fraction": 0.6576980352401733, "avg_line_length": 22.89285659790039, "blob_id": "66f748e56746697c1547cc995c691e67e4475819", "content_id": "b72716a8918de6db81a8f9197dcac155bdfd7246", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 669, "license_type": "permissive", "max_line_length": 54, "num_lines": 28, "path": "/readthedocs/code-tabs/bash/travis.sh", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# some examples need a running docker, see .travis.yml\n\nrun_snippet () {\n echo \"travis_fold:start:$1\"\n echo \"[output of $1]\"\n bash $1 || exit 1; \n echo \"travis_fold:end:$1\"\n}\n\nsnippets=\"DirectoryListing.sh \\\n DirectoryListingShowHidden.sh \\\n DirectoryListingRecursive.sh \\\n CopyFileLocalToLocalAbsolutePaths.sh \\\n SlurmQueuesGetter.sh\n UploadFileLocalToSftpAbsolutePaths.sh\n SlurmJobListGetter.sh \\\n AllTogetherNowWrong.sh \\\n AllTogetherNow.sh\"\n# DownloadFileSftpToLocalAbsolutePaths.sh\"\n\nfor snippet in $snippets ; \ndo\n run_snippet $snippet\ndone\n \nexit 0;\n" }, { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.782608687877655, "avg_line_length": 19.33333396911621, "blob_id": "13fe4694817dd8f635a3f7842b3123d2da8f324a", "content_id": "73e823c830b6abe9c91c69930849b15b603a17bb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 184, "license_type": "permissive", "max_line_length": 56, "num_lines": 9, "path": "/readthedocs/code-tabs/python/tests/test_directory_listing_recursive.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pytest\n\n\nfrom pyxenon_snippets import directory_listing_recursive\n\n\ndef test_directory_listing_recursive():\n directory_listing_recursive.run_example()\n\n" }, { "alpha_fraction": 0.7597402334213257, "alphanum_fraction": 0.7597402334213257, "avg_line_length": 16, "blob_id": "51b705421b9414e6a2cf5d7bdfca5558916c1919", "content_id": "e8804cd7dc40d43471ead09d9c5836fb6c063406", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 154, "license_type": "permissive", "max_line_length": 46, "num_lines": 9, "path": "/readthedocs/code-tabs/python/tests/test_directory_listing.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pytest\n\n\nfrom pyxenon_snippets import directory_listing\n\n\ndef test_directory_listing():\n directory_listing.run_example()\n\n" }, { "alpha_fraction": 0.6924629807472229, "alphanum_fraction": 0.6978465914726257, "avg_line_length": 39.18918991088867, "blob_id": "b2adc28b4e452b79c7d78665c363a0ac0cc869e7", "content_id": "22944b4591a492f92c0f7fc5c3f0b9cfaaa2d8ba", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1486, "license_type": "permissive", "max_line_length": 91, "num_lines": 37, "path": "/readthedocs/code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/CopyFileLocalToLocalAbsolutePaths.java", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "package nl.esciencecenter.xenon.tutorial;\n\nimport nl.esciencecenter.xenon.filesystems.CopyMode;\nimport nl.esciencecenter.xenon.filesystems.CopyStatus;\nimport nl.esciencecenter.xenon.filesystems.FileSystem;\nimport nl.esciencecenter.xenon.filesystems.Path;\n\npublic class CopyFileLocalToLocalAbsolutePaths {\n\n public static void main(String[] args) throws Exception {\n\n // use the local file system adaptor to create a file system representation\n String adaptor = \"file\";\n FileSystem filesystem = FileSystem.create(adaptor);\n\n // create Paths for the source and destination files, using absolute paths\n Path sourceFile = new Path(\"/home/travis/thefile.txt\");\n Path destFile = new Path(\"/home/travis/thefile.bak\");\n\n // create the destination file only if the destination path doesn't exist yet\n CopyMode mode = CopyMode.CREATE;\n boolean recursive = false;\n\n // perform the copy and wait 1000 ms for the successful or otherwise\n // completion of the operation\n String copyId = filesystem.copy(sourceFile, filesystem, destFile, mode, recursive);\n long timeoutMilliSecs = 1000;\n CopyStatus copyStatus = filesystem.waitUntilDone(copyId, timeoutMilliSecs);\n\n // print any exceptions\n if (copyStatus.getException() != null) {\n System.out.println(copyStatus.getException().getMessage());\n } else {\n System.out.println(\"File copied.\");\n }\n }\n}" }, { "alpha_fraction": 0.7515337467193604, "alphanum_fraction": 0.7530674934387207, "avg_line_length": 29.279069900512695, "blob_id": "50470dec77db23da5de2bc4d51b1b5c4e4460966", "content_id": "7f46e2e21fb32a1f70d142614ffbba1c67ca2c78", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1304, "license_type": "permissive", "max_line_length": 114, "num_lines": 43, "path": "/readthedocs/code-tabs/java/README.md", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "\n## Running the code snippets as used in the tutorial from the Linux command line\n\nThe code snippets from ``src/main/java/nl/esciencecenter/xenon/tutorial`` can\nall be run. For this, you'll need Java Runtime Environment version 11 or later.\n\nAdditionally, be aware that some snippets expect certain paths, for example when\ncopying a file.\n\nIndividual snippets can be run with the following syntax:\n\n```bash\n./gradlew run -Pmain=<main class name> [-Ploglevel=<ERROR|WARN|INFO|DEBUG>] [--args='<arguments for main method>']\n```\n\nFor example, to run\n[DirectoryListing](src/main/java/nl/esciencecenter/xenon/tutorial/DirectoryListing.java)\nuse:\n\n```bash\n./gradlew run -Pmain=nl.esciencecenter.xenon.tutorial.DirectoryListing\n```\n\n## Configuring your IDE\n\nYou may want to use an IDE for running the code snippets. Here's how you an set\nup a project for use with Eclipse:\n\n```bash\n./gradlew eclipse\n```\n\nThis configures the classpath such that you can use the project dependencies\nfrom within Eclipse. After running the task, you can see to what location the\ndependencies were downloaded on your system by opening ``.classpath`` with a\ntext editor.\n\nIf you want to \"undo\" ``./gradlew eclipse``, use\n\n```bash\n./gradlew cleanEclipse\n```\n\nwhich will remove files ``.classpath``, ``.project``, and ``.settings``.\n\n" }, { "alpha_fraction": 0.7239999771118164, "alphanum_fraction": 0.7279999852180481, "avg_line_length": 18.230770111083984, "blob_id": "c5ee93d1320d577defa96130eb1c45086629318b", "content_id": "bdfc363c7354da35a718684cb74d304874e5815e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 250, "license_type": "permissive", "max_line_length": 45, "num_lines": 13, "path": "/readthedocs/code-tabs/java/src/test/java/nl/esciencecenter/xenon/tutorial/DirectoryListingRecursiveTest.java", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "package nl.esciencecenter.xenon.tutorial;\n\nimport org.junit.Test;\n\n\npublic class DirectoryListingRecursiveTest {\n\n @Test(expected = Test.None.class)\n public void test1() throws Exception {\n DirectoryListingRecursive.main(null);\n }\n\n}\n" }, { "alpha_fraction": 0.6676163077354431, "alphanum_fraction": 0.6676163077354431, "avg_line_length": 19.647058486938477, "blob_id": "dfe1ab1051954056f6f5703985ff9cc9459c940b", "content_id": "d89f45d68bcc2f5df9b11e9c863f1862cd57fcb1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1053, "license_type": "permissive", "max_line_length": 90, "num_lines": 51, "path": "/readthedocs/when-things-dont-work.rst", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": ":orphan:\n\nWhen things don't work\n======================\n\nBash\n----\n\nIncrease ``xenon``'s verbosity using its ``v`` option. More ``v``'s means more\nverbose output.\n\n.. code-block::\n\n xenon -vvvv <subcommands>\n\nJava from Eclipse\n-----------------\n\nIncrease verbosity by adding the following in Eclipse Debug Configuration, tab\n*Arguments* >> *VM arguments*\n\n.. code-block::\n\n -Dloglevel=DEBUG\n\nJava from command line\n----------------------\n\nIncrease the verbosity by adding ``loglevel=DEBUG`` as a property:\n\n.. code-block::\n\n ./gradlew run -Pmain=nl.esciencecenter.xenon.tutorial.DirectoryListing -Ploglevel=DEBUG\n\nPython\n------\n\nStart ``xenon-grpc`` in a terminal, using its ``v`` option. More ``v``'s means\nmore verbose output, e.g. ``xenon-grpc -vvvvv``. Subsequent calls to\n``xenon.init()`` (originating from anywhere on the system) will connect to this\n``grpc`` server, and its logging will appear in the terminal. Unfortunately,\nthis verbosity setting does not propagate down to ``xenon``.\n\n|\n|\n|\n\n:doc:`back to the tutorial</tutorial>`\n\n|\n|\n" }, { "alpha_fraction": 0.6980610489845276, "alphanum_fraction": 0.7041067481040955, "avg_line_length": 33.40713119506836, "blob_id": "318b4bc2e535d7cf31f07a46d7d80f42bfe08e66", "content_id": "b340440502157a0134af8e414ead991ffbea1e16", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 23157, "license_type": "permissive", "max_line_length": 147, "num_lines": 673, "path": "/readthedocs/tutorial.rst", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "\nNote we have GoogleAnalytics enabled for this tutorial to help show our funders that the work\nwe do is useful to others.\n\n|\n|\n|\n\nGetting started\n---------------\n\nOn your system, start VirtualBox.\n\nThis tutorial uses a virtual machine to help avoid issues that are due to system configuration.\nIn case you don't have a copy of the virtual machine, you can\ndownload it from Zenodo `here`__. After the download finishes, click ``File`` in VirtualBox, then\n``Import appliance``, then select the file you downloaded.\n\n__ https://doi.org/10.5281/zenodo.3406325\n\nDuring the import, you'll see an initialization wizard. Make sure that the virtual machine is configured with two CPUs.\n\nStart the virtual machine and log in as user ``travis`` with password ``password``.\n\nOnce the system has booted, start both a terminal and Firefox by clicking their respective\nicons. Use Firefox to navigate to the tutorial text at `<https://xenon-tutorial.readthedocs.io>`_.\n\nIn the terminal, confirm that the ``xenon`` command line interface\nprogram can be found on the system:\n\n.. code-block:: bash\n\n xenon --help\n\n.. code-block:: bash\n\n xenon --version\n Xenon CLI v3.0.4, Xenon library v3.0.4, Xenon cloud library v3.0.2\n\n|\n\nIf you run into trouble, :doc:`here are some pointers</when-things-dont-work>` on what you can do.\n\n|\n\nInteracting with filesystems\n----------------------------\n\nEssentially, ``xenon`` can be used to manipulate files and to interact with schedulers, where either one can be local\nor remote. Let's start simple and see if we can do something with local files. First, check its help:\n\n.. code-block:: bash\n\n xenon filesystem --help\n\nThe usage line suggests we need to pick one from ``{file,ftp,s3,sftp,webdav}``.\nAgain, choose what seems to be the simplest option (``file``), and again, check its help.\n\n.. code-block:: bash\n\n xenon filesystem file --help\n\n``xenon filesystem file``'s usage line seems to suggest that I need to pick one\nfrom ``{copy,list,mkdir,remove,rename}``. Simplest one is probably ``list``, so:\n\n.. code-block:: bash\n\n xenon filesystem file list --help\n\nSo we need a ``path`` as final argument.\n\nIn case you hadn't noticed the pattern, stringing together any number of ``xenon`` subcommands and appending ``--help``\nto it will get you help on the particular combination of subcommands you supplied.\n\nThe focus of this tutorial is on using Xenon's command line interface, but be\naware that you can use xenon's functionality from other programming\nlanguages through `xenon's gRPC extension`__.\n\nWhere relevant, we have included equivalent code snippets,\nwritten in Java and Python, as a separate tab.\n\n__ https://github.com/xenon-middleware/xenon-grpc\n\nLet's try listing the contents of ``/home/travis/fixtures/``.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/DirectoryListing.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/DirectoryListing.java\n :language: java\n :linenos:\n\n .. group-tab:: Python\n\n .. literalinclude:: code-tabs/python/pyxenon_snippets/directory_listing.py\n :language: python\n :linenos:\n\nThe result should be more or less the same as that of ``ls -1``.\n\n``xenon filesystem file list`` has a few options that let you specify the details of the list operation, e.g.\n``--hidden``\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/DirectoryListingShowHidden.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/DirectoryListingShowHidden.java\n :language: java\n :linenos:\n\n .. group-tab:: Python\n\n .. literalinclude:: code-tabs/python/pyxenon_snippets/directory_listing_show_hidden.py\n :language: python\n :linenos:\n\nand ``--recursive``\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/DirectoryListingRecursive.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/DirectoryListingRecursive.java\n :language: java\n :linenos:\n\n .. group-tab:: Python\n\n .. literalinclude:: code-tabs/python/pyxenon_snippets/directory_listing_recursive.py\n :language: python\n :linenos:\n\nNow let's create a file and try to use ``xenon`` to copy it:\n\n.. code-block:: bash\n\n cd /home/travis\n echo 'some content' > thefile.txt\n\nCheck the relevant help\n\n.. code-block:: bash\n\n xenon filesystem file --help\n xenon filesystem file copy --help\n\nSo, the ``copy`` subcommand takes a source path and a target path:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/CopyFileLocalToLocalAbsolutePaths.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/CopyFileLocalToLocalAbsolutePaths.java\n :language: java\n :linenos:\n\n .. group-tab:: Python\n\n .. literalinclude:: code-tabs/python/pyxenon_snippets/copy_file_local_to_local_absolute_paths.py\n :language: python\n :linenos:\n\nNote that the source path may be standard input, and that the target path may be standard output:\n\n.. code-block:: bash\n\n # read from stdin:\n cat thefile.txt | xenon filesystem file copy - mystdin.txt\n\n # write to stdout:\n xenon filesystem file copy thefile.txt - 1> mystdout.txt\n\n``xenon filesystem file`` has a few more subcommands, namely ``mkdir``, ``rename`` and ``remove``. You can\nexperiment a bit more with those before moving on to the next section.\n\nAccess to remote filesystems\n----------------------------\n\nOf course the point of ``xenon`` is not to move around files on your local filesystem. There are enough tools to help you with\nthat. The idea is that you can also use ``xenon`` to move files to and from different types of remote servers, without having to\nlearn a completely different tool every time.\n\nFirst, let's check which types of file servers ``xenon`` currently supports:\n\n.. code-block:: bash\n\n xenon filesystem --help\n\nThe usage line shows that besides ``file`` we can also choose ``ftp, s3, sftp`` or ``webdav``. Let's try ``ftp`` first.\n\n.. code-block:: bash\n\n xenon filesystem ftp --help\n\nThe usage line tells us that ``ftp`` has an mandatory parameter ``--location`` which we haven't seen yet. We can use this to specify\nwhich server to connect to. Additionally, there are also optional ``--username`` and ``--password`` options in case we need\nto log into the machine.\n\nLet's see if we can use this to connect to a real machine on the internet. A public FTP server for testing should be available at\n``test.rebex.net`` with the credentials ``demo`` and ``password``:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/FTPDirectoryListing.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/FTPDirectoryListingShowHidden.java\n :language: java\n :linenos:\n\nThis should give you a listing of the server at ``test.rebex.net``.\n\nBesides the commands we have already seen (``copy``, ``list``, etc.), ``ftp`` also supports a few new ones, namely ``upload``\nand ``download``. We can use these to transer files to and from the server. For example, this command will download a file from\nour example FTP server:\n\n.. code-block:: bash\n\n # download a file from the ftp server\n xenon filesystem ftp --location test.rebex.net --username demo --password password download /readme.txt `pwd`/readme.txt\n\nYou can even print the remote file on your screen by copying it to stdout:\n\n.. code-block:: bash\n\n # print a file from the ftp server on the screen\n xenon filesystem ftp --location test.rebex.net --username demo --password password download /readme.txt -\n\nNote that when using ``copy`` on remote servers, ``xenon`` will attempt to copy the file on the server itself. Since we don't have write\naccess to this FTP server, the command will fail.\n\nThe strength of ``xenon`` is that you can now use the same syntax to access a different type of server. For example, the ``test.rebex.net``\nserver also offers a secure FTP (``sftp``) service for testing. We can access that service with ``xenon`` by simply changing ``ftp`` into ``sftp``:\n\n.. code-block:: bash\n\n # list the files on the sftp server\n xenon filesystem sftp --location test.rebex.net --username demo --password password list /\n\n # download a file from the sftp server\n xenon filesystem sftp --location test.rebex.net --username demo --password password download /readme.txt `pwd`/readme2.txt\n\nIn case you are reluctant to type plaintext passwords on the command line, for example because of logging in\n``~/.bash_history``, know that you can supply passwords from a file, as follows:\n\n.. code-block:: bash\n\n # read password from the password.txt file\n xenon filesystem sftp --location test.rebex.net --username demo --password @password.txt list /\n\nin which the file ``password.txt`` should contain the password. Since everything about the user ``xenon`` is public\nknowledge anyway, such security precautions are not needed for this tutorial, so we'll just continue to use the\n``--password PASSWORD`` syntax.\n\nYou can also transfer data from and to other types of file servers (such as ``WebDAV`` and ``S3``) in a similar fashion. We are working to add\nsupport for other types such as GridFTP and iRODS. We will come back to transferring files in the sections below.\n\n|\n|\n|\n\nInteracting with schedulers\n---------------------------\n\nNow let's see if we can use schedulers, starting with `SLURM`__. For this part, we need access to a machine that is running\nSLURM. To avoid problems related to network connectivity, we won't try to connect to a physically remote SLURM machine,\nbut instead, we'll use a dockerized SLURM installation. This way, we can mimic whatever infrastructure we need. The\nsetup will thus be something like this:\n\n__ https://slurm.schedmd.com/\n\n.. image:: _static/babushka.svg.png\n :height: 300px\n :alt: babushka\n :align: center\n\n|\n|\n\nA copy of the SLURM Docker image (`xenonmiddleware/slurm`__:17) has been included in the virtual machine. Bring it\nup with:\n\n__ https://hub.docker.com/r/xenonmiddleware/slurm/\n\n.. code-block:: bash\n\n docker run --detach --publish 10022:22 --hostname slurm17 xenonmiddleware/slurm:17\n\nUse ``docker ps`` to check the state of the container\n\n.. code-block:: bash\n\n docker ps\n\nThe last column in the resulting table lists the name of the container. By\ndefault, ``docker`` assigns automatically generated names, like\n``practical_robinson``, ``keen_goodall`` or ``infallible_morse``. You can use\nthis name to stop and remove a container once you're done with it, as follows:\n\n.. code-block:: bash\n\n docker stop practical_robinson\n docker rm practical_robinson\n\nAnyway, that's for later. For now, check that the container's status is\n``healthy``, and see if you can ``ssh`` into it on port ``10022`` as user\n``xenon`` with password ``javagat``:\n\n.. code-block:: bash\n\n ssh -p 10022 xenon@localhost\n\n # if that works, exit again\n exit\n\nBe aware that ``ssh`` can sometimes be a little picky. We've assembled a list of\ntips and tricks for :doc:`troubleshooting SSH</troubleshooting-ssh>`.\n\nCheck the help to see how the ``slurm`` subcommand works:\n\n.. code-block:: bash\n\n xenon scheduler slurm --help\n\nLet's first ask what queues the SLURM scheduler has. For this, we need to specify\na location, otherwise ``xenon`` does not know who to ask for the list of queues. According to the help,\n``LOCATION`` is any location format supported by ``ssh`` or ``local`` scheduler.\nOur dockerized SLURM machine is reachable as ``ssh://localhost:10022``.\nWe'll also need to provide a ``--username`` and ``--password``\nfor that location, as follows:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/SlurmQueuesGetter.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/SlurmQueuesGetter.java\n :language: java\n :linenos:\n\n .. group-tab:: Python\n\n .. literalinclude:: code-tabs/python/pyxenon_snippets/slurm_queues_getter.py\n :language: python\n :linenos:\n\nBesides ``queues``, other ``slurm`` subcommands are ``exec``, ``submit``, ``list``, ``remove``, and ``wait``. Let's try\nto have ``xenon`` ask SLURM for its list of jobs in each queue, as follows:\n\n.. code-block:: bash\n\n xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat list\n # should work, but we don't have any jobs yet\n\nNow, let's try to submit a job using ``slurm submit``. Its usage string suggests that we need to provide (the path\nof) an ``executable``. Note that the executable should be present inside the container when SLURM starts its execution.\nFor the moment, we'll use ``/bin/hostname`` as the executable. It simply prints the name of the host on the command line.\nFor our docker container, it should return the hostname ``slurm17`` of the Docker\ncontainer, or whatever hostname you specified for it when you ran the ``docker run`` command earlier:\n\n.. code-block:: bash\n\n # check the slurm submit help for correct syntax\n xenon scheduler slurm submit --help\n\n # let xenon submit a job with /bin/hostname as executable\n xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat \\\n submit /bin/hostname\n\n # add --stdout to the submit job to capture its standard out so we know it worked:\n xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat \\\n submit --stdout hostname.stdout.txt /bin/hostname\n\n # check to see if the output was written to file /home/xenon/hostname.stdout.txt\n xenon filesystem sftp --location localhost:10022 --username xenon --password javagat download hostname.stdout.txt -\n\nBelow are a few more examples of ``slurm submit``:\n\n.. code-block:: bash\n\n # executables that take options prefixed with '-' need special syntax, e.g. 'ls -la'\n xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat \\\n submit --stdout /home/xenon/ls.stdout.txt ls -- -la\n\n # check to see if the output was written to file /home/xenon/ls.stdout.txt\n xenon filesystem sftp --location localhost:10022 --username xenon --password javagat download ls.stdout.txt -\n\n # submit an 'env' job with environment variable MYKEY, and capture standard out so we know it worked\n xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat \\\n submit --stdout /home/xenon/env.stdout.txt --env MYKEY=myvalue /usr/bin/env\n\n # check to see if the output from 'env' was written to file /home/xenon/env.stdout.txt\n xenon filesystem sftp --location localhost:10022 --username xenon --password javagat download env.stdout.txt -\n\n|\n|\n|\n\nCombining filesystems and schedulers\n------------------------------------\n\nSo far, we've used ``xenon`` to manipulate files on the local filesystem, and to run system executables on the remote\nmachine. In typical usage, however, you would use ``xenon`` to run executables or scripts of your own, which means that\nwe need to upload such files from the local system to the remote system.\n\nA typical workflow may thus look like this:\n\n 1. upload input file(s)\n 2. submit job\n 3. download generated output file(s)\n\nUse an editor to create a file ``sleep.sh`` with the following contents (the virtual machine comes with a bunch of editors\nlike ``gedit``, ``leafpad``, and ``nano``, but you can install a different editor from the repositories if you like):\n\n.. literalinclude:: code-tabs/bash/sleep.sh\n :language: bash\n\nYou can test if your file is correct by:\n\n.. code-block:: bash\n\n # last argument is the sleep duration in seconds\n bash sleep.sh 5\n\nWe need to upload ``sleep.sh`` to the remote machine. We can't use ``xenon filesystem file`` like we did before,\nbecause we're copying between file systems, so let's look at what other options are available:\n\n.. code-block:: bash\n\n xenon filesystem --help\n\n # let's try sftp protocol\n xenon filesystem sftp --help\n\n # we're interested in 'upload' for now\n xenon filesystem sftp upload --help\n\nWe'll also need to tell ``xenon`` what location we want to connect to, and what credentials to use. The SLURM Docker\ncontainer we used before is accessible via SFTP using the same location, username and password as before, so let's use\nthat:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/UploadFileLocalToSftpAbsolutePaths.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/UploadFileLocalToSftpAbsolutePaths.java\n :language: java\n :linenos:\n\n .. group-tab:: Python\n\n .. literalinclude:: code-tabs/python/pyxenon_snippets/upload_file_local_to_sftp_absolute_paths.py\n :language: python\n :linenos:\n\nNow that the script is in place, we can submit a ``bash`` job using ``xenon scheduler slurm submit`` like before, taking\nthe newly uploaded ``sleep.sh`` file as input to ``bash``, and using a sleep duration of 60 seconds:\n\n.. code-block:: bash\n\n # step 2: submit job\n xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat \\\n submit --stdout sleep.stdout.txt bash sleep.sh 60\n\n # (should return an identifier for the job)\n\nWith the job running, let's see if it shows up in any of the SLURM queues:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/SlurmJobListGetter.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/SlurmJobListGetter.java\n :language: java\n :linenos:\n\n .. group-tab:: Python\n\n .. literalinclude:: code-tabs/python/pyxenon_snippets/slurm_job_list_getter.py\n :language: python\n :linenos:\n\nWhen we submitted, we did not specify any queues, so the default queue ``mypartition`` was used:\n\n.. code-block:: bash\n\n xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat list --queue mypartition\n # should have the job identifier in it that was printed on the command line\n\n xenon scheduler slurm --location ssh://localhost:10022 --username xenon --password javagat list --queue otherpartition\n # this queue is empty\n\nWith step 1 (upload) and step 2 (submit) covered, step 3 (download) remains:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/DownloadFileSftpToLocalAbsolutePaths.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/DownloadFileSftpToLocalAbsolutePaths.java\n :language: java\n :linenos:\n\n .. group-tab:: Python\n\n .. literalinclude:: code-tabs/python/pyxenon_snippets/download_file_sftp_to_local_absolute_paths.py\n :language: python\n :linenos:\n\nBy this time you may start to consider putting those 3 commands in a script, as follows:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/AllTogetherNowWrong.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/AllTogetherNowWrong.java\n :language: java\n :linenos:\n\nHowever, if you create the script above and run it, you'll find that:\n\n1. Xenon complains about some destination paths already existing.\n2. The script finishes suspiciously quickly;\n\nThe first error is easily avoided by adding a ``--replace`` optional argument after ``upload`` and ``download``, but\nthat does not address the real issue: that of Xenon not waiting for the completion of our sleep job.\n\nNot to worry though, we can use ``xenon scheduler slurm wait`` to wait for jobs to finish. In order to make this work,\nwe do need to capture the identifier for a specific job, otherwise we don't know what to wait for.\n\nAdapt the script as follows and run it:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. literalinclude:: code-tabs/bash/AllTogetherNow.sh\n :language: bash\n\n .. group-tab:: Java\n\n .. literalinclude:: code-tabs/java/src/main/java/nl/esciencecenter/xenon/tutorial/AllTogetherNow.java\n :language: java\n :linenos:\n\n .. group-tab:: Python\n\n .. literalinclude:: code-tabs/python/pyxenon_snippets/all_together_now.py\n :language: python\n :linenos:\n\nAfter about 60 seconds, you should have a local copy of ``sleep.stdout.txt``, with the correct contents this time.\n\nCongratulations -- you have successfully completed the tutorial!\n\nCleanup\n^^^^^^^\n\nUse ``docker ps`` to check the state of the container:\n\n.. code-block:: bash\n\n docker ps\n\nThe last column in the resulting table lists the name of the container. By\ndefault, ``docker`` assigns automatically generated names, like\n``practical_robinson``, ``keen_goodall`` or ``infallible_morse``. You can use\nthis name to stop and remove a container once you're done with it, as follows:\n\n.. code-block:: bash\n\n docker stop practical_robinson\n docker rm practical_robinson\n\n|\n|\n|\n\nWhat's next?\n------------\n\nIf you want, you can continue reading about relevant subjects, or try some of the suggested exercises.\n\nFurther reading\n^^^^^^^^^^^^^^^\n- Xenon's homepage on `GitHub`__\n- Xenon's JavaDoc on `github.io`__\n- PyXenon: The Python interface to Xenon (`github.com`__, `readthedocs.io`__)\n\n__ https://github.com/xenon-middleware/xenon\n__ http://xenon-middleware.github.io/xenon/versions/3.0.4/javadoc\n__ https://github.com/xenon-middleware/pyxenon\n__ http://pyxenon.readthedocs.io/en/latest/\n\nSuggested exercises\n^^^^^^^^^^^^^^^^^^^\n\n- Repeat selected exercises, but test against a physically remote system instead of a Docker container. Requires\n credentials for the remote system.\n- Repeat selected exercises using `WebDAV`__ instead of SFTP. We included the Docker container `xenonmiddleware/webdav`__\n as part of the virtual machine for testing.\n- Use the ``s3`` file adaptor to connect to Amazon's\n `Simple Storage Service`__. Either use the Docker container `xenonmiddleware/s3`__ (included in this virtual machine) for\n testing on your own machine, or use an existing Amazon Web Services account for testing against the real thing.\n\n__ https://en.wikipedia.org/wiki/WebDAV\n__ https://hub.docker.com/r/xenonmiddleware/webdav/\n__ https://aws.amazon.com/s3\n__ https://hub.docker.com/r/xenonmiddleware/s3/\n\n\n|\n|\n|\n|\n|\n|\n\nThis document was generated from `its source files`__ using Sphinx.\n\n\n|\n|\n\n__ https://github.com/xenon-middleware/xenon-tutorial/\n" }, { "alpha_fraction": 0.7547169923782349, "alphanum_fraction": 0.7547169923782349, "avg_line_length": 18.75, "blob_id": "6870e26a0d1ce28238392d2ffa95e8ef7ee9ddfd", "content_id": "de9b6e173a550b216818fa385674919b98670500", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 159, "license_type": "permissive", "max_line_length": 48, "num_lines": 8, "path": "/readthedocs/code-tabs/python/tests/test_slurm_queues_getter.py", "repo_name": "xenon-middleware/xenon-tutorial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pytest\n\nfrom pyxenon_snippets import slurm_queues_getter\n\n\ndef test_slurm_queues_getter():\n slurm_queues_getter.run_example()\n\n" } ]
52
shirota1526064/robosys
https://github.com/shirota1526064/robosys
b5a92816eba80d609205e936c58be77eb71e1b1e
23c7efd6f43a84cff3b650406fa50c0b93663f85
90df1bdf57795cfa577cd3d250c9741d3539e259
refs/heads/master
2021-09-02T08:36:58.131600
2018-01-01T03:00:31
2018-01-01T03:00:31
111,624,560
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.6600000262260437, "avg_line_length": 17.18181800842285, "blob_id": "3b231986c0579c11133a41118a85e5a2cd2d58c4", "content_id": "95bc7e1c72f925c12260799cc6c2fbca6b9b10a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 200, "license_type": "permissive", "max_line_length": 62, "num_lines": 11, "path": "/005/Makefile", "repo_name": "shirota1526064/robosys", "src_encoding": "UTF-8", "text": "TARGET:=myled.ko\n\nall: ${TARGET}\n\nmyled.ko: myled.c\n\tmake -C /usr/src/linux-headers-`uname -r` M=`pwd` V=1 modules\n\nclean:\n\tmake -C /usr/src/linux-headers-`uname -r` M=`pwd` V=1 clean\n\nobj-m:=myled.o\n" }, { "alpha_fraction": 0.6511628031730652, "alphanum_fraction": 0.6744186282157898, "avg_line_length": 13.333333015441895, "blob_id": "bb335b7703a0d366cc58881b99b8e9ce430a6f8d", "content_id": "cfba4cd15751908142c2d3f79e040564e545ab31", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 43, "license_type": "permissive", "max_line_length": 22, "num_lines": 3, "path": "/002/hoge.py", "repo_name": "shirota1526064/robosys", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nprint(\"Give me money\")\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.8717948794364929, "avg_line_length": 12, "blob_id": "a8049a977b0226af10043562d5fa216c6e28ef2a", "content_id": "7467fa31ec4c58f97272427fe86aa8c806e71dd6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 77, "license_type": "permissive", "max_line_length": 23, "num_lines": 3, "path": "/README.md", "repo_name": "shirota1526064/robosys", "src_encoding": "UTF-8", "text": "# robosys2017\n\nロボットシステム学2017において作成したもの\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6833333373069763, "avg_line_length": 6.5, "blob_id": "21f331e89c07535b5c31535a69a38f35f05e1461", "content_id": "999916efa3e375a17cc191400f1aa40fa3dccdcc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 74, "license_type": "permissive", "max_line_length": 14, "num_lines": 8, "path": "/004/exec_sample.bash", "repo_name": "shirota1526064/robosys", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\necho $$\nsleep 30\n\nexec sleep 100\n\necho ここには来ない\n" } ]
4
mawhab/Network-test-script
https://github.com/mawhab/Network-test-script
e7396bb009c875a9fad07cba07f367faed3ea3b1
20463081469d1fba7833fccdf4af7f5a4252faf4
097f9458ca152e91904fc40e28ec61a8fc866683
refs/heads/master
2023-01-22T20:18:38.894750
2020-11-30T18:22:50
2020-11-30T18:22:50
317,309,383
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8315789699554443, "alphanum_fraction": 0.8315789699554443, "avg_line_length": 37, "blob_id": "7983c984aabf0ba5293b750e11c6151064944e7b", "content_id": "8d8fffb604ec3c382613e4639fe69caa9b63dd57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 190, "license_type": "no_license", "max_line_length": 144, "num_lines": 5, "path": "/README.md", "repo_name": "mawhab/Network-test-script", "src_encoding": "UTF-8", "text": "# Network-test-script\n\nThis script tests network availability by visiting router web interface and checking internet state and showing notification when network is up.\n\nMade using Pyautogui\n" }, { "alpha_fraction": 0.6694812774658203, "alphanum_fraction": 0.7141134142875671, "avg_line_length": 22.685714721679688, "blob_id": "bde52ff8067c936d4667bc4ec52bd1ff1777d79b", "content_id": "abdd79427fe0ab21cb4b25769c026d23b39274ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 829, "license_type": "no_license", "max_line_length": 69, "num_lines": 35, "path": "/main.py", "repo_name": "mawhab/Network-test-script", "src_encoding": "UTF-8", "text": "import pyautogui\nimport time\n\nwhite = (255,255,255)\nx,y = 1736,875 # x and y values for chrome position in toolbar\n\n# opning chrome\npyautogui.click(x=x, y=y)\n\ntime.sleep(2)\n# opneing a new tab\npyautogui.hotkey('ctrl', 't') \n\n# going to router web interface\npyautogui.write('192.168.1.1')\npyautogui.press('enter') \n\nx,y = 885, 692 # x and y values for internet unavailable message\n\n# moving mouse to required position\npyautogui.moveTo(x,y)\n\ntime.sleep(1)\n\n# getting colors of required portion\nrgb = pyautogui.screenshot().getpixel((x,y))\n\n# checking if internet is good\nwhile rgb != white:\n pyautogui.click(x=88, y=44) # refreshing page\n pyautogui.moveTo(x,y) # moving back to position\n time.sleep(3)\n rgb = pyautogui.screenshot().getpixel((x,y))\n\npyautogui.alert(text='Internet is up', title='internet', button='Ok')\n" } ]
2
olidare/quiz
https://github.com/olidare/quiz
2919305f7cdb545ddd2616511ed4ed393dbcff9c
18ec39555ac9499bdab6be2acc2335771de167f1
18f0f65b113c6e3c917176e14875b9e08af400f4
refs/heads/master
2021-04-27T09:43:54.141534
2018-02-22T19:05:27
2018-02-22T19:05:27
122,521,224
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5356732606887817, "alphanum_fraction": 0.5542069673538208, "avg_line_length": 42.55714416503906, "blob_id": "0fb5e041170360ce801f24cfe5e1d23535c32e63", "content_id": "63cdc63f72e9f577b37e0a17c749ab40ded657ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6097, "license_type": "no_license", "max_line_length": 116, "num_lines": 140, "path": "/questions.py", "repo_name": "olidare/quiz", "src_encoding": "UTF-8", "text": "from fileread import FileRead\nfrom random import shuffle\nfrom layout import Layout\nimport time\nimport random\nimport pygame\n\nclass Question:\n backgroundColour, backgroundBonus = (30, 144, 255), (220,20,60)\n layout = Layout()\n mainQuiz = FileRead()\n mainQuiz.filename = \"testfile.txt\"\n attemptMain, mainLength = mainQuiz.readText()\n bonusQuiz = FileRead()\n bonusQuiz.filename = \"bonus.txt\"\n attemptBonus, bonusLength = bonusQuiz.readText()\n clock = pygame.time.Clock()\n\n # Function for creating the standard questions\n def normal(self, list, finalScore, question_count, lives):\n for i in list:\n question_count += 1\n count, questionMain, answersMain, correctAnswerMain, \\\n rand1, rand2 = self.initialise_normal(i)\n while (count > 0):\n count -= 1\n finalScore -=3\n userAnswer = self.controls()\n # finds the index of where the correct answer is placed\n answersMainIndex = (1 + answersMain.index(correctAnswerMain))\n self.clock.tick(30)\n if (userAnswer != None):\n print(\"answersmain index is : \" +str(answersMainIndex))\n if (int(userAnswer) == int(answersMainIndex)):\n self.layout.message_display(\"Correct\", 1, 60)\n finalScore += 2500\n break\n else:\n self.layout.message_display(\"Incorrect, answer was: \" + str(correctAnswerMain), 5, 30)\n finalScore -= 100\n lives -=1\n return finalScore, question_count, lives\n # puts the questions and answers into layout class to be displayed in game\n if (count%25==0):\n self.layout.questionandAnswers(questionMain, answersMain[0], answersMain[1], answersMain[2],\n answersMain[3], lives, finalScore,self.time_convert(count),\n self.backgroundColour)\n if (count == 0):\n self.layout.message_display(\"Took too long, answer was: \" + str(correctAnswerMain), 5, 30)\n lives -= 1\n break\n\n return finalScore, question_count, lives\n\n # Function for creating the bonus questions\n def bonus(self, bonuspoints, finalScore, lives):\n for b in bonuspoints:\n count, questionBonus, answersBonus, \\\n correctAnswerBonus = self.initialise_bonus(b)\n while (count > 0):\n count -= 1\n userAnswer = self.controls()\n # finds the index of where the correct answer is placed\n answersMainIndex = (1 + answersBonus.index(correctAnswerBonus))\n self.clock.tick(30)\n if (userAnswer != None):\n #if user input matches correct answer\n if (int(userAnswer) == int(answersMainIndex)):\n self.layout.message_display(\"Correct\", 1, 60)\n finalScore += 5000\n break\n else:\n self.layout.message_display(\"Incorrect, answer was: \" + str(correctAnswerBonus), 5, 30)\n break\n if (count%25==0):\n # puts the questions and answers into layout class to be displayed in game\n self.layout.questionandAnswers(questionBonus, answersBonus[0], answersBonus[1], answersBonus[2],\n answersBonus[3], lives, finalScore, self.time_convert(count),\n self.backgroundBonus)\n return finalScore\n\n #returns a corresponding value depending on key pressed\n def controls(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_1:\n return '1'\n elif event.key == pygame.K_2:\n return '2'\n elif event.key == pygame.K_3:\n return '3'\n elif event.key == pygame.K_4:\n return '4'\n\n def randomiseList(self, x):\n list = random.sample(xrange(0, x), x-1)\n return list\n\n #selects a specific number of values to be used in a list\n def selectedRange(self, list, start, end):\n updatedList = []\n for m in list[start: end]:\n updatedList.append(m)\n return updatedList\n\n def clearValues(self, list, list2):\n del list[:]\n del list2[:]\n\n def time_convert(self, time):\n converted_vale = time/30\n return converted_vale\n\n def fifty_fifty(self, answersMain, value1, value2):\n answersMain[value1] = \"\"\n answersMain[value2] = \"\"\n\n\n def initialise_normal(self, i):\n count = 750\n questionMain = self.attemptMain.keys()[i - 1] # Extracts the Question from the Dictionary\n answersMain = (self.attemptMain.values()[i - 1]) # Extracts the answers from the Dictionary\n correctAnswerMain = answersMain[0] # records the correct answer\n random1 = answersMain[1]\n random2 = answersMain[2]\n shuffle(answersMain)\n rand1 = (answersMain.index(random1))\n rand2 = (answersMain.index(random2))\n return count, questionMain, answersMain, correctAnswerMain, int(rand1), int(rand2)\n\n def initialise_bonus(self, b):\n count = 1000\n questionBonus = self.attemptBonus.keys()[b - 1] # Extracts the Question from the Dictionary\n answersBonus = self.attemptBonus.values()[b - 1] # Extracts the answers from the Dictionary\n correctAnswerBonus = answersBonus[0] # records the correct answer\n shuffle(answersBonus)\n return count, questionBonus, answersBonus, correctAnswerBonus" }, { "alpha_fraction": 0.5522620677947998, "alphanum_fraction": 0.5678626894950867, "avg_line_length": 39.914894104003906, "blob_id": "4e865ac96b9c93aa3990fa0b92077302e97c9413", "content_id": "004a5557ba0839231189382ba6c760f7813af882", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1923, "license_type": "no_license", "max_line_length": 122, "num_lines": 47, "path": "/leaderboard.py", "repo_name": "olidare/quiz", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport Tkinter as tk\nimport csv\n\nclass Leaderboard:\n\n df = pd.read_csv('leaderboard.csv')\n #sort the the leaderboard csv and get the smallest value\n smallest_value = np.sort(df['Score'].unique())[:1]\n\n def add_value(self, df, username, highscore):\n df2 = pd.DataFrame({'Username': [username], 'Score': [highscore]})\n return df2\n\n def sort_values(self, df):\n df = df.sort_values(by='Score', ascending=False)\n df = df.reset_index(drop=True)\n return df\n\n def updated_leaderboard(self, df,username, highscore):\n df2 = self.add_value(df, username, highscore) #creates a new leaderboard with the new username and score\n sorted_values = self.df.sort_values(by='Score', ascending=False).head(25) #Resorts the main table\n b = pd.concat([sorted_values, df2]) #merges the two leaderboards together\n b = b[['Username', 'Score']] #Puts the columns in the correct order\n b = self.sort_values(b) #Sorts the leaderboard with the new value\n b.to_csv('leaderboard.csv') #updates the CSV file with the new leaderboard\n\n\t#display function utilised code from https://stackoverflow.com/questions/42748343/how-to-show-csv-file-in-a-grid/42748973\n def leader_board(self):\n root = tk.Tk()\n # open file\n with open(\"leaderboard.csv\") as file:\n reader = csv.reader(file)\n # r and c tell us where to grid the labels\n r = 0\n for col in reader:\n c = 0\n for row in col:\n # styling\n label = tk.Label(root, width=12, height=2, \\\n text=row, relief=tk.RIDGE)\n label.grid(row=r, column=c)\n c += 1\n r += 1\n\n root.mainloop()\n" }, { "alpha_fraction": 0.6022913455963135, "alphanum_fraction": 0.6333878636360168, "avg_line_length": 28.516128540039062, "blob_id": "cec3583fe0f96852373bc367356933594e17187c", "content_id": "871559f66d21c05595dfa91ae3c62f6f1e476e35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1833, "license_type": "no_license", "max_line_length": 84, "num_lines": 62, "path": "/inputbox.py", "repo_name": "olidare/quiz", "src_encoding": "UTF-8", "text": "''' This class taken from Stack Overflow, code made by Timothy Downs\n\nThis class opens a screen which allows the user to enter information\ninto a textbox and the data is recorded as a string which can then be\nused elsewhere.\n\nIn this case, it is used to record a username for the leaderboard.\n'''\n\nimport pygame, pygame.font, pygame.event, pygame.draw, string\nfrom pygame.locals import *\n\nbackgroundColour = (30, 144, 255)\nyellow = (255, 255, 0)\n\ndef get_key():\n while 1:\n event = pygame.event.poll()\n if event.type == KEYDOWN:\n return event.key\n else:\n pass\n\ndef display_box(screen, message):\n \"Print a message in a box in the middle of the screen\"\n font = pygame.font.Font(None,24)\n\n pygame.draw.rect(screen, (0,0,0),\n ((screen.get_width() / 3), (screen.get_height() / 3), 400,80), 0)\n\n pygame.draw.rect(screen, (backgroundColour),\n ((screen.get_width() / 3),(screen.get_height() / 3), 408,96), 1)\n if len(message) != 0:\n screen.blit(font.render(message, 1, (yellow)),\n ((screen.get_width() / 3 +5), (screen.get_height() / 3) + 10))\n\n pygame.display.flip()\n\n\n\ndef ask(screen, question):\n \"ask(screen, question) -> answer\"\n pygame.font.init()\n current_string = []\n display_box(screen, question + \": \" + string.join(current_string,\"\"))\n while 1:\n inkey = get_key()\n if inkey == K_BACKSPACE:\n current_string = current_string[0:-1]\n elif inkey == K_RETURN:\n break\n elif inkey == K_MINUS:\n current_string.append(\"_\")\n elif inkey <= 127:\n current_string.append(chr(inkey))\n display_box(screen, question + \": \" + string.join(current_string,\"\"))\n return string.join(current_string,\"\")\n\ndef main():\n screen = pygame.display.set_mode((1200,900))\n print ask(screen, \"UserName\") + \" was entered\"\n #main.game_intro()\n\n\n\n" }, { "alpha_fraction": 0.5493594408035278, "alphanum_fraction": 0.5538809299468994, "avg_line_length": 36.85714340209961, "blob_id": "deb49af308248007c7f56d455193f667b0e9327f", "content_id": "1a22ebc6178288bccc1890762c917b8a72723fca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1327, "license_type": "no_license", "max_line_length": 94, "num_lines": 35, "path": "/fileread.py", "repo_name": "olidare/quiz", "src_encoding": "UTF-8", "text": "from random import shuffle\nimport collections\n\n\nclass FileRead:\n filename = \"\"\n\n #this function reads .txt file into a dictionary\n def readText(self):\n QandA = collections.OrderedDict()\n numberofLines = 0\n with open(self.filename, \"r\") as readfile:\n for line in readfile:\n numberofLines += 1\n content = line.split(\"`\") #splits the lines with \"`\"\n question = content[0] #first split is always the question\n answers = []\n #for the second to fifth splits, they are appended to a list\n for index, line in enumerate(content):\n if (index >= 1 and index <5):\n answers.append(line)\n #Question and the list of answers are updated to an empty QandA dictionary\n QandA.update({question: answers})\n return QandA, numberofLines\n\n #simple fileread which appends a .txt file to a list\n def readFact(self):\n facts = []\n with open(self.filename, \"r\") as readfile:\n for line in readfile:\n content = line.split(\"`\")\n for c in content:\n facts.append(c)\n shuffle(facts)\n return facts[0] #function returns a random fact every time.\n\n\n" }, { "alpha_fraction": 0.590395450592041, "alphanum_fraction": 0.6054614186286926, "avg_line_length": 39.730770111083984, "blob_id": "d5b78ee6d6290efab9203d57dd6cd0fc7d52184f", "content_id": "75d4f9f4c5b5fe9b3afb0219bbaca006b201bd83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 91, "num_lines": 26, "path": "/button.py", "repo_name": "olidare/quiz", "src_encoding": "UTF-8", "text": "import pygame\n\nclass Button:\n yellow = (255, 255, 0)\n\n def text_objects(self,text, font):\n textSurface = font.render(text, True, self.yellow)\n return textSurface, textSurface.get_rect()\n\n def button(self,Screen, msg,x,y,w,h,ic,ac,action=None):\n mouse = pygame.mouse.get_pos() #gets the coordinates of the mouse\n click = pygame.mouse.get_pressed() # returns a [0] value when clicked\n\n #if mouse hovers between correct coordinates of button change colour\n if x+w > mouse[0] > x and y+h > mouse[1] > y:\n pygame.draw.rect(Screen, ac,(x,y,w,h))\n #if mouse is clicked within coordinates, do an action\n if click[0] == 1 and action != None:\n action()\n else:\n pygame.draw.rect(Screen, ic,(x,y,w,h)) #else button just stay in a normal state\n\n smallText = pygame.font.SysFont(\"monospace\",20)\n textSurf, textRect = self.text_objects(msg, smallText)\n textRect.center = ( (x+(w/2)), (y+(h/2)) )\n Screen.blit(textSurf, textRect)\n\n\n\n" }, { "alpha_fraction": 0.577311098575592, "alphanum_fraction": 0.62363600730896, "avg_line_length": 47.54999923706055, "blob_id": "f0afe99c1103065868246d10946d000f114164f7", "content_id": "3a26608f6c4c2d29a2f1a691a4040f9796b5a39a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4857, "license_type": "no_license", "max_line_length": 130, "num_lines": 100, "path": "/layout.py", "repo_name": "olidare/quiz", "src_encoding": "UTF-8", "text": "from textWrapper import TextRectException\nimport pygame\nimport time\nfrom button import Button\n\nclass Layout:\n dw, dh = 1380,1000\n backgroundColour = (30, 144, 255)\n yellow = (255, 255, 0)\n green, bright_green = (0, 200, 0), (0, 255, 0)\n red,bright_red = (200, 0, 0), (255, 0, 0)\n gameDisplay = pygame.display.set_mode((dw, dh))\n button = Button()\n textWrap = TextRectException()\n\n #Puts all of the 4 answers into 4 different textboxes and draws borders around them\n def answer1(self,text, colour):\n self.button.button(self.gameDisplay, \"1: \", (self.dw * 0.15), (self.dh * 0.5), 60, 50, self.green, self.bright_green,None)\n self.textBox(self.gameDisplay, self.bright_green, (self.dw * 0.22), (self.dh * 0.5), (self.dw * 0.28),(self.dh * 0.25))\n self.questionBox(text,(self.dw * 0.23), (self.dh * 0.51), (self.dw * 0.27), (self.dh * 0.24), 25, colour)\n\n def answer2(self,text, colour):\n self.button.button(self.gameDisplay,\"2: \", (self.dw * 0.52), (self.dh * 0.5), 60, 50, self.green, self.bright_green,None)\n self.textBox(self.gameDisplay, self.bright_green, (self.dw * 0.6), (self.dh * 0.5), (self.dw * 0.28),(self.dh * 0.25))\n self.questionBox(text,(self.dw * 0.61), (self.dh * 0.51), (self.dw * 0.27), (self.dh * 0.23), 25, colour)\n\n def answer3(self,text, colour):\n self.button.button(self.gameDisplay,\"3: \", (self.dw * 0.15), (self.dh * 0.75), 60, 50, self.green, self.bright_green,None)\n self.textBox(self.gameDisplay, self.bright_green, (self.dw * 0.22), (self.dh * 0.75), (self.dw * 0.28),(self.dh * 0.24))\n self.questionBox(text,(self.dw * 0.23), (self.dh * 0.76), (self.dw * 0.27), (self.dh * 0.22), 25, colour)\n\n def answer4(self,text, colour):\n self.button.button(self.gameDisplay,\"4: \", (self.dw * 0.52), (self.dh * 0.75), 60, 50, self.green, self.bright_green,None)\n self.textBox(self.gameDisplay, self.bright_green, (self.dw * 0.6), (self.dh * 0.75), (self.dw * 0.28),(self.dh * 0.24))\n self.questionBox(text,(self.dw * 0.61), (self.dh * 0.76), (self.dw * 0.27), (self.dh * 0.22), 25, colour)\n\n #Puts the question, answers, lives and score on the pygame display\n def questionandAnswers(self, Question, a,b,c,d, lives,finalScore,time, colour):\n self.gameDisplay.fill(colour)\n self.questionBox(Question, (self.dw / 4), (self.dh / 8), (self.dw * 0.6), (self.dh * 0.35), 40, colour)\n self.answer1(a, colour)\n self.answer2(b, colour)\n self.answer3(c, colour)\n self.answer4(d, colour)\n self.lives_remaining(lives)\n self.score(finalScore)\n self.timing(time)\n pygame.display.update()\n\n def score(self, score):\n my_font = pygame.font.Font(\"Quicksand-Regular.otf\", 32)\n text = my_font.render(\"Score: \" + str(score), True, self.yellow)\n self.gameDisplay.blit(text, [0, 0])\n\n def timing(self, time):\n my_font = pygame.font.Font(\"Quicksand-Regular.otf\", 32)\n text = my_font.render(\"Time: \" + str(time), True, self.yellow)\n self.gameDisplay.blit(text, [(0.5*self.dw), 0])\n pygame.display.update()\n\n def lives_remaining(self, lives):\n my_font = pygame.font.Font(\"Quicksand-Regular.otf\", 32)\n text = my_font.render(\"Lives: \" + str(lives), True, self.yellow)\n self.gameDisplay.blit(text, [(0.85*self.dw), 0])\n\n def questionBox(self,text, x,y,w,h, font_size, colour):\n my_font = pygame.font.Font(\"Quicksand-Regular.otf\", font_size)\n my_rect = pygame.Rect(x,y,w,h)\n rendered_text = self.textWrap.render_textrect(text, my_font, my_rect, self.yellow, colour, 0)\n self.gameDisplay.blit(rendered_text, my_rect.topleft)\n\n def textBox(self,screen, colour,x,y,h,w):\n thickness = 2\n pygame.draw.rect(screen, colour, (x,y, h, w),thickness)\n\n def correct(self,string):\n self.message_display(string)\n\n def text_objects(self, text, font):\n textSurface = font.render(text, True, self.yellow)\n return textSurface, textSurface.get_rect()\n\n #Message pops up for a certain amount of time\n def message_display(self, text, display_length, text_size):\n largeText = pygame.font.SysFont(\"monospace\", text_size)\n TextSurf, TextRect = self.text_objects(text, largeText)\n TextRect.center = ((self.dw / 2), (self.dh * 0.45))\n self.gameDisplay.blit(TextSurf, TextRect)\n\n pygame.display.update()\n\n time.sleep(display_length)\n self.gameDisplay.fill(self.backgroundColour)\n\n #Used for headers and titles\n def message_Title(self, text, x, y, text_size):\n largeText = pygame.font.SysFont(\"monospace\", text_size)\n TextSurf, TextRect = self.text_objects(text, largeText)\n TextRect.center = ((x), (y))\n self.gameDisplay.blit(TextSurf, TextRect)\n\n\n" }, { "alpha_fraction": 0.5043389201164246, "alphanum_fraction": 0.5456866025924683, "avg_line_length": 42.05494689941406, "blob_id": "61edb41e9a3314410031aa74ddc60416cdfa15f3", "content_id": "61fc66e33ee2708097dd3dcec6854f1796768e89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3918, "license_type": "no_license", "max_line_length": 143, "num_lines": 91, "path": "/main.py", "repo_name": "olidare/quiz", "src_encoding": "UTF-8", "text": "import pygame\nimport time\nfrom game import Game\nfrom button import *\nfrom leaderboard import Leaderboard\nfrom layout import Layout\n\nclass Main:\n dw, dh = 1380,1000\n gameDisplay = pygame.display.set_mode((dw, dh))\n clock = pygame.time.Clock()\n backgroundColour = (30, 144, 255)\n yellow, light_yellow = (200,200,0), (255,255,0)\n red,bright_red = (200, 0, 0), (255, 0, 0)\n green, bright_green = (0, 200, 0), (0, 255, 0)\n lb = Leaderboard()\n layout = Layout()\n button = Button()\n game = Game()\n\n def quitgame(self):\n pygame.quit()\n quit()\n\n def start_game(self):\n intro = True\n while intro:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.quitgame()\n\n self.main_setup()\n self.clock.tick(15)\n\n def game_instructions(self):\n gcont = True\n while gcont:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.quitgame()\n\n self.intro_setup()\n self.clock.tick(15)\n\n\n def main_setup(self):\n self.gameDisplay.fill(self.backgroundColour)\n self.layout.message_Title(\"Welcome to the \", (self.dw / 2), (self.dh * 2 / 8), 50)\n self.layout.message_Title(\"Charity Quiz Game!\", (self.dw / 2), (self.dh * 3 / 8), 50)\n\n self.button.button(self.gameDisplay, \"Start Game!\", (self.dw * 1 / 8), (self.dh * 0.75), 150, 50, self.green,\n self.bright_green, self.game.game_loop)\n self.button.button(self.gameDisplay, \"Leaderboard\", (self.dw * 3 / 8), (self.dh * 0.75), 150, 50, self.green,\n self.bright_green, self.lb.leader_board)\n self.button.button(self.gameDisplay, \"Instructions\", (self.dw * 5 / 8), (self.dh * 0.75), 150, 50, self.green,\n self.bright_green, self.game_instructions)\n self.button.button(self.gameDisplay, \"Quit\", (self.dw * 7 / 8), (self.dh * 0.75), 80, 50, self.red, self.bright_red,\n self.quitgame)\n pygame.display.update()\n\n\n def intro_setup(self):\n self.gameDisplay.fill(self.backgroundColour)\n self.layout.message_Title(\"Instructions: \", (self.dw / 2), (self.dh * 1 / 9), 55)\n self.layout.message_Title(\":- Multiple choice quiz game, controlled by keys 1-4.\", (self.dw / 2),\n (self.dh * 2 / 9), 25)\n self.layout.message_Title(\":- Game ends when lives run out, lives are lost if a normal blue question is answered wrong\", (self.dw / 2),\n (self.dh * 3 /9 ), 25)\n self.layout.message_Title(\":- 25 seconds to answer each normal question and points can be gained for speed. \", (self.dw / 2),\n (self.dh * 4 / 9), 25)\n self.layout.message_Title(\":- Red Background indicates it's a bonus question\", (self.dw / 2),\n (self.dh * 5 / 9), 25)\n self.layout.message_Title(\":- Lives and points are not lost for Bonus Questions\", (self.dw / 2),\n (self.dh * 6 / 9), 25)\n self.layout.message_Title(\":- Bonus Questions in red are designed for raising charity awareness\", (self.dw / 2),\n (self.dh * 7 / 9), 25)\n self.button.button(self.gameDisplay, \"Main\", (self.dw * 2 / 8), (self.dh * 0.85), 150, 50,\n self.yellow,\n self.light_yellow, self.start_game)\n self.button.button(self.gameDisplay, \"quit\", (self.dw * 5 / 8), (self.dh * 0.85), 150, 50, self.red,\n self.bright_red,\n self.quitgame)\n pygame.display.update()\n\n\npygame.init()\npygame.display.set_caption(' Quiz')\n\n#To run code without linking it to arduino\nrun = Main()\nrun.start_game()\n" }, { "alpha_fraction": 0.6311787366867065, "alphanum_fraction": 0.6539924144744873, "avg_line_length": 22.909090042114258, "blob_id": "655948302a658c4a8c17bac7e0637637861dc5dc", "content_id": "4e83adcc645e94f50e15c2a72952c8477ba54a94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 263, "license_type": "no_license", "max_line_length": 44, "num_lines": 11, "path": "/test_game.py", "repo_name": "olidare/quiz", "src_encoding": "UTF-8", "text": "import unittest\nfrom game import Game\nclass test_game(unittest.TestCase):\n game = Game()\n\n def test_add(self):\n result = self.game.add(10,5)\n self.assertEqual(result,15)\n\n def test_update(self):\n self.assertEqual(self.game.lives, 2)\n" }, { "alpha_fraction": 0.7473233342170715, "alphanum_fraction": 0.7665953040122986, "avg_line_length": 34.846153259277344, "blob_id": "a0c5c81259c1c8454a0c7d58c6b63286ea729610", "content_id": "c958924262666589c8ff6a816dbef555184798ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 467, "license_type": "no_license", "max_line_length": 71, "num_lines": 13, "path": "/readme.txt", "repo_name": "olidare/quiz", "src_encoding": "UTF-8", "text": "Programmes required to install in order to have the working prototype. \n\nTo run the game you will need to: \n\nDownload python 2.7: https://www.python.org/downloads/ \nDownload Pygame for python 2.7: http://www.pygame.org/download.shtml \nDownload Pandas: https://pypi.python.org/pypi/pandas \nDownload Tkinter: https://pypi.python.org/pypi/EasyTkinter/1.1.0 \nDownload PySerial: https://pypi.python.org/pypi/pyserial/2.7 \n\nTo compile and run in terminal:\n\npython main.py\n\n" }, { "alpha_fraction": 0.6126984357833862, "alphanum_fraction": 0.6299319863319397, "avg_line_length": 41.133758544921875, "blob_id": "0df91b8b05015095dd6f593ffa8081e9c454f263", "content_id": "3623c4e44c2c2255dae44c0c0495cdc55b87f59e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6615, "license_type": "no_license", "max_line_length": 115, "num_lines": 157, "path": "/game.py", "repo_name": "olidare/quiz", "src_encoding": "UTF-8", "text": "import pygame\nimport random\nimport inputbox\nimport time\nfrom questions import Question\nfrom layout import Layout\nfrom leaderboard import Leaderboard\nfrom fileread import FileRead\nfrom button import Button\n\nclass Game:\n dw, dh = 1380,1000\n backgroundColour, backgroundBonus = (30, 144, 255), (220,20,60)\n yellow, bright_red = (255, 255, 0), (255, 0, 0)\n green, bright_green = (0, 200, 0), (0, 255, 0)\n finalScore = 3000\n question_count = 0\n lives = 3\n gameDisplay = pygame.display.set_mode((dw, dh))\n clock = pygame.time.Clock()\n question = Question()\n layout = Layout()\n lb = Leaderboard()\n button = Button()\n\n def game_loop(self):\n #initialises the original scores\n gameExit, self.lives = False, 3\n mainIndex, bonusIndex, selectedQuestions,\\\n selectedBonus, mainFreq, bonusFreq = self.initialiseGame()\n # self.getRandomFact()\n while not gameExit:\n self.respawnValues()\n if ((self.lives == 0)): #if out of lives, game over\n self.verifyScore()\n break\n if (self.question_count >20): #if completed all of the questions, game over\n self.layout.message_display(\"Congratulations, you've completed the quiz! finalscore is: \"\n + str(self.finalScore), 8, 30)\n self.verifyScore()\n break\n else:\n self.getNextQuestion(selectedQuestions) #Else load more normal questions\n if(self.lives > 0):\n self.getBonus(selectedBonus) #load a bonus question if lives still remain\n else:\n self.verifyScore() #if no lives remain, compare score to existing leaderboard scores\n break\n #This updates all of the information so more questions can be loaded\n mainFreq, bonusFreq, mainIndex, bonusIndex, selectedQuestions, selectedBonus = \\\n self.updateValues(mainFreq, bonusFreq, mainIndex, bonusIndex, selectedQuestions, selectedBonus)\n self.post_game()\n\n #Screen after completing game, there is no button to play another round\n def post_game(self):\n gcont = True\n while gcont:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.quitgame()\n\n self.post_game_screen()\n self.clock.tick(15)\n\n\n def post_game_screen(self):\n self.gameDisplay.fill(self.backgroundColour)\n\n self.layout.message_Title(\"Thanks for donating\", (self.dw / 2), (self.dh * 2 / 8), 50)\n self.layout.message_Title(\"and playing!\", (self.dw / 2), (self.dh * 3 / 8), 50)\n self.button.button(self.gameDisplay, \"Leaderboard\", (self.dw * 2 / 8), (self.dh * 0.85), 150, 50,\n self.green,\n self.bright_green, self.lb.leader_board)\n self.button.button(self.gameDisplay, \"quit\", (self.dw * 5 / 8), (self.dh * 0.85), 150, 50, self.bright_red,\n self.bright_red,\n self.quitgame)\n pygame.display.update()\n\n\n\n def updateValues(self, mainFreq, bonusFreq, mainIndex, bonusIndex, selectedQuestions, selectedBonus):\n\n #removes previous indexes in the list\n self.question.clearValues(selectedQuestions, selectedBonus)\n\n #moves indexes along the dictionary so they ask the next questions in order\n mainStart = mainFreq\n mainFreq = mainFreq + random.randint(3,5) #will be a random number of questions between 3 and 5\n bonusStart = bonusFreq\n bonusFreq += 1\n\n selectedQuestions = self.question.selectedRange(mainIndex, mainStart, mainFreq)\n selectedBonus = self.question.selectedRange(bonusIndex, bonusStart, bonusFreq)\n\n return mainFreq, bonusFreq, mainIndex, bonusIndex, selectedQuestions, selectedBonus\n\n #calls the next standard questions\n def getNextQuestion(self, selectedQuestions):\n self.layout.score(self.finalScore)\n self.layout.lives_remaining(self.lives)\n self.finalScore, self.question_count, self.lives = self.question.normal(selectedQuestions, self.finalScore,\n self.question_count, self.lives)\n #gets a fact for the start of the game by reading a .txt file\n def getRandomFact(self):\n rfact = FileRead()\n rfact.filename = \"fact.txt\"\n randomValue = rfact.readFact()\n\n self.gameDisplay.fill(self.backgroundColour)\n #insert a fact from the fact.txt file into the display text box\n self.layout.questionBox(randomValue, (self.dw / 4), (self.dh / 8),\n (self.dw * 0.6), (self.dh * 0.65), 40, self.backgroundColour)\n pygame.display.update()\n time.sleep(7)\n\n def initialiseGame(self):\n mainStart, bonusStart, bonusFreq = 0, 0, 1\n mainFreq = random.randint(3, 5)\n\n #randomises the indexes of the Dictionary\n mainIndex = self.question.randomiseList(self.question.mainLength)\n bonusIndex = self.question.randomiseList(self.question.bonusLength)\n\n #gets a selected range of questions\n selectedQuestions = self.question.selectedRange(mainIndex, mainStart, mainFreq)\n selectedBonus = self.question.selectedRange(bonusIndex, bonusStart, bonusFreq)\n\n return mainIndex, bonusIndex, selectedQuestions, selectedBonus, mainFreq, bonusFreq\n\n def respawnValues(self):\n self.gameDisplay.fill(self.backgroundColour)\n self.layout.score(self.finalScore)\n self.layout.lives_remaining(self.lives)\n\n #calls the bonus questions\n def getBonus(self, selectedBonus):\n self.gameDisplay.fill(self.backgroundColour)\n self.layout.message_display(\"Bonus Question\", 1, 60)\n self.gameDisplay.fill(self.backgroundBonus)\n self.finalScore = self.question.bonus(selectedBonus, self.finalScore, self.lives)\n\n #If score is higher than the lowest value in the leaderboard, ask for username\n def verifyScore(self):\n if (self.finalScore > self.lb.smallest_value):\n self.new_highscore(self.finalScore)\n\n\n def new_highscore(self, finalscore):\n #Gets username\n username = inputbox.ask(self.gameDisplay,\n 'New highscore, enter username: ')\n #puts username and score into leaderboard\n self.lb.updated_leaderboard(self.lb.df, username, self.finalScore)\n\n def quitgame(self):\n pygame.quit()\n quit()\n" } ]
10
tconsta/todo
https://github.com/tconsta/todo
c4ef5b87a04ec9ec2b15f4f48fb7bd99c8dbc564
50c0cf49340f2c4f879ca9b1923f8fdfe42d0f8a
fb1a06e420b6717da6c5ca60d2bb7449a631c4fe
refs/heads/master
2023-08-13T03:16:55.583772
2021-09-13T04:09:24
2021-09-13T04:09:24
363,367,270
0
0
null
2021-05-01T09:07:33
2021-05-05T14:36:50
2021-09-13T04:09:24
HTML
[ { "alpha_fraction": 0.5058823823928833, "alphanum_fraction": 0.699999988079071, "avg_line_length": 16, "blob_id": "e2251563938cf36dc59591c1ec7c9719ad54a1ea", "content_id": "0514ced33fa104749b3be69357917f090ccc7a4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 170, "license_type": "no_license", "max_line_length": 27, "num_lines": 10, "path": "/requirements.txt", "repo_name": "tconsta/todo", "src_encoding": "UTF-8", "text": "asgiref==3.3.4\nDjango==3.2\ndjango-widget-tweaks==1.4.8\nflake8==3.9.1\nmccabe==0.6.1\npsycopg2-binary==2.8.6\npycodestyle==2.7.0\npyflakes==2.3.1\npytz==2021.1\nsqlparse==0.4.2\n" }, { "alpha_fraction": 0.6552631855010986, "alphanum_fraction": 0.6552631855010986, "avg_line_length": 20.11111068725586, "blob_id": "69c4222413ea6844c8164f206c3c5ca594c51c99", "content_id": "1c42423087bec2a6cc50cfe659ab183bcada8d23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 760, "license_type": "no_license", "max_line_length": 50, "num_lines": 36, "path": "/app/views.py", "repo_name": "tconsta/todo", "src_encoding": "UTF-8", "text": "from django.views import generic\nfrom django.shortcuts import redirect\nfrom .models import Task\n\n\nclass TaskListView(generic.ListView):\n model = Task\n ordering = ['-created']\n\n\nclass TaskCreate(generic.CreateView):\n model = Task\n fields = ['title', 'description']\n template_name = 'app/task_create.html'\n success_url = '/'\n\n\nclass TaskDelete(generic.DeleteView):\n model = Task\n success_url = '/'\n\n\nclass TaskUpdate(generic.UpdateView):\n model = Task\n fields = ['title', 'description', 'completed']\n success_url = '/'\n\n\ndef done_undone(request, pk):\n task = Task.objects.get(pk=pk)\n if task.completed is True:\n task.completed = False\n else:\n task.completed = True\n task.save()\n return redirect('/')\n" }, { "alpha_fraction": 0.5925925970077515, "alphanum_fraction": 0.605555534362793, "avg_line_length": 35, "blob_id": "9f3c59b6b746d10e4e70aa96e5b73719dc9fad5a", "content_id": "f08119ee32c9ebaaa6172c084b861470ca10befa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 79, "num_lines": 15, "path": "/app/models.py", "repo_name": "tconsta/todo", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Task(models.Model):\n \"\"\"Model representing a task.\"\"\"\n title = models.CharField(max_length=200)\n description = models.TextField(max_length=1000,\n help_text='Enter a description of the task',\n null=True, blank=True)\n created = models.DateTimeField(auto_now_add=True)\n completed = models.BooleanField(default=False)\n\n def __str__(self):\n \"\"\"String for representing the Model object.\"\"\"\n return self.title\n" }, { "alpha_fraction": 0.7243816256523132, "alphanum_fraction": 0.7385159134864807, "avg_line_length": 22.58333396911621, "blob_id": "47a48b7093ebe99eb5e5c775f9a7c5a922ce7dae", "content_id": "1db21e0264774df3df748e5909d798bb578466e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 283, "license_type": "no_license", "max_line_length": 71, "num_lines": 12, "path": "/README.md", "repo_name": "tconsta/todo", "src_encoding": "UTF-8", "text": "# pretty simple web app\n![demo](https://raw.githubusercontent.com/tconsta/todo/master/demo.gif)\n\n# check it out:\n```\ngit clone https://github.com/tconsta/todo.git\ncd todo && docker-compose up\n\ndocker exec -it APP_CONTAINER_ID bash\npython manage.py migrate\n```\nhttp://localhost:8000/\n" }, { "alpha_fraction": 0.6775362491607666, "alphanum_fraction": 0.6847826242446899, "avg_line_length": 38.42856979370117, "blob_id": "798a77335031948e6517ed8688a4a399ffe1f077", "content_id": "8a67a0b698a781e87c1380572fd844d5a7654079", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1104, "license_type": "no_license", "max_line_length": 77, "num_lines": 28, "path": "/todo/urls.py", "repo_name": "tconsta/todo", "src_encoding": "UTF-8", "text": "\"\"\"todo URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\n\nfrom app import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.TaskListView.as_view()),\n path('add/', views.TaskCreate.as_view(), name='task_create'),\n path('<int:pk>/delete/', views.TaskDelete.as_view(), name='task_delete'),\n path('<int:pk>/update/', views.TaskUpdate.as_view(), name='task_update'),\n path('<int:pk>/undone/', views.done_undone, name='task_undone'),\n]\n" }, { "alpha_fraction": 0.5658482313156128, "alphanum_fraction": 0.5680803656578064, "avg_line_length": 31, "blob_id": "2c206e2a5864824663c4f970b6915902344d11e0", "content_id": "25a20d3fc555cacfedfecf82457e462aa625b5fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 896, "license_type": "no_license", "max_line_length": 76, "num_lines": 28, "path": "/app/templates/app/task_confirm_delete.html", "repo_name": "tconsta/todo", "src_encoding": "UTF-8", "text": "{% extends \"app/base.html\" %}\n\n{% block content %}\n<div class=\"container\">\n <div class=\"top-space\"></div>\n <div class=\"d-flex justify-content-center\">\n <p class=\"whitetext\">Are you sure you want to delete the task:</p>\n </div>\n <div class=\"d-flex justify-content-center\">\n <h2 class=\"whitetext\">{{ task }}</h2>\n </div>\n <div class=\"d-flex justify-content-center\">\n <div class=\"top-space\"></div>\n </div>\n <div class=\"d-flex justify-content-center\">\n <form action=\"\" method=\"POST\">\n {% csrf_token %}\n <button type=\"submit\" class=\"btn btn-light\">Yes, delete</button>\n </form>\n </div>\n <div class=\"d-flex justify-content-center\">\n <div class=\"top-space\"></div>\n </div>\n <div class=\"d-flex justify-content-center\">\n <a class=\"btn btn-light\" href=\"/\">Cancel</a>\n </div>\n</div>\n{% endblock %}\n" } ]
6
tung2921/FacialExpression
https://github.com/tung2921/FacialExpression
a4d4ac58d69774ee443662464002b50f4d3cfb35
55f46173f04b89ce96f01571550d8619a2b27fb5
8430e7b9af796b4745c95ccbcfe9cbe5de827768
refs/heads/master
2021-01-04T05:51:18.106690
2020-09-07T03:22:54
2020-09-07T03:22:54
240,416,882
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7425569295883179, "alphanum_fraction": 0.7767075300216675, "avg_line_length": 35.870967864990234, "blob_id": "3ce5b671e7d904ca20bae4b3d671b1104d539bda", "content_id": "22dadf15a6e5a4abfd6ed91f8cdd9be3c5a7bc41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1142, "license_type": "no_license", "max_line_length": 110, "num_lines": 31, "path": "/ComputerVision/Facial_expression/README.md", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# Facial Expression Classifier\n\nBuilding an emotion classifier using tensorflow-gpu 2.0 and Opencv4.\n\n## Data\n\nData is taken from Kaggle [fer2013](https://www.kaggle.com/deadskull7/fer2013). \nThe dataset contains 34034 images of 7 basic emotions stored in a csv file.\nEach image is of size 48x48.\n\n## Requirement \n\n1. [Anaconda](https://www.anaconda.com/distribution/#download-section)\n2. Tensorflow-gpu2 (This can be automatically [set up](https://anaconda.org/anaconda/tensorflow-gpu) \nusing Anaconda)\n3. Opencv4 (Also can be [set up](https://anaconda.org/conda-forge/opencv) using anaconda)\n\n## Usage\n\n1. Clone the Repo to your local machine\n2. Move to the directory that contains the cloned repo\n\n*Optional:* if you want to rerun the notebook:\n3. Download fer2013 data and save it to folder data\n\n4. Install the virtual environment using conda from the environment.yml file\n> conda env create -f environment.yml\n5. Once installed, activate the environment\n> conda activate tf-gpu2\n6. Type in command line the following command:\n> python recognize_video.py -d face_detection_model -pre models/bn_dp_image_augmentation/bn_dp_augmentation.h5" }, { "alpha_fraction": 0.5644151568412781, "alphanum_fraction": 0.5752882957458496, "avg_line_length": 34.70588302612305, "blob_id": "5ac033d82e13f2d0d9503cf63bab66a95498d41d", "content_id": "051e3c14057c34a6e0bebe6ca7c93f14b55d0074", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3035, "license_type": "no_license", "max_line_length": 86, "num_lines": 85, "path": "/ComputerVision/Image_Denoising/utils/utils.py", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# Utility Functions\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom typing import List\n\ndef add_noise(img: np.array, min_noise_factor: float=.3, \n max_noise_factor: float=.6) -> np.array:\n \"\"\"Add random noise to an image using a uniform distribution\n Input\n -----\n img: array-like\n Array of pixels\n min_noise+factor: float\n Min value for random noise\n max_noise_factor: float\n Max value for random noise\n Output\n ------\n Noisy image\"\"\"\n # Generating and applying noise to image:\n noise_factor = np.random.uniform(min_noise_factor, max_noise_factor)\n noise = np.random.normal(loc=0.0, scale=noise_factor, size=img.shape) \n img_noisy = img + noise\n \n # Making sure the image value are still in the proper range:\n img_noisy = np.clip(img_noisy, 0., 1.)\n \n return img_noisy\n\ndef plot_image_grid(images: List[np.array], titles:List[str]=None, \n figure: plt.figure =None,grayscale: bool = False, \n transpose: bool = False) -> plt.figure:\n \"\"\"\n Plot a grid of n x m images\n Input\n -----\n images: List[np.array] \n Images in a n x m array\n titles: List[str] (opt.) \n List of m titles for each image column\n figure: plt.figure (opt.) \n Pyplot figure (if None, will be created)\n grayscale: bool (opt.) \n If True return grayscaled images\n transpose: bool (opt.) \n If True, transpose the grid\n Output\n ------\n Pyplot figure filled with the images\n \"\"\"\n num_cols, num_rows = len(images), len(images[0])\n img_ratio = images[0][0].shape[1] / images[0][0].shape[0]\n\n if transpose:\n vert_grid_shape, hori_grid_shape = (1, num_rows), (num_cols, 1)\n figsize = (int(num_rows * 5 * img_ratio), num_cols * 5)\n wspace, hspace = 0.2, 0.\n else:\n vert_grid_shape, hori_grid_shape = (num_rows, 1), (1, num_cols)\n figsize = (int(num_cols * 5 * img_ratio), num_rows * 5)\n hspace, wspace = 0.2, 0.\n \n if figure is None:\n figure = plt.figure(figsize=figsize)\n imshow_params = {'cmap': plt.get_cmap('gray')} if grayscale else {}\n grid_spec = gridspec.GridSpec(*hori_grid_shape, wspace=0, hspace=0)\n for j in range(num_cols):\n grid_spec_j = gridspec.GridSpecFromSubplotSpec(\n *vert_grid_shape, subplot_spec=grid_spec[j], wspace=wspace, hspace=hspace)\n\n for i in range(num_rows):\n ax_img = figure.add_subplot(grid_spec_j[i])\n # ax_img.axis('off')\n ax_img.set_yticks([])\n ax_img.set_xticks([])\n if titles is not None:\n if transpose:\n ax_img.set_ylabel(titles[j], fontsize=25)\n else:\n ax_img.set_title(titles[j], fontsize=15)\n ax_img.imshow(images[j][i], **imshow_params)\n\n figure.tight_layout()\n return figure\n" }, { "alpha_fraction": 0.6048808097839355, "alphanum_fraction": 0.6170260906219482, "avg_line_length": 38.68918991088867, "blob_id": "c243d75a15fcf069750d6129c8c2f2d3bcb68b5e", "content_id": "d3226e45611e1ce4fba91d8359d6282d9b8c7dbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8810, "license_type": "no_license", "max_line_length": 117, "num_lines": 222, "path": "/ComputerVision/TFDS/TF-Hub/tfds_utils.py", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport tensorflow_datasets as tfds\nfrom tensorflow.keras.preprocessing.image import img_to_array, load_img\n\n\nfrom typing import Optional, Dict, Iterable, Any, List\nimport functools\nimport os, math\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport matplotlib.gridspec as gridspec\n\n# Some hyper-parameters:\nbatch_size = 8 # Images per batch (reduce/increase according to the machine's capability)\nnum_epochs = 300 # Max number of training epochs\nrandom_seed = 42 # Seed for some random operations, for reproducibility\n\n# print(\"TF version:\", tf.__version__)\n# print(\"Hub version:\", hub.__version__)\n# print(tf.config.list_physical_devices('GPU'))\n\n\n\"\"\" Download and prepare tfds dataset \"\"\"\n\n\nclass TFDS():\n \"\"\"Download and process datasets from tensorflow dataset\"\"\"\n AVAILABLE_DATASETS = tfds.list_builders()\n\n def __init__(self, name:str, seed=1234, data_dir:Optional[str]=None) -> None:\n\n (self.train_ds, self.val_ds, self.test_ds), self.metadata = tfds.load(\n name=name,\n split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],\n with_info=True,\n as_supervised=True,\n data_dir=data_dir)\n\n self.total_imgs = self.metadata.splits['train'].num_examples\n self.num_trainImgs = int(self.total_imgs * 0.8)\n self.num_valImgs = int(self.total_imgs * 0.1)\n self.num_testImgs = int(self.total_imgs * 0.1)\n self.img_shape = next(iter(self.train_ds))[0].shape\n self.get_label_name = self.metadata.features['label'].int2str\n self.seed=seed\n self.Preprocess = Preprocess(seed=self.seed)\n\n def get_dataset(self, num_epochs:int=300, batch_size:int=32,\n input_shape:Iterable[int]=(32, 32, 3), seed=None):\n \"\"\"[Generate train, val, test sets from tfds]\n\n Args:\n batch_size (int, optional): [number of images for each batch]. Defaults to 32.\n num_epochs (int, required): [number of epochs to run on experiment]. Defaults to 300.\n input_shape (tuple, optional): [shape of each image (h, w, c)]. Defaults to (32, 32, 3).\n seed ([type], optional): []. Defaults to None.\n\n Returns:\n [tuple]: [train, val, test sets]\n \"\"\" \n train_prepare_data_fn = functools.partial(self.Preprocess.preprocess, input_shape=input_shape)\n test_prepare_data_fn = functools.partial(self.Preprocess.preprocess, augment=False, input_shape=input_shape)\n train_ds = (self.train_ds\n .repeat(num_epochs)\n .shuffle(10000, seed=seed)\n .map(train_prepare_data_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n .batch(batch_size)\n .prefetch(tf.data.experimental.AUTOTUNE)\n )\n val_ds = (self.val_ds\n .repeat(num_epochs)\n .map(test_prepare_data_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n .batch(batch_size)\n .prefetch(tf.data.experimental.AUTOTUNE)\n )\n test_ds = self.test_ds.map(test_prepare_data_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n return (train_ds, val_ds, test_ds)\n\nclass Preprocess():\n \"\"\"Preprocess images from tfds\"\"\"\n\n def __init__(self, seed):\n self.seed = seed\n \n @staticmethod\n def visualize(original, augmented):\n fig = plt.figure()\n plt.subplot(1,2,1)\n plt.title('Original image')\n plt.imshow(original)\n\n plt.subplot(1,2,2)\n plt.title('Augmented image')\n plt.imshow(augmented)\n\n def preprocess(self, image:List[float], label:Any, input_shape:Iterable[int], augment:bool=True):\n \"\"\"[Perform augmentation on input image]\n\n Args:\n image (List[float]): [input image]\n label (Any): [label of the image]\n input_shape (Iterable[int]): [expected shape of the output image ]\n augment (bool, optional): [whether to augment or not]. Defaults to True.\n\n Returns:\n [type]: [tuple of image and label]\n \"\"\" \n image = tf.image.convert_image_dtype(image, tf.float32)\n\n if augment:\n # Randomly applied horizontal flip:\n image = tf.image.random_flip_left_right(image, seed=self.seed)\n\n # Random B/S changes:\n image = tf.image.random_brightness(image, max_delta=0.1, seed=self.seed)\n if input_shape[2] == 3:\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5, seed=self.seed)\n image = tf.clip_by_value(image, 0.0, 1.0) # keeping pixel values in check\n\n # Random resize and random crop back to expected size:\n \n random_scale_factor = tf.random.uniform([1], minval=1., maxval=1.4, dtype=tf.float32, seed=self.seed)\n scaled_height = tf.cast(tf.cast(input_shape[0], tf.float32) * random_scale_factor, \n tf.int32)\n scaled_width = tf.cast(tf.cast(input_shape[1], tf.float32) * random_scale_factor, \n tf.int32)\n scaled_shape = tf.squeeze(tf.stack([scaled_height, scaled_width]))\n image = tf.image.resize(image, scaled_shape)\n image = tf.image.random_crop(image, input_shape, seed=self.seed)\n else:\n image = tf.image.resize(image, input_shape[:2])\n \n return (image, label)\n\nclass Evaluation():\n \"\"\" Eval utility functions\"\"\"\n def __init__(self):\n pass\n\n def load_image(self, image_path, size):\n \"\"\"\n Load an image as a Numpy array.\n :param image_path: Path of the image\n :param size: Target size\n :return Image array, normalized between 0 and 1\n \"\"\"\n image = img_to_array(load_img(image_path, target_size=size)) / 255.\n return image\n\n\n def process_predictions(self, class_probabilities, class_readable_labels, k=5):\n \"\"\"\n Process a batch of predictions from our estimator.\n :param class_probabilities: Prediction results returned by the Keras classifier for a batch of data\n :param class_readable_labels: List of readable-class labels, for display\n :param k: Number of top predictions to consider\n :return Readable labels and probabilities for the predicted classes\n \"\"\"\n topk_labels, topk_probabilities = [], []\n for i in range(len(class_probabilities)):\n # Getting the top-k predictions:\n topk_classes = sorted(np.argpartition(class_probabilities[i], -k)[-k:])\n\n # Getting the corresponding labels and probabilities:\n topk_labels.append([class_readable_labels[predicted] for predicted in topk_classes])\n topk_probabilities.append(class_probabilities[i][topk_classes])\n\n return topk_labels, topk_probabilities\n\n\n def display_predictions(self, images, topk_labels, topk_probabilities, true_labels):\n \"\"\"\n Plot a batch of predictions.\n :param images: Batch of input images\n :param topk_labels: String labels of predicted classes\n :param topk_probabilities: Probabilities for each class\n \"\"\"\n num_images = len(images)\n num_images_sqrt = np.sqrt(num_images)\n plot_cols = plot_rows = int(np.ceil(num_images_sqrt))\n\n figure = plt.figure(figsize=(13, 10))\n grid_spec = gridspec.GridSpec(plot_cols, plot_rows)\n\n for i in range(num_images):\n img, pred_labels, pred_proba, true_label = images[i], topk_labels[i], topk_probabilities[i], true_labels[i]\n # Shortening the labels to better fit in the plot:\n pred_labels = [label.split(',')[0][:20] for label in pred_labels]\n\n grid_spec_i = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=grid_spec[i],\n hspace=0.1)\n\n # Drawing the input image:\n ax_img = figure.add_subplot(grid_spec_i[:2])\n ax_img.axis('off')\n ax_img.imshow(img)\n ax_img.set_title(f'True Label: {true_label}')\n ax_img.autoscale(tight=True)\n\n # Plotting a bar chart for the predictions:\n ax_pred = figure.add_subplot(grid_spec_i[2])\n ax_pred.spines['top'].set_visible(False)\n ax_pred.spines['right'].set_visible(False)\n ax_pred.spines['bottom'].set_visible(False)\n ax_pred.spines['left'].set_visible(False)\n y_pos = np.arange(len(pred_labels))\n ax_pred.barh(y_pos, pred_proba, align='center')\n ax_pred.set_yticks(y_pos)\n ax_pred.set_yticklabels(pred_labels)\n ax_pred.invert_yaxis()\n\n plt.tight_layout()\n plt.show()\n\nif __name__ == \"__main__\":\n pass" }, { "alpha_fraction": 0.6623541116714478, "alphanum_fraction": 0.6832315921783447, "avg_line_length": 34.63810729980469, "blob_id": "e3a9ecb5621652431f9ee7b852bd44a3a460386d", "content_id": "ca66a9363cf11ac838186dbfccf9cedd5b5ad05a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31613, "license_type": "no_license", "max_line_length": 713, "num_lines": 887, "path": "/ComputerVision/Facial_expression/Facial Expression Recognition Classifier.py", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.4.1\n# kernelspec:\n# display_name: 'Python 3.7.5 64-bit (''tf-gpu2'': conda)'\n# language: python\n# name: python37564bittfgpu2conda05ef10f1ea7941329b7828cc85e18783\n# ---\n\n# # Facial Expression Recognition Classification\n#\n# In this notebook, we utilize Opencv, Keras and Tensorflow-gpu 2.x to create a real-time facial expression recognition classifier. We will use the [fer2013](https://www.kaggle.com/deadskull7/fer2013) dataset from Kaggle.There are two components in our project:\n#\n# 1. Building an emotion classifier (This is what most of the notebook is devoted to)\n# * We'll experiment multiple training architectures to get as good a performance as possible for our emotion classifier.\n# 2. Building an facial detector in real-time for emotion classification (We'll take advantage of [tensorflow object detection API](https://github.com/tensorflow/models/tree/master/research/object_detection) and Opencv for our real-time facial detector)\n# * The detector will feed facial images in real-time to the emotion classifier for classification\n\n# +\n# Importing dependencies\nimport pandas as pd\nfrom typing import List\nimport numpy as np\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport functools\nimport os\nfrom pathlib import Path\n\n# Model Building\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense , Activation , Dropout ,Flatten\nfrom tensorflow.keras.layers import Conv2D, BatchNormalization, MaxPooling2D\nfrom tensorflow.keras.metrics import categorical_accuracy, sparse_categorical_accuracy\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.optimizers import *\n\n# -\n\ntf.test.is_gpu_available()\n\n\n# ## Exploring\n\n# + code_folding=[1, 19, 32, 54, 74]\n# Utilities Function\ndef learning_curve():\n \"\"\"Plot the learning curve for the trained model \n \"\"\"\n history = h.history\n train_loss = history['loss']\n train_acc = history['sparse_categorical_accuracy']\n val_loss = history['val_loss']\n val_acc = history['val_sparse_categorical_accuracy']\n\n plt.figure()\n plt.plot(train_loss, label='train loss')\n plt.plot(val_loss, label='val loss')\n plt.legend()\n\n plt.figure()\n plt.plot(train_acc, label='train acc')\n plt.plot(val_acc, label='val acc')\n plt.legend()\ndef str_to_float(string: str) -> List[float]:\n \"\"\"Transform str object into an array of floats\n Input\n -----\n string: str\n The values to be transformed\n Output\n ------\n Array-like of float values corresponding to the input\n \"\"\"\n string = string.split(' ')\n values = [float(x) for x in string]\n return values\ndef plot_dist(data: pd.DataFrame, filter='Training', figsize=(12,8), color='White'):\n \"\"\"Returns a figure that shows the distribution of the specified data\n Input\n -----\n data: pd.DataFrame\n pandas dataframe\n filter: str \n one of ['Training', 'PublicTest','PrivateTest']\n figsize: tuple\n height and width of the returned figure\n color: matplotlib defined color scheme\n THe color of the title\n \"\"\"\n plt.figure(figsize=figsize)\n filters = data.loc[data.Usage == filter, ['emotion', 'numerical']] \n freq = list(filters['emotion'].value_counts().values)\n emo = np.arange(0, len(freq), step=1)\n plt.bar(x=emo, height=freq)\n plt.title(f'{filter} distribution', fontsize=25, color=color)\n plt.xlabel('Emotions', color=color)\n plt.xticks(ticks=emo,labels=label_map)\n plt.ylabel('Frequency', color=color)\ndef split_data(df: pd.DataFrame, filter: str='Training') -> tf.data.Dataset:\n \"\"\"Filter out data from the DataFrame using filter\n Input\n -----\n df: pd.DataFrame\n data to be processed\n filter: one of 'Training', 'PublicTest','PrivateTest'\n Output\n ------\n tf.data.Dataset\"\"\"\n data = []\n label = []\n for idx, val in enumerate(df.loc[df.Usage == filter, ['emotion', 'numerical']].values):\n data.append(val[1])\n label.append(val[0])\n data = np.array(data)\n data= data.reshape(-1, 48, 48,1).astype('float32') / 255\n label = np.array(label)\n\n return tf.data.Dataset.from_tensor_slices((data, label)) \ndef obs(data):\n \"\"\"Returns the number of examples in a tf.data.Dataset object\"\"\"\n count = 0\n for instance in data:\n count += 1\n print(f'Number of observations is {count}')\n return count\n\n\n# -\n\ndata =pd.read_csv('fer2013.csv')\ndata.head()\n\n# Check the data type of each variable\ndata.dtypes\n\n# 1. The dataset contains 3 variables. 'Emotion' denotes the type of emotions that the image (represented by the variable 'pixels') portrays. The variable 'Usage' specifies whether the example is used in training , validation or test sets.\n# 2. The pixel variable is of object type, however. In pandas, this means each example in pixels is a string object. But we know that an image is represented by a matrix of values from 0 to 255. Therefore, we need to transform this variable into float type. We will utilize the str_to_float function defined in the beginning cell and store the transformed variable in 'numerical'.\n\ndata['numerical'] = data['pixels'].apply(str_to_float)\ndisplay(data.head())\nprint('==='*30)\nprint(type(data.numerical[0][0]))\n\n# Now each example in the new variable is a list of float values\n\n# Number of examples in each dataset\ndisplay(data.Usage.value_counts())\n\n# We have 28k images in training set, and 3.5k images in each of the test and validation sets.\n\n# + code_folding=[]\n# Plotting distribution of emotions in each dataset\nlabel_map = ['Anger', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']\nfigsize = (10,8)\n# Training Dist\nplot_dist(data=data, filter='Training', figsize=figsize)\n# Val Dist\nplot_dist(data=data, filter='PublicTest',figsize=figsize)\n# Test Dist\nplot_dist(data=data, filter='PrivateTest',figsize=figsize)\n# -\n\n# The distribution of each dataset is similar to each other. Neutral seems to be underrepresented. We might want to downsample other emotions or giving more weight to neutral during training. In this notebook, however, we will train without addressing the imbalance (I'm a little lazy here).\n\n# In order to train the model, we need to transform the data into a tf.data.Dataset object. Tensorflow have great documentation [here](https://www.tensorflow.org/guide/keras/train_and_evaluate). I recommend you check it out if you want to assign weight to address imbalances in our datasets. We'll take use of the split_data function defined in the beginning.\n\n# + code_folding=[0]\n# Transform datasets into tf.data.Dataset\ntrain_dataset = split_data(data, filter='Training')\nval_dataset = split_data(data, filter='PublicTest')\ntest_dataset = split_data(data, filter='PrivateTest')\n\nprint('Training shape:\\t', train_dataset)\nprint('Val shape:\\t', val_dataset)\nprint('Test shape:\\t',test_dataset)\n# -\n\n# Each tf.data.Dataset object includes the image pixels and its corresponding label. Each image in our dataset is in a grayscale 48x48 shape. \n\n# Checking the number of examples in each dataset\ntrain_count = obs(data=train_dataset)\nval_count = obs(data=val_dataset)\ntest_count = obs(data=test_dataset)\n\n# Let's checkout what each emotion looks like\n\n# Check images\nlabel_map = ['Anger', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']\nfor idx, label in enumerate(label_map):\n emo = data.loc[data.emotion == idx, 'numerical']\n fig = plt.figure(figsize=(20,15))\n for idx, img in enumerate(emo[0:5]):\n img = np.array(img).reshape(48,48)\n ax = fig.add_subplot(1,5,idx+1)\n ax.imshow(img)\n ax.set_title(f'{label}', color='white')\n\n# Some of the images here I deem wrongly labeled. For example, the first image in fear. It doesn't look like fear to me. This means that our classifier will have a hard time converging to an optimal solution.\n\n# ## Training\n\n# Hyperparameter definition\ninput_shape = [48,48,1]\nBATCH_SIZE = 64\nnum_epoch = 100\nSHUFFLE_BUFFER_SIZE = train_count\n\n# Again please refer to tensorflow documentation to create dataset for model training\ntrain_dataset = train_dataset.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)\nval_dataset = val_dataset.batch(BATCH_SIZE)\ntest_dataset = test_dataset.batch(BATCH_SIZE)\n\n\n# ### Batch Normalization without Dropout\n#\n# We'll be using a model with 6 conv2d layers and 1 dense layer on top for classification. According to [this article]('./papers/BN.pdf'), the use of batch normalization after the convolutional layer addresses the change in distribution between conv layers and acts as a regularizer, thereby eliminating the need to use dropout. So we'll train a model with BN layer and no dropout and test it with one with dropout for this dataset to see which one performs better.\n\n# + code_folding=[]\ndef my_model_nodropout():\n model = Sequential()\n input_shape = (48,48,1)\n model.add(Conv2D(64, (5, 5), input_shape=input_shape,activation='relu', padding='same'))\n model.add(Conv2D(64, (5, 5), activation='relu', padding='same'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Conv2D(128, (5, 5),activation='relu',padding='same'))\n model.add(Conv2D(128, (5, 5),activation='relu',padding='same'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Conv2D(256, (3, 3),activation='relu',padding='same'))\n model.add(Conv2D(256, (3, 3),activation='relu',padding='same'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Flatten())\n model.add(Dense(128))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n# model.add(Dropout(0.2))\n model.add(Dense(7))\n model.add(Activation('softmax'))\n \n model.compile(loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'],optimizer='adam')\n \n return model\n\n\n# -\n\nmodel=my_model_nodropout()\nmodel.summary()\n\n# +\npath_model='./models/model_bn_nodropout.h5' # save model at this location after each epoch\n\nmodel=my_model_nodropout() # create the model\n\n# fit the model\n# We save the model after each epoch and use early stopping based on val_loss\nh=model.fit(train_dataset, \n verbose=1, \n validation_data=val_dataset,\n epochs=20,\n callbacks=[\n ModelCheckpoint(filepath=path_model),\n tf.keras.callbacks.EarlyStopping(\n monitor='val_loss', patience=5, verbose=1)\n ]\n )\n# -\n\n# Utility function defined at the beginning\nlearning_curve()\n\n\n# The model quickly overfits after 1 epoch. Although the training accuracy is high, the val accuracy is not.\n\n# ### Batch Normalization with Dropout\n#\n# This time well apply dropout together with BN layer to train the emotion classifier\n\n# + code_folding=[]\ndef my_model():\n model = Sequential()\n input_shape = (48,48,1)\n model.add(Conv2D(64, (5, 5), input_shape=input_shape,activation='relu', padding='same'))\n model.add(Conv2D(64, (5, 5), activation='relu', padding='same'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Conv2D(128, (5, 5),activation='relu',padding='same'))\n model.add(Conv2D(128, (5, 5),activation='relu',padding='same'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Conv2D(256, (3, 3),activation='relu',padding='same'))\n model.add(Conv2D(256, (3, 3),activation='relu',padding='same'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Flatten())\n model.add(Dense(128))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(Dropout(0.2))\n model.add(Dense(7))\n model.add(Activation('softmax'))\n \n model.compile(loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'],optimizer='adam')\n \n return model\n\n\n# -\n\nmodel=my_model()\nmodel.summary()\n\n# +\npath_model='./models/model_bn_dp02.h5' # save model at this location after each epoch\n\nmodel=my_model() # create the model\n\n# fit the model\nh=model.fit(train_dataset, \n verbose=1, \n validation_data=val_dataset,\n epochs=20,\n callbacks=[\n ModelCheckpoint(filepath=path_model),\n tf.keras.callbacks.EarlyStopping(\n monitor='val_loss', patience=5, verbose=1)\n ]\n )\n# -\n\nlearning_curve()\n\n# This time the model performs slightly better. However, it still overfits very quickly. We need to address the overfitting issue. We'll increase the dropout threshold to 0.5 to see if helps.\n\n# ### No Batch Normalization with Dropout rate 0.5\n\n# +\nmodel = Sequential()\n\nmodel.add(Conv2D(6, (5, 5), input_shape=input_shape, padding='same', activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(16, (5, 5), padding='same', activation = 'relu'))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(64, (3, 3), activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(128, activation = 'relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(7, activation = 'softmax'))\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer='adam',metrics=[\"sparse_categorical_accuracy\"])\nmodel.summary\n\npath_model='./models/model_bn_dp05.h5' # save model at this location after each epoch\n\n# model=my_model() # create the model\n\n# fit the model\nh=model.fit(train_dataset, \n verbose=1, \n validation_data=val_dataset,\n epochs=100,\n callbacks=[\n ModelCheckpoint(filepath=path_model),\n tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=1)\n ]\n )\n\n\n# -\n\n# <!-- As expected, loosening the threshold for dropout worsens the performance of the model --> [TO DO ]Check again. Let's address overfitting with image augmentation.\n\n# ## Image augmentation\n\n# +\ndef show_img(img, crop, bright, title):\n fig = plt.figure(figsize=(15,10))\n plt.subplot(1,3,1)\n plt.imshow(img, cmap='gray')\n plt.title(title[0], color='white')\n \n plt.subplot(1,3,2)\n plt.imshow(crop, cmap='gray')\n plt.title(title[1], color='white')\n \n plt.subplot(1,3,3)\n plt.imshow(bright, cmap='gray')\n plt.title(title[2], color='white')\n\ntitle = ['Original Image', 'Randomly resized and cropped Image', 'Randomly brightened image']\n\nimg = np.array(data['numerical'][0]).reshape(48,48)\n\ncrop = tf.image.resize_with_crop_or_pad(img.reshape(48,48,1), 52, 52) # Add 5 pixels of padding\ncrop = tf.image.random_crop(crop, size=[48, 48, 1]) # Random crop back to 48x48\ncrop = crop.numpy().reshape(48,48)\n\nimg1 = np.array(data['numerical'][0]).reshape(48,48,1)\nbright = tf.image.random_brightness(img1, max_delta=0.5)\nbright = bright.numpy().reshape(48,48)\n\nshow_img(img, crop, bright, title=title)\n\n\n\n# + code_folding=[]\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nnum_epoch = 35\ndef convert(image, label):\n image = tf.image.convert_image_dtype(image, tf.float32) # Cast and normalize the image to [0,1]\n return image, label\n\ndef augment(image,label):\n image = tf.image.convert_image_dtype(image, tf.float32) # Cast and normalize the image to [0,1]\n image = tf.image.resize_with_crop_or_pad(image, 52, 52) # Add 5 pixels of padding\n image = tf.image.random_crop(image, size=[48, 48, 1]) # Random crop back to 48x48\n image = tf.image.random_brightness(image, max_delta=0.5) # Random brightness\n return image,label\n\ntrain_dataset = split_data(data, filter='Training')\nval_dataset = split_data(data, filter='PublicTest')\n\n# +\naugmented_train_batches = (train_dataset\n # Only train on a subset, so you can quickly see the effect.\n .shuffle(train_count)\n # The augmentation is added here.\n .map(augment, num_parallel_calls=AUTOTUNE)\n .batch(BATCH_SIZE)\n .prefetch(AUTOTUNE))\n\n\nvalidation_batches = (\n val_dataset\n .map(convert, num_parallel_calls=AUTOTUNE)\n .batch(BATCH_SIZE))\n# -\n\n# ### Batch Norm + Augmentation\n\nmodel = my_model_nodropout()\nmodel_dir = Path(r'.\\models\\bn_nodp_image_augmentation')\nmodel_dir.mkdir(parents=True, exist_ok=True)\n\nos.path.join(str(model_dir / 'weights-epoch{epoch:02d}-loss{val_loss:.2f}.h5')\n\nnum_epoch = 35\nmodel = my_model_nodropout()\nhistory = model.fit(augmented_train_batches,\n epochs=num_epoch,\n validation_data=validation_batches,\n verbose=1)\n\nmodel.save(str(model_dir / 'bn_nodropout_augmentation.h5'))\n\n# Our emotion classifier improves a little bit in comparison with the one without image augmentation. However, it still suffers from heavy overfitting.\n\n# ### Batch Norm + Dropout + Augmentation \n\nmodel_dir = Path(r'.\\models\\bn_dp_image_augmentation')\nmodel_dir.mkdir(parents=True, exist_ok=True)\n\nmodel = my_model()\nhistory = model.fit(augmented_train_batches,\n epochs=num_epoch,\n validation_data=validation_batches,\n verbose=1)\n\nmodel.save(str(model_dir / 'bn_dp_augmentation.h5'))\n\n# The classifier with dropout also suffers from overfitting. It did perform better than the other models, however.\n\n# ## Transfer Learning\n#\n# The idea behind transfer learning is that a model trained on a dataset could be reused for another dataset because what the neural network does is learn the representational structure underlying the dataset. Early layers will learn to detect simple, yet ubiquitous features while deeper ones learn to detect data specific features. As a result, we could reuse a model trained on a huge dataset that encompasses a large number of real life objects by reusing the early layers of the pre-trained model while training deeper layers and our own classifier on top of the network. In this notebook, we will reuse Mobilenetv2, trained on imagenet dataset, as we need to lightweight model for real time classification.\n\n# +\n# Preprocessing data\nIMG_SIZE = 160\nIMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3)\nSHUFFLE_BUFFER_SIZE = train_count\nBATCH_SIZE = 64\n\ndef format_example(image, label):\n image = tf.cast(image, tf.float32)\n image = tf.image.grayscale_to_rgb(image)\n image = (image/127.5) - 1\n image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))\n return image, label\n\n\ntrain_batches = train_dataset.map(format_example).shuffle(\n SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)\nval_batches = val_dataset.map(format_example).batch(BATCH_SIZE)\n\nfor image, label in train_batches.take(1):\n print(image.shape)\n# -\n\n# Mobilenetv2 only accepts images of certain dimensions. So we need to resize the images. In our case, the images is resized from (48,48,1) to (160,160,3)\n\n# Create the base model from the pre-trained model MobileNet V2\nbase_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,\n include_top=False,\n weights='imagenet')\n\nfeature_batch = base_model(image)\nprint(feature_batch.shape)\n\n# ### Freeze the convolutional base\n#\n# As mentioned earlier, we only train the deeper layers and our own classifier. But before we train the deeper layers, let's just train the classifier first to see how the model performs by freezing all the weights, thereby preventing the training process from updating the weights.\n\nbase_model.trainable = False\n\nbase_model.summary()\n\n# Adding a global average layer on top of the conv layers to reduce computations\nglobal_average_layer = tf.keras.layers.GlobalAveragePooling2D()\nfeature_batch_average = global_average_layer(feature_batch)\nprint(feature_batch_average.shape)\n\n# Finally adding our own classifier to train Mobilenet on our specific emotion classification task\nprediction_layer = tf.keras.layers.Dense(7)\nprediction_batch = prediction_layer(feature_batch_average)\nprint(prediction_batch.shape)\n\nmodel = tf.keras.Sequential([\n base_model,\n global_average_layer,\n prediction_layer\n])\n\nbase_learning_rate = 0.0001\nmodel.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\nmodel.summary()\n\n# As shown in the model architecture, this model is weight as the number of parameters in this model is only . This is less computation than our previous models, whose paramters were about 2.7m.\n\n# Checking that all the weights except for the classifier are frozen\nlen(model.trainable_variables)\n\n# ### Training\n\n# +\ninitial_epochs = 10\nvalidation_steps=20\n\nloss0,accuracy0 = model.evaluate(val_batches, steps = validation_steps)\n# -\n\nhistory = model.fit(train_batches,\n epochs=initial_epochs,\n validation_data=val_batches)\n\nmodel.save('./models/mobilenet_freeze.h5')\n\n# ### Learning Curve\n\n# +\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nplt.figure(figsize=(8, 8))\nplt.subplot(2, 1, 1)\nplt.plot(acc, label='Training Accuracy')\nplt.plot(val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.ylabel('Accuracy')\nplt.ylim([min(plt.ylim()),1])\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(2, 1, 2)\nplt.plot(loss, label='Training Loss')\nplt.plot(val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.ylabel('Cross Entropy')\nplt.ylim([0,5.0])\nplt.title('Training and Validation Loss')\nplt.xlabel('epoch')\nplt.show()\n# -\n\n# The pre-trained model does not seem to perform very well on our dataset as the validation accuracy is less than 0.5\n\n# ### Un-freeze the top layers of the model\n#\n# We could unfreeze the deeper layers so that these layers also learns the features specific to our dataset, thereby improving the performance of the model.\n\nbase_model.trainable = True\n\n# +\nprint(\"Number of layers in the base model: \", len(base_model.layers))\n# Fine-tune from this layer onwards\nfine_tune_at = 100\n\n# Freeze all the layers before the `fine_tune_at` layer\nfor layer in base_model.layers[:fine_tune_at]:\n layer.trainable = False\n# -\n\nmodel.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n optimizer = tf.keras.optimizers.RMSprop(lr=base_learning_rate/10),\n metrics=['accuracy'])\n\nmodel.summary()\n\nlen(model.trainable_variables)\n\n# +\nfine_tune_epochs = 25\ntotal_epochs = initial_epochs + fine_tune_epochs\n\nhistory_fine = model.fit(train_batches,\n epochs=total_epochs,\n initial_epoch = history.epoch[-1],\n validation_data=val_batches)\n# -\n\n# ### Fine-tune Learning Curve\n\n# +\nacc += history_fine.history['accuracy']\nval_acc += history_fine.history['val_accuracy']\n\nloss += history_fine.history['loss']\nval_loss += history_fine.history['val_loss']\n\n# +\nplt.figure(figsize=(8, 8))\nplt.subplot(2, 1, 1)\nplt.plot(acc, label='Training Accuracy')\nplt.plot(val_acc, label='Validation Accuracy')\nplt.ylim([0, 1])\nplt.plot([initial_epochs-1,initial_epochs-1],\n plt.ylim(), label='Start Fine Tuning')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(2, 1, 2)\nplt.plot(loss, label='Training Loss')\nplt.plot(val_loss, label='Validation Loss')\nplt.ylim([0, 5.0])\nplt.plot([initial_epochs-1,initial_epochs-1],\n plt.ylim(), label='Start Fine Tuning')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.xlabel('epoch')\nplt.show()\n# -\n\n# This model indeed performs better than the frozen one. However, the performance of the pre-trained model is still no where near the ones we created. \n\nmodel.save('./models/mobilenet_finetuned.h5')\n\n# ## Evaluating with test data\n#\n# After training multiple models and applying transfer learning, the best model we got is the one bn+dropout+image augmentation. Let's evaluate that model on the test set to make sure that we don't overfit both the train and the val datasets.\n\n# +\nlabel_map = {0:'Anger', 1:'Disgust', 2:'Fear', 3:'Happy', 4:'Sad', 5:'Surprise', 6:'Neutral'}\n\nbest_model = r'D:\\personal_projects\\Facial_expression\\models\\bn_dp_image_augmentation\\bn_dp_augmentation.h5'\nmodel = tf.keras.models.load_model(\n best_model\n)\n# -\n\nmodel.summary()\n\nBATCH_SIZE = 64\ntest_batches = (\n test_dataset\n .map(convert, num_parallel_calls=AUTOTUNE)\n .batch(BATCH_SIZE))\nresult = model.evaluate(test_batches)\ndict(zip(model.metrics_names, result))\n\n# This model got a 65% accuracy on the test set. This means our model did not overfit both the train and val datasets. Still, 65% accuracy is not really that big of an achievement.\n\n# ### Checking which image the model predicted incorrectly\n\npredictions = model.predict(test_batches)\n\n\nfrom typing import List\ndef wrong_predictions(data: tf.data.Dataset) -> (List[np.array], List[np.array], List[np.array]):\n \"\"\"Return metadata from tf.data.Dataset\n Input\n -----\n data: tf.data.Dataset\n the data to be fed\n Output\n ------\n A tuple of the images in the dataset, the corresponding labels and the predictions\"\"\"\n labels =[]\n images = []\n preds = []\n count = 0\n i = 0\n start = 0\n for image, label in (test_batches):\n end = start + len(label)\n prediction = predictions[start:end]\n label = label.numpy()\n # print(label.shape)\n # print(prediction.shape)\n cond = np.equal(np.argmax(prediction,axis=1),label)\n images.append(image[~cond])\n labels.append(label[~cond])\n preds.append(np.argmax(prediction[~cond],axis=1))\n start += len(label)\n return images, labels, preds\nimages, labels, preds = wrong_predictions(test_batches)\n\n\n# +\ndef flatten(x: List) -> List[float]:\n \"\"\"Return data in a list from a list of list\"\"\"\n flat_list = []\n for pred in x:\n for item in pred:\n flat_list.append(item)\n return flat_list\n\nflat_preds = flatten(preds)\nflat_labels = flatten(labels)\nflat_images = flatten(images)\n# -\n\ntest = model.predict_proba(flat_images[0].numpy().reshape(1,48,48,1), batch_size=None)\n\nfrom operator import itemgetter\nfig = plt.figure(figsize=(12,8))\nsample = np.random.randint(0, len(flat_images),size=10)\nfor idx, val in enumerate(sample):\n ax = fig.add_subplot(2,5,idx+1)\n ax.imshow(flat_images[val].numpy().reshape(48,48), cmap='gray')\n ax.set_title(f\"Label = {label_map[flat_label[val]]}\", color='white')\n ax.set_xlabel(f'prediction = {label_map[flat_preds[val]]}',color='white')\n\n# ## Real-time Facial Expression Classification\n#\n# It's time we apply our emotion classifier in on streaming videos. There are a few things I'm not talking in detail here. Our real time classifier is implemented in combination with an object detection model - Mobilenet SSD (short for Single Shot Detection). Our emotion classifier needs facial images to be able to classify them into emotions. In a streaming video, the images are the frames per second of the video. The important thing here is the facial image in the video. We need a model that could capture facial images in the frames of the video in continuously feed them to our emotion classifier. This is where the Mobilenet SSD comes from. If you want to dig deeper, please refer to ([TO DO] more here)\n\n# +\nimport cv2\nfrom imutils.video import VideoStream\nfrom imutils.video import FPS\nimport time\nlabel_map = {0:'Anger', 1:'Disgust', 2:'Fear', 3:'Happy', 4:'Sad', 5:'Surprise', 6:'Neutral'}\n\n# load our serialized face detector from disk\nprint(\"[INFO] loading face detector...\")\nprotoPath = os.path.sep.join([\"face_detection_model\", \"deploy.prototxt\"])\nmodelPath = os.path.sep.join([\"face_detection_model\",\n \"res10_300x300_ssd_iter_140000.caffemodel\"])\ndetector = cv2.dnn.readNetFromCaffe(protoPath, modelPath)\n\n\n# Loading\nmodel_path = './models/bn_dp_image_augmentation/bn_dp_augmentation.h5'\nmodel = tf.keras.models.load_model(model_path)\n\n# initialize the video stream, then allow the camera sensor to warm up\nprint(\"[INFO] starting video stream...\")\nvs = VideoStream(src=0).start()\ntime.sleep(2.0)\n\n# start the FPS throughput estimator\nfps = FPS().start()\n\n# loop over frames from the video file stream\nwhile True:\n # grab the frame from the threaded video stream\n frame = vs.read()\n\n # resize the frame to have a width of 600 pixels (while\n # maintaining the aspect ratio), and then grab the image\n # dimensions\n frame = imutils.resize(frame, width=600)\n (h, w) = frame.shape[:2]\n\n # construct a blob from the image\n imageBlob = cv2.dnn.blobFromImage(\n cv2.resize(frame, (300, 300)), 1.0, (300, 300),\n (104.0, 177.0, 123.0), swapRB=False, crop=False)\n\n # apply OpenCV's deep learning-based face detector to localize\n # faces in the input image\n detector.setInput(imageBlob)\n detections = detector.forward()\n\n # loop over the detections\n for i in range(0, detections.shape[2]):\n # extract the confidence (i.e., probability) associated with\n # the prediction\n confidence = detections[0, 0, i, 2]\n\n # filter out weak detections\n if confidence > 0.5:\n # compute the (x, y)-coordinates of the bounding box for\n # the face\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n # extract the face region of interest\n face = frame[startY:endY, startX:endX] # The result is a numpy.darray \n (fH, fW) = face.shape[:2]\n\n # ensure the face width and height are sufficiently large\n if fW < 20 or fH < 20:\n continue\n\n # Preprocess data for our model\n # It requires gray scale images of shape (48,48,1)\n face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)\n face = cv2.resize(face, (48,48))\n face = face.reshape(1,48,48,1)\n # perform classification to recognize the face\n preds = model.predict_proba(face, batch_size=None)\n j = np.argmax(preds[0])\n proba = preds[0][j]\n name = label_map[j]\n\n # draw the bounding box of the face along with the\n # associated probability\n text = \"{}: {:.2f}%\".format(name, proba * 100)\n y = startY - 10 if startY - 10 > 10 else startY + 10\n cv2.rectangle(frame, (startX, startY), (endX, endY),\n (0, 0, 255), 2)\n cv2.putText(frame, text, (startX, y),\n cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)\n\n # update the FPS counter\n fps.update()\n\n # show the output frame\n cv2.imshow(\"Frame\", frame)\n key = cv2.waitKey(1) & 0xFF\n\n # if the `q` key was pressed, exit the program\n if key == ord(\"q\"):\n break\n\n# stop the timer and display FPS information\nfps.stop()\nprint(\"[INFO] elasped time: {:.2f}\".format(fps.elapsed()))\nprint(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n\n# do a bit of cleanup\ncv2.destroyAllWindows()\nvs.stop()\n# -\n\nj = np.argmax(test[0])\n\n\ntest[0]\n\nj\n\n\n" }, { "alpha_fraction": 0.7435897588729858, "alphanum_fraction": 0.7487179636955261, "avg_line_length": 16.81818199157715, "blob_id": "3e930ea85defa77f409271cb7e04741bf396e1ef", "content_id": "0559a2a44ca92a2e22824d89f5ad85ecfc5ae686", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 195, "license_type": "no_license", "max_line_length": 70, "num_lines": 11, "path": "/ComputerVision/Image_Denoising/README.md", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# Image Denoising\n\nBuild an encoder-decoder model to denoise MNIST images\n\n## Requirement\n\n1. [Anaconda](https://www.anaconda.com/distribution/#download-section)\n\n## Set Up\n\nPlease refer [here]()" }, { "alpha_fraction": 0.7594433426856995, "alphanum_fraction": 0.7833002209663391, "avg_line_length": 30.5, "blob_id": "fb063b2f4dd5ae0bbca782be376b7614ccf92ff1", "content_id": "819bec4602f4e75996b9ea165a0052dffb9c97fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 507, "license_type": "no_license", "max_line_length": 158, "num_lines": 16, "path": "/ComputerVision/Image_Segmentation/README.md", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# Image Segmentation\n\nUsing FCn8 and Unet architecture to segment images from cityscape images\n\n## Data\n\n[Cityscape](https://www.cityscapes-dataset.com/) dataset contains a diverse set of stereo video sequences recorded in street scenes from 50 different cities, \nwith high quality pixel-level annotations of 5 000 frames in addition to a larger set of 20 000 weakly annotated frames.\n\n## Requirement\n\n[Anaconda](https://www.anaconda.com/distribution/#download-section)\n\n## Set up\n\nPlease refer [here]()" }, { "alpha_fraction": 0.7796609997749329, "alphanum_fraction": 0.7881355881690979, "avg_line_length": 23.625, "blob_id": "b7e16c7eb026f30207e98ea61456199df8525350", "content_id": "b5fd0393dd7971b55d0650fa583a19dc3c0071b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 590, "license_type": "no_license", "max_line_length": 82, "num_lines": 24, "path": "/NLP/README.md", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# Introduction\n\nThis repository contains my NLP projects (using Deep Learning techniques)\n\n## Requirement\n\n- [Anaconda](https://www.anaconda.com/distribution/#download-section)\n\nIn order to run the notebooks in this repository: \n\n1. Clone the repository to your local machine. You should\nhave Anaconda installed already.\n\n2. Open Anaconda command terminal and move to the directory that contains the repo\n\n3. Type this code and let Anaconda create the virtual environment\n\n> conda env create -f environment.yml\n\n4. Activate the environment\n\n> conda activate nlp\n\n5. Fire up jupyter notebook" }, { "alpha_fraction": 0.7467105388641357, "alphanum_fraction": 0.7878289222717285, "avg_line_length": 32.77777862548828, "blob_id": "5f7d43ded8eb95f008754bd2e42266472ee80f85", "content_id": "b41b1edd56d74446a860666fa2509c4ee3d9ecf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 608, "license_type": "no_license", "max_line_length": 120, "num_lines": 18, "path": "/README.md", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# Deep Learning\n\nThis is my repository for deep learning related projects\n\n## Computer Vision\n\n1. [Facial Expression](https://github.com/tung2921/Facial-Expression-Classifier)\n2. Image Denoising\n3. Image Segmentation (Incomplete)\n4. Resnet\n5. [Super Resolution](https://github.com/tung2921/DeepLearning/tree/master/ComputerVision/Super-Resolution) (Incomplete)\n6. [Image Similarity](https://github.com/tung2921/Similarity-Search) (Incomplete)\n\n## Natural Language Procesing (NLP)\n\n1. Date Normalization (Incomplete)\n2. LSTM Language Translator\n3. [Poem Generator](https://github.com/tung2921/Poem_generator)\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 25.33333396911621, "blob_id": "efbdb82b794ac8539004cfb046667bcef35acbd3", "content_id": "1fb73bcff256e8be82ece3e1e439a19836d6d808", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 315, "license_type": "no_license", "max_line_length": 98, "num_lines": 12, "path": "/NLP/Poem_generator/README.md", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# Introduction\n\nUsing Recurrent Neural Network (GRU) to create a character-level language model. \nThe model is trained on The Sonnets written by Shakespeare to generate Shakespear-like style poem.\n\n## Requirement\n\n[Anaconda](https://www.anaconda.com/distribution/#download-section)\n\n## Set Up\n\nPlease refer [here]()" }, { "alpha_fraction": 0.7621621489524841, "alphanum_fraction": 0.7729730010032654, "avg_line_length": 22.0625, "blob_id": "aab10e2b272c261026077080aa5091c2e47ecb7d", "content_id": "6dabded380c5d772842b67a2830503e388dbde94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 370, "license_type": "no_license", "max_line_length": 77, "num_lines": 16, "path": "/NLP/LSTM_languageTranslator/README.md", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# Neural Language Translation\n\nUsing Recurrent Neural Network to build an encoder-decoder for language\ntranslation with Tensorflow\n\n## Data\n\ndata is downloaded from [here](http://www.manythings.org/anki/)\n\n## Requirement\n\n[Anaconda](https://www.anaconda.com/products/individual)\n\n## Set Up\n\nPlease refer [here](https://github.com/tung2921/DeepLearning/tree/master/NLP)\n\n" }, { "alpha_fraction": 0.7607476711273193, "alphanum_fraction": 0.7738317847251892, "avg_line_length": 27.210525512695312, "blob_id": "4dc55b33656384d0a5a4d2a4f05f4e68e290bd89", "content_id": "0af3e59608e54a624d5ec21daa41bd80b95b2021", "detected_licenses": [ "CC-BY-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 537, "license_type": "permissive", "max_line_length": 104, "num_lines": 19, "path": "/ComputerVision/Super-Resolution/README.md", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# Image Super Resolution\n\nImplementing Unet encoder-decoder architecture to enhance images quality\n\n## Data \n\n[rock-paper-scissors](http://www.laurencemoroney.com/rock-paper-scissors-dataset/)\n\nRock Paper Scissors is a dataset containing 2,892 images of diverse hands in Rock/Paper/Scissors poses. \nIt is licensed CC By 2.0 and available for all purposes, but it’s intent is primarily for learning and \nresearch. \n\n## Requirement\n\n1. [Anaconda](https://www.anaconda.com/distribution/#download-section)\n\n## Set up\n\nPlease refer [here]()" }, { "alpha_fraction": 0.7658689022064209, "alphanum_fraction": 0.7845993638038635, "avg_line_length": 27.878787994384766, "blob_id": "c4bd6f4d9f9cb6026d1d047fce09d593c2068d9b", "content_id": "5a71c3102c95f466b8f897c5a180a17ded7bd924", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 961, "license_type": "no_license", "max_line_length": 204, "num_lines": 33, "path": "/ComputerVision/README.md", "repo_name": "tung2921/FacialExpression", "src_encoding": "UTF-8", "text": "# Computer Vision\n\nThis repo contains my projects in Computer Vision\n\n## Projects\n\n1. Facial Expression Classifier\n\nCombining object detection and image classification to build a real-time expression\nclassifier \n\n2. Image Denoising\n\nDenoise MNIST images using an encoder-decoder model\n\n3. Image Segmentation (Not complete)\n\nImplementing FCn8 and Unet architecture to create encoder-decoder models to segment\nimages using cityscape images \n\n4. Resnet (Not complete)\n\nImplementing Resnet architecture from scratch\n\n5. Super resolution\n\nImplementing Unet encoder-decoder to enchance hand images quality\n\n6. TFDS - Tensorflow Dataset\n \n 1. TF-Hub models: [Inceptionv3 and Mobilenetv2 classification on cifar10 image dataset ](./TFDS/TF-Hub)\n \n [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/tung2921/DeepLearning/blob/master/ComputerVision/TFDS/TF-Hub/Cifar10.Tf-hub.ipynb)\n \n \n" } ]
12
andrada-tapuc/invoice-extraction-tesseract
https://github.com/andrada-tapuc/invoice-extraction-tesseract
577a13435f7421c791c4199aeb83a5c3ebc5ab55
a00fcdb9c5ab7754e64117a18d0ccab8d573d1c8
57a58e9df3dddef3944a3280335668cbdb1a9df0
refs/heads/master
2022-10-01T01:33:16.114463
2020-06-07T11:26:15
2020-06-07T11:26:15
261,848,287
0
0
null
2020-05-06T18:40:19
2020-05-06T17:34:14
2020-05-06T17:34:12
null
[ { "alpha_fraction": 0.6078066825866699, "alphanum_fraction": 0.6078066825866699, "avg_line_length": 25.899999618530273, "blob_id": "7f57a1f5506a44289257c49e1c63ac6ca49ede3e", "content_id": "94229509dfbc1c8a90e435432dde6b535885926b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 538, "license_type": "no_license", "max_line_length": 58, "num_lines": 20, "path": "/TableProcessing/header.py", "repo_name": "andrada-tapuc/invoice-extraction-tesseract", "src_encoding": "UTF-8", "text": "class Header:\n\n def __init__(self):\n self.list_of_proprieties = []\n self.ordered_list = []\n self.path_to_header_txt = \"final/header_tabel.txt\"\n\n def add_proprieties(self, prop):\n self.list_of_proprieties.append(prop)\n\n def sort_list(self):\n self.list_of_proprieties.reverse()\n\n def print_props(self):\n print(self.list_of_proprieties)\n\n def save_to_file(self):\n file = open(self.path_to_header_txt, \"w\")\n file.writelines(self.list_of_proprieties)\n file.close()\n" }, { "alpha_fraction": 0.5811138153076172, "alphanum_fraction": 0.5811138153076172, "avg_line_length": 23.352941513061523, "blob_id": "0bfd6a762e42a72fd16273505b8ebc32864ab062", "content_id": "0d1d1d4ec53f48fd49e54d30794d0ce54f85d93c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "no_license", "max_line_length": 55, "num_lines": 17, "path": "/TableProcessing/cells.py", "repo_name": "andrada-tapuc/invoice-extraction-tesseract", "src_encoding": "UTF-8", "text": "import json\nclass Cells:\n\n def __init__(self):\n self.cells_dic = {}\n self.path_to_bodyr_txt = \"final/body_tabel.txt\"\n\n def add_cell(self, index, value):\n self.cells_dic[index] = value\n\n def print_dict(self):\n print(self.cells_dic)\n\n def save_to_file(self):\n file = open(self.path_to_bodyr_txt, \"w\")\n file.write(json.dumps(self.cells_dic))\n file.close()" }, { "alpha_fraction": 0.7694013118743896, "alphanum_fraction": 0.7782704830169678, "avg_line_length": 36.58333206176758, "blob_id": "7c5215d657d90d05bb4bdc325ce91254d85f5d85", "content_id": "85c23b8856d42a45c19b1298a25c8910b3fa353e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 451, "license_type": "no_license", "max_line_length": 88, "num_lines": 12, "path": "/main.py", "repo_name": "andrada-tapuc/invoice-extraction-tesseract", "src_encoding": "UTF-8", "text": "from HeaderRecognition import recognitionTypeHeader\nfrom TableProcessing import detectTableWithCv2\n\nfile = r'C:\\Faculty\\Master1\\Invoice\\invoice-extraction-tesseract\\src\\fact.jpg'\nheader_final = r'C:\\Faculty\\Master1\\Invoice\\invoice-extraction-tesseract\\final\\fact.txt'\n\nif __name__ == '__main__':\n # extract header\n print(recognitionTypeHeader.getContent(file, header_final))\n\n # tabel detect and recognize\n detectTableWithCv2.detect(file)\n" }, { "alpha_fraction": 0.5850832462310791, "alphanum_fraction": 0.6220130324363708, "avg_line_length": 35.31578826904297, "blob_id": "e501bb6245f0d03cff7494a0e98c5f9117f6ba70", "content_id": "ff720945c6d05a34a9430fcfe9877133b899182a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1381, "license_type": "no_license", "max_line_length": 97, "num_lines": 38, "path": "/TableProcessing/detectTableWithCv2.py", "repo_name": "andrada-tapuc/invoice-extraction-tesseract", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom TableProcessing.cellExtraction import extractCells\n\n\ndef detect(file):\n\n im1 = cv2.imread(file, 0)\n im = cv2.imread(file)\n height, width, channels = im.shape\n ret, thresh_value = cv2.threshold(im1, 180, 255, cv2.THRESH_BINARY_INV)\n kernel = np.ones((5, 5), np.uint8)\n dilated_value = cv2.dilate(thresh_value, kernel, iterations=1)\n\n contours, hierarchy = cv2.findContours(dilated_value, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cordinates = []\n flag = True\n for cnt in contours:\n x, y, w, h = cv2.boundingRect(cnt)\n cordinates.append((x, y, w, h))\n # bounding the images\n if y < height and h-x >150 and w-y >150 and h-x < height-50:\n cv2.rectangle(im, (x, y), (x + w, y + h), (0, 0, 255), 1)\n crop_img = im[y+3:y+h, x+3:x+w]\n if flag:\n header_img = im[0:h, 0:width]\n cv2.imwrite('TableProcessing/result/header.jpg', header_img)\n flag = False\n cv2.namedWindow('crop', cv2.WINDOW_NORMAL)\n cv2.imwrite('TableProcessing/result/crop.jpg', crop_img)\n\n\n cv2.namedWindow('detecttable2', cv2.WINDOW_NORMAL)\n cv2.imwrite('TableProcessing/result/detecttable2.jpg', im)\n\n myCells = extractCells('TableProcessing/result/crop.jpg')\n myCells.save_to_file()\n\n" } ]
4
AranGarcia/HumiditySensor
https://github.com/AranGarcia/HumiditySensor
c0be1713ab7db520706404bb249605d8404b0b7f
5426ef8d765857926bde686423ce5097249b9adb
a267109af06f1e5100b87be78b571052fa9e151c
refs/heads/master
2020-04-01T20:01:52.167296
2018-10-26T06:44:09
2018-10-26T06:44:09
153,584,716
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5065789222717285, "alphanum_fraction": 0.6973684430122375, "avg_line_length": 15.88888931274414, "blob_id": "718715fd99b55a0d6b73de83fb60dbe61bf5ddcc", "content_id": "d518252557a751015565752e7e044d0eca00594d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 152, "license_type": "no_license", "max_line_length": 22, "num_lines": 9, "path": "/requirements.txt", "repo_name": "AranGarcia/HumiditySensor", "src_encoding": "UTF-8", "text": "cycler==0.10.0\nkiwisolver==1.0.1\nmatplotlib==3.0.0\nnumpy==1.15.2\npkg-resources==0.0.0\npyparsing==2.2.2\npyserial==3.4\npython-dateutil==2.7.3\nsix==1.11.0\n" }, { "alpha_fraction": 0.6147128939628601, "alphanum_fraction": 0.6305900812149048, "avg_line_length": 29.97541046142578, "blob_id": "58d6cdc90f1bb0c377db0dcc11e5e92f62d28230", "content_id": "27328b582c7f4ef506c9b5d4026d5c8675cc68b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3779, "license_type": "no_license", "max_line_length": 112, "num_lines": 122, "path": "/monitor.py", "repo_name": "AranGarcia/HumiditySensor", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport tkinter as tk\nimport matplotlib.animation as animation\nimport serial\n\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom matplotlib.figure import Figure\nfrom tkinter import font\n\nimport util\nfrom arduinoiface import Reader\n\nPROPS = util.get_config()\n\n\nclass CustomWidget:\n \"\"\"\n Abstract class for all widgets. \n\n The create_widghets method is to be overwritten so that the\n widget may be properly intialized.\n \"\"\"\n\n def create_widgets(self):\n raise NotImplementedError\n\n\nclass InfoFrame(tk.Frame, CustomWidget):\n bgcolor = util.rgb(41, 43, 44)\n txcolor = util.rgb(255, 255, 255)\n\n def __init__(self, master):\n super(InfoFrame, self).__init__(master, background=InfoFrame.bgcolor)\n self.pack(side=tk.LEFT, fill=tk.BOTH)\n\n self.create_widgets()\n\n def create_widgets(self):\n\n lblfont = font.Font(family=\"Verdana\")\n\n tk.Label(self, font=lblfont, background=InfoFrame.bgcolor, foreground=InfoFrame.txcolor,\n text=\"Instituto Politecnico Nacional\\nEscuela Superior de Computo\\n\").grid(row=0, columnspan=2)\n tk.Label(self, font=lblfont, background=InfoFrame.bgcolor, foreground=InfoFrame.txcolor,\n text=\"Instrumentacion\").grid(row=1, column=0)\n tk.Label(self, font=lblfont, background=InfoFrame.bgcolor, foreground=InfoFrame.txcolor,\n text=PROPS[\"grupo\"]).grid(row=1, column=1)\n\n names = PROPS[\"integrantes\"].split(\";\")\n lblteam = tk.Label(self, font=lblfont, background=InfoFrame.bgcolor, foreground=InfoFrame.txcolor,\n justify=\"left\", text='\\n'.join(names))\n lblteam.grid(row=3, columnspan=2)\n\n self.measurement = tk.DoubleVar(self, value=0)\n tk.Entry(self, text=\"Valor de prueba\", justify=\"center\", state=\"readonly\",\n textvariable=self.measurement, width=10).grid(row=5, column=0)\n tk.Label(self, font=lblfont, background=InfoFrame.bgcolor, foreground=InfoFrame.txcolor,\n text=\"% de humedad\").grid(row=5, column=1)\n\n self.grid_rowconfigure(2, minsize=100)\n self.grid_rowconfigure(4, minsize=50)\n\n\nclass MonitorCanvas(Figure, CustomWidget):\n def __init__(self, master):\n super(MonitorCanvas, self).__init__(figsize=(5, 4), dpi=100)\n self.master = master\n\n # Plot stuff\n self.liminf = int(PROPS[\"liminf\"])\n self.limsup = int(PROPS[\"limsup\"])\n\n # Serial reader\n self.r = Reader(PROPS[\"port\"], i.measurement,\n int(PROPS[\"seconds\"]) / 0.01)\n\n self.r.start()\n\n self.create_widgets()\n\n def create_widgets(self):\n ax = self.subplots()\n\n self.x = np.arange(0, int(PROPS[\"seconds\"]), 0.01)\n self.y = np.zeros(len(self.x))\n self.line, = ax.plot(self.x, self.y)\n\n ax.set_ylabel(\"Porcentaje de humedad\")\n ax.set_ybound(0, 105)\n self.set_tight_layout(True)\n\n canvas = FigureCanvasTkAgg(self, master=self.master)\n canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)\n\n self.ani = animation.FuncAnimation(\n self, self.animate, init_func=self.init,\n interval=32, blit=True, save_count=50)\n\n canvas.draw()\n\n def init(self):\n self.line.set_ydata(np.zeros(len(self.x)))\n return self.line,\n\n def animate(self, i):\n self.line.set_ydata(self.r.measures)\n return self.line,\n\n\nif __name__ == '__main__':\n root = tk.Tk()\n root.title(\"Sensor de humedad\")\n icon = tk.PhotoImage(file='water-drop.png')\n root.tk.call('wm', 'iconphoto', root._w, icon)\n\n i = InfoFrame(root)\n m = MonitorCanvas(root)\n\n root.mainloop()\n" }, { "alpha_fraction": 0.5439407825469971, "alphanum_fraction": 0.5596669912338257, "avg_line_length": 26.024999618530273, "blob_id": "f197d0fb98e32e22da92375454d1881d8f7fdd5f", "content_id": "284e10d3c3386516ebb7c85475cc019280a1c530", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 66, "num_lines": 40, "path": "/arduinoiface.py", "repo_name": "AranGarcia/HumiditySensor", "src_encoding": "UTF-8", "text": "import serial\nimport threading\nimport numpy\n\n\nclass DoubleVarContainer:\n def __init__(self, container):\n self.container = container\n\n def update(self, value):\n self.container.set(value)\n\n\nclass Reader:\n def __init__(self, port, dvar, size):\n try:\n self.arduino = serial.Serial(port, 115200, timeout=.1)\n except serial.serialutil.SerialException:\n print(\"[ERROR] No se pudo conectar con el arduino.\")\n exit(1)\n self.dvar = DoubleVarContainer(dvar)\n self.t = None\n self.measures = [0 for i in range(int(size))]\n\n def start(self):\n self.t = threading.Thread(target=self.__read)\n self.t.daemon = True\n self.t.start()\n\n def __read(self):\n resolution = 100 / 255\n while True:\n data = self.arduino.read(1)\n\n if data:\n value = int.from_bytes(data, byteorder=\"little\")\n m = value * resolution\n self.dvar.update(m)\n self.measures.pop(0)\n self.measures.append(m)\n" }, { "alpha_fraction": 0.5105485320091248, "alphanum_fraction": 0.5253164768218994, "avg_line_length": 22.649999618530273, "blob_id": "12ca7d7a6abbd03e7bbab9c3d0a6381702875a6b", "content_id": "947f5e9b7be003e040d55696919024947fc5c231", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "no_license", "max_line_length": 58, "num_lines": 20, "path": "/util.py", "repo_name": "AranGarcia/HumiditySensor", "src_encoding": "UTF-8", "text": "def get_config(fname=\"sensor.config\"):\n with open(fname, encoding=\"utf8\") as fobj:\n lines = fobj.readlines()\n \n props = {}\n \n try:\n for l in lines:\n key, value = l.split('=')\n props[key] = value.rstrip('\\n')\n except ValueError:\n print(\"Error al cargar configuracion del sensor.\")\n \n return props\n\ndef rgb(r, g, b):\n return \"#%02x%02x%02x\" % (r, g, b)\n\nif __name__ == \"__main__\":\n print(get_config())\n\n" }, { "alpha_fraction": 0.6814159154891968, "alphanum_fraction": 0.7345132827758789, "avg_line_length": 55, "blob_id": "f79c667a3b2dfe62ad637227a75c75538c66de24", "content_id": "8ffb9d6ded4845ebd891a334000b954b6788f4e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 113, "license_type": "no_license", "max_line_length": 99, "num_lines": 2, "path": "/notes.md", "repo_name": "AranGarcia/HumiditySensor", "src_encoding": "UTF-8", "text": "### Credits\nwater-drop.png made by Wissawa Khamsriwath from [Flaticon](https://www.flaticon.com/free-icon/water-drop_179181)\n\n" } ]
5
zrluety/rmusicbot
https://github.com/zrluety/rmusicbot
a1f368b6cd618547aae31866682b9794469190d4
8e3a2f2c76cbcf3054fdf76f7ed233c30e9ce545
2770d1d2f31169e3b6512600a602776b183d3ea8
refs/heads/master
2020-03-20T19:09:13.982240
2018-06-18T00:15:31
2018-06-18T00:15:31
137,623,994
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5972272753715515, "alphanum_fraction": 0.6008756160736084, "avg_line_length": 28.483871459960938, "blob_id": "e4706ffc22c0c74444d22faf467769d5acdce013", "content_id": "20926d090fd74b723acd6ea573379f187af10d10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2741, "license_type": "no_license", "max_line_length": 82, "num_lines": 93, "path": "/bot.py", "repo_name": "zrluety/rmusicbot", "src_encoding": "UTF-8", "text": "import re\nimport configparser\n\nimport praw\nimport spotipy\nimport spotipy.util as util\nimport requests\n\nfrom requests.exceptions import HTTPError\nfrom pprint import pprint\n\ndef parse_title_for_song_detail(title):\n \"\"\"Get song detail from submission title.\"\"\"\n # r/music posts should include the artist name, song name, and genre in the\n # following format:\n #\n # <artist name> - <song name> [genre]\n pattern = re.compile(pattern=r\"(.*)\\s-\\s(.*)\\s?(\\[.*\\])\")\n\n # search title for pattern\n match = pattern.search(title)\n if match:\n return {\n 'artist': match.group(1).rstrip().replace('\"', ''),\n 'name': match.group(2).rstrip().replace('\"', ''),\n 'genre': match.group(3).rstrip().replace('\"', ''),\n 'title': title.rstrip().replace('\"', ''),\n }\n \n return None\n\ndef main(n=10):\n # User-Agent string should be something unique and descriptive, including the\n # target platform, a unique application identifier, a version string, and your\n # username as contact information, in the following format:\n #\n # <platform>:<app ID>:<version string> (by /u/<reddit username>)\n user_agent = \"python:r/music playlist generator:v0.0.1 (by /u/zrluety\"\n\n # create Reddit object\n r = praw.Reddit(user_agent=user_agent,\n site_name='MUSIC_BOT')\n\n subreddit = r.subreddit('music')\n songs = []\n \n # iterate through hot submissions to create a list of n songs\n for submission in subreddit.hot():\n title = submission.title\n\n # get song info from posts\n song = parse_title_for_song_detail(title)\n if song:\n songs.append(song)\n \n if len(songs) >= n:\n break\n\n spotify_config = configparser.ConfigParser()\n spotify_config.read('config.ini')\n\n token = util.prompt_for_user_token(\n username='Zachary Luety',\n scope='playlist-modify-public',\n client_id=spotify_config['SPOTIFY']['client_id'],\n client_secret=spotify_config['SPOTIFY']['secret'],\n redirect_uri='http://localhost/'\n )\n\n # create Spotify object\n spotify = spotipy.Spotify(auth=token)\n\n tracks = []\n for song in songs:\n # search for the track\n result = spotify.search(q=song.get('name'), limit=1)\n\n # get the track id\n try:\n track = result.get('tracks').get('items')[0].get('id')\n tracks.append(track)\n except HTTPError:\n continue\n\n # get playlists\n playlist = spotify.user_playlist_add_tracks(\n user=spotify_config['SPOTIFY']['user_id'],\n playlist_id=spotify_config['SPOTIFY']['playlist_id'],\n tracks=tracks\n )\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.8070175647735596, "alphanum_fraction": 0.8070175647735596, "avg_line_length": 27.5, "blob_id": "2f4b4724235754eac7b1137a67b4be5597d20bce", "content_id": "dd870897a81465cc71edf462c548175e7e8da91f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 57, "license_type": "no_license", "max_line_length": 44, "num_lines": 2, "path": "/README.md", "repo_name": "zrluety/rmusicbot", "src_encoding": "UTF-8", "text": "# rmusicbot\ncreate a spotify playlist from r/music posts\n" } ]
2
sahorgan/my-first-blog
https://github.com/sahorgan/my-first-blog
c2fd2b54715ca8ea9a2ff9aae2fd0bd2cab26c3b
5d9672abbab451d4e272dd666064bb022b91bad9
38bcbb72f2e95c9e43f6694eb5136aa27c032e01
refs/heads/master
2020-04-11T20:49:16.127938
2018-12-18T07:22:46
2018-12-18T07:22:46
162,084,037
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7870370149612427, "alphanum_fraction": 0.7870370149612427, "avg_line_length": 20.799999237060547, "blob_id": "c7957f93d24eb3b1735318b2b2829b1083e2bad8", "content_id": "c8347278aa48711612bfdc58327aa31a96cf3f6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 108, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/blog/admin.py", "repo_name": "sahorgan/my-first-blog", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Post\n\n# password = djangogirls\nadmin.site.register(Post)" } ]
1
zkneupper/Instacart-Prediction-Capstone
https://github.com/zkneupper/Instacart-Prediction-Capstone
ec76b078a5206d69064942f59b62984a67fde827
3b3ce1fb25e3c4d4a00454959f2bc15a5ad438cf
cfa4998ee671e5f61f4928537e03c22b5987672a
refs/heads/master
2021-09-10T06:32:38.529811
2018-03-21T16:02:15
2018-03-21T16:02:15
106,613,620
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7400793433189392, "alphanum_fraction": 0.7577030658721924, "avg_line_length": 50.92121124267578, "blob_id": "293150001046bf055cd91d3d3e64dd57e29ba7a8", "content_id": "1842300416e246f4f8fe7b2f618145367fc532b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8572, "license_type": "permissive", "max_line_length": 604, "num_lines": 165, "path": "/reports/Milestone-Report.md", "repo_name": "zkneupper/Instacart-Prediction-Capstone", "src_encoding": "UTF-8", "text": "\n# Milestone Report For Capstone Project 2: Predicting Behavior of Instacart Shoppers\n\nIn this Milestone Report, we will do the following:\n\n1. Define the problem;\n2. Identify our client;\n3. Describe our data set, and how we cleaned/wrangled it;\n4. List other potential data sets we could use; and\n5. Explain our initial findings.\n\n### 1. Define the problem\n\nThe goal of this capstone project is to build a model to predict what grocery items each Instacart user will reorder based on the user's purchase history.\n\n### 2. Identify the client\n\nOur client is Instacart. With the proposed predictive model, Instacart could provide its users with useful purchase recommendations and improve the app's overall user experience. This could help Instacart retain current app users and increase the number of purchases through the app.\n\n### 3. Describe our dataset, and how we cleaned/wrangled it;\n\n#### Our Data Source\n\nLast year, Instacart released a public dataset, “The Instacart Online Grocery Shopping Dataset 2017”. The dataset contains over 3 million anonymized grocery orders from more than 200,000 Instacart users. We use this dataset in our analysis. The dataset can be downloaded [here](https://www.instacart.com/datasets/grocery-shopping-2017)\n\n-----------------------------------\n\n#### Data Description\n\nThe Instacart dataset contains six tables in `.csv` format:\n\n1. `aisles.csv`\n2. `deptartments.csv`\n3. `order_products__prior.csv`\n4. `order_products__train.csv`\n5. `orders.csv`\n6. `products.csv`\n\nA more detailed description of these tables is as follows:\n\n\n`orders` (3.4m rows, 206k users):\n* `order_id`: order identifier\n* `user_id`: customer identifier\n* `eval_set`: which evaluation set this order belongs in (see `SET` described below)\n* `order_number`: the order sequence number for this user (1 = first, n = nth)\n* `order_dow`: the day of the week the order was placed on\n* `order_hour_of_day`: the hour of the day the order was placed on\n* `days_since_prior`: days since the last order, capped at 30 (with NAs for `order_number` = 1)\n\n`products` (50k rows):\n* `product_id`: product identifier\n* `product_name`: name of the product\n* `aisle_id`: foreign key\n* `department_id`: foreign key\n\n`aisles` (134 rows):\n* `aisle_id`: aisle identifier\n* `aisle`: the name of the aisle\n\n`deptartments` (21 rows):\n* `department_id`: department identifier\n* `department`: the name of the department\n\n`order_products__SET` (30m+ rows):\n* `order_id`: foreign key\n* `product_id`: foreign key\n* `add_to_cart_order`: order in which each product was added to cart\n* `reordered`: 1 if this product has been ordered by this user in the past, 0 otherwise\n\nwhere `SET` is one of the four following evaluation sets (`eval_set` in `orders`):\n* `\"prior\"`: orders prior to that users most recent order (~3.2m orders)\n* `\"train\"`: training data supplied to participants (~131k orders)\n* `\"test\"`: test data reserved for machine learning competitions (~75k orders)\n\n(Source: https://gist.github.com/jeremystan/c3b39d947d9b88b3ccff3147dbcf6c6b)\n\n#### Data Wrangling & Feature Engineering\n\nOur first step in wrangling the Instacart dataset was to take the contents of the six `.csv` files and store them in one SQLite database.\n\nWe then used SQL to transform the dataset to create a new table that we could use to train and test our machine learning model.\n\n##### The Index\n\nWe created a list of unique pairs of users and products from the `prior` set of orders. We gave this list the label \"`up_pair`\" for \"user-product pair\". This list was used as a unique index of our final data table.\n\n##### The Target\n\nWe created a binary target variable `y` for whether or not a user reordered a product.\n\nFor each unique pair of user and product from the `prior` set of orders, if the user bought the product in the `prior` set of orders *and* reordered the product in the `train` set of orders, then our target variable `y` is assigned the value 1. On the other hand, if the user bought the product in the `prior` set, but they didn't reorder the product in the `train` set, then our target variable `y` is assigned the value 0.\n\n##### The Features\n\nWe engineered five explanatory features. These features are as follows:\n\nGiven the user-product pair of (User A, Product B),\n\n1. `total_buy_n5`: the total number of times User A bought Product B out of the 5 most recent orders.\n\n2. `total_buy_ratio_n5`: the proportion of User A's 5 most recent orders in which User A bought Product B.\n\n3. `order_ratio_by_chance_n5`: the proportion of User A's 5 most recent orders in which User A had the \"chance\" to buy B, and did indeed do so. Here, a \"chance\" refers to the number of opportunities the user had for buying the item after first encountering (*viz.*, buying) it. For example, if a User A bought Product B for the first time in their 4th most recent order, then the user would have had 4 chances to buy the product. If that user had bought the product only in their 4th and 2nd most recent orders, then `order_ratio_by_chance_n5` would be 0.5 (*i.e., (1+1)/4) for that user-product pair.\n\n4. `useritem_order_days_max_n5`: the longest number of days that User A has recently gone without buying Product B. We are only considering the 5 most recent orders.\n\n5. `useritem_order_days_min_n5`: the shortest number of days that User A has recently gone without buying Product B. Again, we are only considering the 5 most recent orders.\n\n\nThe choice of these five features was inspired by [Onodera's solution](http://blog.kaggle.com/2017/09/21/instacart-market-basket-analysis-winners-interview-2nd-place-kazuki-onodera/]), which won 2nd place in the Instacart Kaggle competition.\n\n### 4. List other potential data sets we could use\n\nWe did not deem it appropriate or necessary to use any additional sources of data.\n\n### 5. Explain our initial findings\n\n\n#### The Target is Imbalanced\n\nWe found that our target variable `y` is quite imbalanced. Among all of the \"user-product pairs\" considered, only about 6% of the samples had reorders.\n\n#### Bivariate Visualizations\n\nWe visualized how the proportion of reorders varies with each feature.\n\n\n\nFirst, we plotted the how the proportion of reorders varies with the feature `total_buy_n5`, which is the total number of times User A bought Product B out of the 5 most recent orders. We found that the proportion of reorders increases linearly with `total_buy_n5`.\n\n<img src=\"figures/EDA_Reorders_by_total_buy_n5.png\" width=450>\n\nNext, we plotted the how the proportion of reorders varies with the feature `order_ratio_by_chance_n5`, which is the proportion of User A's 5 most recent orders in which User A had the \"chance\" to buy B, and did indeed do so. We found that the proportion of reorders generally increases with `order_ratio_by_chance_n5`.\n\n<img src=\"figures/EDA_Reorders_by_order_ratio_by_chance_n5.png\" width=450>\n\nWe then plotted the how the proportion of reorders varies with `useritem_order_days_max_n5` and `useritem_order_days_min_n5`, respectively. We found that the proportion of reorders generally decreases nonlinearly with both of these features.\n\n<img src=\"figures/EDA_Reorders_by_useritem_order_days_max_n5.png\" width=450>\n<img src=\"figures/EDA_Reorders_by_useritem_order_days_min_n5.png\" width=450>\n\n#### PCA for Data Visualization\n\n\nIn order to better visualize the data, we used principal component analysis to reduce the dimensionality of the feature set.\n\nThe plot below shows two overlaid histograms, where the x-axis is the first principal component and the y-axis the number of reorders or non-reorders. The red histograms is for reorders. The blue histograms is for non-reorders. \n\n<img src=\"figures/EDA_histogram_pc_1.png\" width=450>\n\nBelow is the same type of plot as above, but here, the x-axis represents the second principal component\n\n<img src=\"figures/EDA_histogram_pc_2.png\" width=450>\n\nFrom the previous two plots, the two categories do not appear to be easily separable in our feature space.\n\nAdditionally, we created two hexbin plots, where the x-axis represents the first principal component and the y-axis represents the second principal component.\n\nThe first hexbin plot shows how *reordered* observations are distributed in the feature space.\n<img src=\"figures/EDA_jointplot_reordered.png\" width=400>\n\nThe second hexbin plot shows how *non-reordered* observations are distributed in the feature space.\n<img src=\"figures/EDA_jointplot_not_reordered.png\" width=400>\n\nBuilding a classification algorithm for this imbalanced and apparently inseparable dataset may prove challenging.\n" }, { "alpha_fraction": 0.6108224987983704, "alphanum_fraction": 0.6277056336402893, "avg_line_length": 31.08333396911621, "blob_id": "6842c185c07f7822d803c87669b4e86940312757", "content_id": "3c44162ccf294a68391fed985d88774380ae9efc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2310, "license_type": "permissive", "max_line_length": 76, "num_lines": 72, "path": "/src/data/create_sqlitedb.py", "repo_name": "zkneupper/Instacart-Prediction-Capstone", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport pandas as pd\nfrom re import sub\nfrom sqlalchemy import create_engine\n\n# Create paths to data folders\nprint(\"Setting file paths...\")\n\n# Create a variable for the project root directory\n#proj_root = os.path.join(os.pardir)\nproj_root = os.path.join(os.pardir, os.pardir)\n\n# Save the path to the folder containing the original, immutable data dump:\n# /data/raw/instacart_2017_05_01\nraw_data_dir = os.path.join(proj_root,\n \"data\",\n \"raw\",\n \"instacart_2017_05_01\")\n\n# Save the path to the folder that will contain the intermediate data \n# that will be transformed: /data/interim\ninterim_data_dir = os.path.join(proj_root,\n \"data\",\n \"interim\")\n\n# Save the path to the SQLite databse we will create in /data/interim\ndb_name = 'instacart_2017_05_01.db'\n\ninterim_sqlitedb = os.path.join('sqlite:///',\n interim_data_dir,\n db_name)\n\n# Put the contents of csv files into a sqlite database\nprint(\"Building SQLite database...\")\n\n# Create list of data files\nraw_data_files = os.listdir(raw_data_dir)\n\n# Create list of table names\ntable_names = [sub('.csv', '', fn) for fn in raw_data_files]\n\n# Create a sqllite database\nengine = create_engine(interim_sqlitedb)\n\n# Set the chunksize to 100,000 to keep the size of the chunks managable.\nchunksize = 100000\n\n# Iterate over each csv file in chunks and store the data \n# from each csv file in its own table in the sqllite database\n\nfor i in range(len(raw_data_files)):\n\n print(\"Building {} table...\".format(table_names[i]))\n\n file_dir = os.path.join(raw_data_dir, raw_data_files[i])\n \n # Initialize iterator variables\n j = 1\n\n # Set the table name\n table_name = sub('.csv', '', raw_data_files[i])\n \n for df in pd.read_csv(file_dir, chunksize=chunksize, iterator=True):\n # Make sure column names won't contain spaces.\n df = df.rename(columns={c: c.replace(' ', '_') for c in df.columns})\n # Set index values and table values\n df.index += j\n df.to_sql(table_name, engine, if_exists='append')\n j = df.index[-1] + 1\n\nprint(\"Finished! The SQLite database has been built\")\n" }, { "alpha_fraction": 0.6490675210952759, "alphanum_fraction": 0.6585237979888916, "avg_line_length": 38.65625, "blob_id": "9be2f6073d3224185a1dcf21d8464ba15b16919f", "content_id": "af201a542ce913a2d6907a798af69cfacefc2efc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4011, "license_type": "permissive", "max_line_length": 298, "num_lines": 96, "path": "/README.md", "repo_name": "zkneupper/Instacart-Prediction-Capstone", "src_encoding": "UTF-8", "text": "![logo](reports/images/Instacart_logo_and_wordmark.svg.png)\n\n\nPredicting Behavior of Instacart Shoppers\n==========================================\n\n[Kaggle.com](kaggle.com) recently hosted the Instacart Market Basket Analysis competition. The goal of this competition was to predict what grocery items each Instacart user will reorder based on the user's purchase history.\n\nKazuki Onodera, a data scientist at Yahoo! JAPAN, won second place in the competition. Onodera was able to take the original dataset and engineer some strongly predictive new features. \n\nIn this project, I engineered a subset of the most important features identified by Onodera. I trained a gradient boosting model to predict the probability that a user will reorder any given product that they had previously ordered. \n\nI was able to achieve a mean cross-validated ROC AUC score of 0.79.\n\n------------\n\nKeywords: Consumer behavior; Machine learning; Gradient boosting; XGBoost\n\n------------\n\n\n## Table of Contents\n\n[Process Overview and Tech Stack](#process-overview-and-tech-stack) \n[Final Report](#final-report) \n[GitHub Folder Structure](#github-folder-structure) \n[References](#references) \n[Acknowledgements](#acknowledgements)\n\n------------\n\n## Process Overview and Tech Stack\n\n![tech-stack](reports/images/tech-stack.png)\n\n------------\n\n## Final Slide Deck and Final Report\n\nThe final slide deck for this project can be found [here](https://github.com/zkneupper/Instacart-Prediction-Capstone/tree/master/reports/Final_Slide_Deck.pdf), and the final report can be found [here](https://github.com/zkneupper/Instacart-Prediction-Capstone/tree/master/reports/Final_Report.pdf).\n\n------------\n\n## GitHub Folder Structure\n\n ├── LICENSE\n ├── README.md <- The top-level README for this project.\n ├── data\n │   ├── interim <- Intermediate data that has been transformed.\n │   ├── processed <- The final, canonical data sets for modeling.\n │   └── raw <- The original, immutable data dump.\n │\n ├── models <- Trained and serialized models\n │\n ├── notebooks <- Jupyter notebooks.\n │\n ├── references <- Dataset descriptions.\n │\n ├── reports <- Generated analysis as PDF reports and Jupyter notebooks.\n │   └── figures <- Generated graphics and figures to be used in reporting\n │   └── images \n │\n └── src <- Source code for use in this project.\n    ├── __init__.py <- Makes src a Python module\n    │ \n ├── data <- Scripts to download or generate data\n    │   └── make_dataset.py\n    │\n    ├── features <- Scripts to turn raw data into features for modeling\n    │   └── build_features.py\n    │\n    └── models <- Scripts to train models and then use trained models to make\n       │ predictions\n       ├── predict_model.py\n       └── train_model.py\n\n------------\n\n## References\n\n1. [“The Instacart Online Grocery Shopping Dataset 2017”](https://www.instacart.com/datasets/grocery-shopping-2017), accessed on June 25, 2017.\n\n2. [Instacart Market Basket Analysis](https://www.kaggle.com/c/instacart-market-basket-analysis#description) challenge on www.kaggle.com.\n\n3. [\"Instacart Market Basket Analysis, Winner's Interview: 2nd place, Kazuki Onodera\"](http://blog.kaggle.com/2017/09/21/instacart-market-basket-analysis-winners-interview-2nd-place-kazuki-onodera/) by Edwin Chen, dated September 21, 2017.\n\n\n------------\n\n## Acknowledgements\n\nThis was one of my capstone projects for the Data Science Career Track program at [Springboard](https://www.springboard.com/workshops/data-science-career-track). \n\nI would like to thank my mentor Kenneth Gil-Pasquel for his guidance and feedback. \n\n------------\n" }, { "alpha_fraction": 0.5014976263046265, "alphanum_fraction": 0.5229929089546204, "avg_line_length": 42.215736389160156, "blob_id": "19e139a4744dbc051cefeb4a6a8097f78eb02a74", "content_id": "0568d927c2bd4748d937a0e3b424b319be0a8b27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17027, "license_type": "permissive", "max_line_length": 119, "num_lines": 394, "path": "/src/features/build_features.py", "repo_name": "zkneupper/Instacart-Prediction-Capstone", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport sqlite3\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.engine.reflection import Inspector\nimport csv\nimport pandas as pd\nfrom shutil import copy2\n\n# Create paths to data folders\nprint(\"Setting file paths...\")\n\n# Create a variable for the project root directory\n#proj_root = os.path.join(os.pardir)\nproj_root = os.path.join(os.pardir, os.pardir)\n\n# Save the path to the folder that will contain the intermediate data \n# that will be transformed: /data/interim\ninterim_data_dir = os.path.join(proj_root,\n \"data\",\n \"interim\")\n\n# Save the path to the SQLite databse containing the untransformed\n# Instacart data\ndb_name = 'instacart_2017_05_01.db'\n\ninterim_sqlitedb_path = os.path.join(interim_data_dir,\n db_name)\n\ninterim_sqlitedb_eng = os.path.join('sqlite:///',\n interim_sqlitedb_path)\n\n# Save the path to the SQLite database that will contain the transformed\n# Instacart data\ndb_name_tf = 'instacart_transformed.db'\n\ntransformed_sqlitedb_path = os.path.join(interim_data_dir,\n db_name_tf)\n\n# Save the engine path to the SQLite database that will contain the \n# transformed Instacart data\ntransformed_sqlitedb_eng = os.path.join('sqlite:///',\n transformed_sqlitedb_path)\n\n\n# Save the path to the folder that will contain the final,\n# processed data: /data/processed\nprocessed_data_dir = os.path.join(proj_root,\n \"data\",\n \"processed\")\n\n# Save the path to the csv file that will contain the final,\n# processed Instacart data\nfinal_csv_name = 'instacart_final.csv'\n\nfinal_csv_path = os.path.join(processed_data_dir,\n final_csv_name)\n\n\n# Put the contents of csv files into a sqlite database\nprint(\"Copying the untransformed database...\")\n\n# Make a copy of the untransformed database.\ncopy2(interim_sqlitedb_path, transformed_sqlitedb_path)\n\n# Create a connection to the new database\nprint(\"Creating a connection to the new database...\")\n\n# Create a sqlite3 connection cursor\nconn = sqlite3.connect(transformed_sqlitedb_path)\nc = conn.cursor()\n\n# Create an engine to the new SQLite database \nengine = create_engine(transformed_sqlitedb_eng, echo=False)\n\n\n### Transform the data and create new views and tables\nprint(\"Creating new views and tables...\")\n\nprint(\"Creating new table 'up_pairs_train'...\")\n\n# Create table\nc.execute('''CREATE TABLE up_pairs_train AS\n SELECT substr('00'||orders.user_id, -6) || '-' || \n substr('0000'||order_products__train.product_id, -6) AS up_pair\n FROM order_products__train\n JOIN orders\n ON orders.order_id = order_products__train.order_id\n GROUP BY up_pair\n ORDER BY user_id ASC, product_id ASC''')\n\n# Save (commit) the changes\nconn.commit()\n\nprint(\"Creating new table 'up_pairs_prior'...\")\n\n# Create table\nc.execute('''CREATE TABLE up_pairs_prior AS\n SELECT substr('00'||orders.user_id, -6) || '-' || \n substr('0000'||order_products__prior.product_id, -6) AS up_pair,\n orders.user_id AS user_id, \n order_products__prior.product_id AS product_id,\n orders.order_number AS order_number\n FROM order_products__prior\n JOIN orders\n ON orders.order_id = order_products__prior.order_id\n ORDER BY user_id ASC, product_id ASC''')\n\n# Save (commit) the changes\nconn.commit()\n\nprint(\"Creating new table 'max_order_by_user'...\")\n\n# Create table\nc.execute('''CREATE TABLE max_order_by_user AS\n SELECT user_id, MAX(order_number) AS max_order_number\n FROM up_pairs_prior\n GROUP BY user_id\n ORDER BY user_id ASC''')\n\n# Save (commit) the changes\nconn.commit()\n\nprint(\"Creating new table 'up_pairs_prior_modified'...\")\n\n# Create table\nc.execute('''CREATE TABLE up_pairs_prior_modified AS\n SELECT up_pairs_prior.*, \n max_order_by_user.max_order_number,\n (1 + max_order_by_user.max_order_number - up_pairs_prior.order_number) AS order_number_rev\n FROM up_pairs_prior\n JOIN max_order_by_user\n ON max_order_by_user.user_id = up_pairs_prior.user_id''')\n\n# Save (commit) the changes\nconn.commit()\n\nprint(\"Creating new table 'first_data_table'...\")\n\n# Create table\nc.execute('''CREATE TABLE first_data_table AS\n SELECT up_pairs_prior_modified.up_pair AS up_pair,\n up_pairs_prior_modified.user_id AS user_id, \n up_pairs_prior_modified.product_id AS product_id, \n CASE WHEN up_pairs_train.up_pair IS NULL THEN 0 ELSE 1 END as 'y',\n SUM(CASE WHEN (order_number_rev <= 5) THEN 1 ELSE 0 END) AS total_buy_n5, \n SUM(CASE WHEN (order_number_rev <= 5) THEN 1 ELSE 0 END) / 5.0 AS total_buy_ratio_n5, \n MAX(order_number_rev) AS max_order_number_rev,\n CASE WHEN MAX(order_number_rev) > 5\n THEN (SUM(CASE WHEN (order_number_rev <= 5) THEN 1 ELSE 0 END) / 5.0)\n ELSE (SUM(CASE WHEN (order_number_rev <= 5) THEN 1 ELSE 0 END) /\n (MAX(order_number_rev) * 1.0))\n END AS order_ratio_by_chance_n5 \n FROM up_pairs_prior_modified\n LEFT JOIN up_pairs_train ON up_pairs_train.up_pair = up_pairs_prior_modified.up_pair\n GROUP BY up_pairs_prior_modified.up_pair''')\n\n# Save (commit) the changes\nconn.commit()\n\nprint(\"Creating new view 'n5_view'...\")\n\n# Create table\nc.execute('''CREATE VIEW n5_view AS\n SELECT user_id, \n MAX(order_number) AS order_number_n1,\n CASE WHEN (MAX(order_number) - 1) < 1 THEN NULL \n ELSE (MAX(order_number) - 1) END AS order_number_n2,\n CASE WHEN (MAX(order_number) - 2) < 1 THEN NULL \n ELSE (MAX(order_number) - 2) END AS order_number_n3,\n CASE WHEN (MAX(order_number) - 3) < 1 THEN NULL \n ELSE (MAX(order_number) - 3) END AS order_number_n4,\n CASE WHEN (MAX(order_number) - 4) < 1 THEN NULL \n ELSE (MAX(order_number) - 4) END AS order_number_n5\n FROM orders\n WHERE eval_set = 'prior'\n GROUP BY user_id''')\n\n# Save (commit) the changes\nconn.commit()\n\nprint(\"Creating new table 'n5_table'...\")\n\n# Create table\nc.execute('''CREATE TABLE n5_table AS\n SELECT n5_view.user_id,\n orders_t1.order_id AS order_id_n1,\n orders_t2.order_id AS order_id_n2,\n orders_t3.order_id AS order_id_n3,\n orders_t4.order_id AS order_id_n4,\n orders_t5.order_id AS order_id_n5,\n orders_t1.days_since_prior_order AS days_since_prior_order_n1,\n orders_t2.days_since_prior_order AS days_since_prior_order_n2,\n orders_t3.days_since_prior_order AS days_since_prior_order_n3,\n orders_t4.days_since_prior_order AS days_since_prior_order_n4,\n orders_t5.days_since_prior_order AS days_since_prior_order_n5\n FROM n5_view\n LEFT JOIN orders AS orders_t1\n ON (orders_t1.user_id = n5_view.user_id\n AND orders_t1.order_number = n5_view.order_number_n1)\n LEFT JOIN orders AS orders_t2\n ON (orders_t2.user_id = n5_view.user_id\n AND orders_t2.order_number = n5_view.order_number_n2)\n LEFT JOIN orders AS orders_t3\n ON (orders_t3.user_id = n5_view.user_id\n AND orders_t3.order_number = n5_view.order_number_n3)\n LEFT JOIN orders AS orders_t4\n ON (orders_t4.user_id = n5_view.user_id\n AND orders_t4.order_number = n5_view.order_number_n4)\n LEFT JOIN orders AS orders_t5\n ON (orders_t5.user_id = n5_view.user_id\n AND orders_t5.order_number = n5_view.order_number_n5)''')\n\n# Save (commit) the changes\nconn.commit()\n\nprint(\"Creating new table 'new_table'...\")\n\n# Create table\nc.execute('''CREATE TABLE new_table AS\n SELECT first_data_table.*,\n n5_table.order_id_n1,\n n5_table.order_id_n2,\n n5_table.order_id_n3,\n n5_table.order_id_n4,\n n5_table.order_id_n5\n FROM first_data_table\n LEFT JOIN n5_table\n ON (n5_table.user_id = first_data_table.user_id)\n ''')\n\n# Save (commit) the changes\nconn.commit()\n\nprint(\"Creating new table 'new_table_2'...\")\n\n# Create table\nc.execute('''CREATE TABLE new_table_2 AS\n SELECT new_table.up_pair,\n new_table.y,\n new_table.total_buy_n5,\n new_table.total_buy_ratio_n5,\n new_table.order_ratio_by_chance_n5, \n n5_table.days_since_prior_order_n1,\n n5_table.days_since_prior_order_n2,\n n5_table.days_since_prior_order_n3,\n n5_table.days_since_prior_order_n4,\n n5_table.days_since_prior_order_n5, \n CASE WHEN order_products__prior_1.product_id IS NULL THEN 0 ELSE 1 END as bought_n1,\n CASE WHEN order_products__prior_2.product_id IS NULL THEN 0 ELSE 1 END as bought_n2,\n CASE WHEN order_products__prior_3.product_id IS NULL THEN 0 ELSE 1 END as bought_n3,\n CASE WHEN order_products__prior_4.product_id IS NULL THEN 0 ELSE 1 END as bought_n4,\n CASE WHEN order_products__prior_5.product_id IS NULL THEN 0 ELSE 1 END as bought_n5\n FROM new_table\n LEFT JOIN n5_table\n ON (n5_table.user_id = new_table.user_id)\n LEFT JOIN order_products__prior AS order_products__prior_1\n ON (order_products__prior_1.order_id = new_table.order_id_n1\n AND order_products__prior_1.product_id = new_table.product_id)\n LEFT JOIN order_products__prior AS order_products__prior_2\n ON (order_products__prior_2.order_id = new_table.order_id_n2\n AND order_products__prior_2.product_id = new_table.product_id)\n LEFT JOIN order_products__prior AS order_products__prior_3\n ON (order_products__prior_3.order_id = new_table.order_id_n3\n AND order_products__prior_3.product_id = new_table.product_id)\n LEFT JOIN order_products__prior AS order_products__prior_4\n ON (order_products__prior_4.order_id = new_table.order_id_n4\n AND order_products__prior_4.product_id = new_table.product_id)\n LEFT JOIN order_products__prior AS order_products__prior_5\n ON (order_products__prior_5.order_id = new_table.order_id_n5\n AND order_products__prior_5.product_id = new_table.product_id)\n ''')\n\n# Save (commit) the changes\nconn.commit()\n\nprint(\"Creating new table 'new_table_3'...\")\n\n# Create table\nc.execute('''CREATE TABLE new_table_3 AS\n SELECT up_pair, \n y, \n total_buy_n5, \n total_buy_ratio_n5, \n order_ratio_by_chance_n5, \n \n MAX(IFNULL(order_days_n1, 0), \n IFNULL(order_days_n2, 0),\n IFNULL(order_days_n3, 0),\n IFNULL(order_days_n4, 0),\n IFNULL(order_days_n5, 0)) AS useritem_order_days_max_n5,\n \n CASE WHEN days_since_prior_order_n5 IS NULL THEN\n MIN(IFNULL(order_days_n1, 1000000), \n IFNULL(order_days_n2, 1000000),\n IFNULL(order_days_n3, 1000000),\n IFNULL(order_days_n4, 1000000),\n MAX(IFNULL(order_days_n1, 0), \n IFNULL(order_days_n2, 0),\n IFNULL(order_days_n3, 0),\n IFNULL(order_days_n4, 0),\n IFNULL(order_days_n5, 0))) \n ELSE\n MIN(IFNULL(order_days_n1, 1000000), \n IFNULL(order_days_n2, 1000000),\n IFNULL(order_days_n3, 1000000),\n IFNULL(order_days_n4, 1000000),\n order_days_n5)\n END AS useritem_order_days_min_n5\n\n FROM \n (\n SELECT *,\n CASE WHEN bought_n1 = 0 THEN NULL\n ELSE days_since_prior_order_n1\n END AS order_days_n1,\n \n CASE WHEN bought_n2 = 0 THEN NULL\n ELSE CASE WHEN bought_n1 = 0 THEN\n (days_since_prior_order_n1 + days_since_prior_order_n2)\n ELSE days_since_prior_order_n2\n END\n END AS order_days_n2,\n \n CASE WHEN bought_n3 = 0 THEN NULL\n ELSE \n CASE WHEN bought_n2 = 0 THEN \n CASE WHEN bought_n1 = 0 THEN\n (days_since_prior_order_n1 + days_since_prior_order_n2 +\n days_since_prior_order_n3)\n ELSE (days_since_prior_order_n2 + days_since_prior_order_n3) \n END \n ELSE days_since_prior_order_n3\n END\n END AS order_days_n3,\n \n CASE WHEN bought_n4 = 0 THEN NULL\n ELSE \n CASE WHEN bought_n3 = 0 THEN\n CASE WHEN bought_n2 = 0 THEN\n CASE WHEN bought_n1 = 0 THEN\n (days_since_prior_order_n1 + days_since_prior_order_n2 +\n days_since_prior_order_n3 + days_since_prior_order_n4)\n ELSE (days_since_prior_order_n2 + days_since_prior_order_n3 +\n days_since_prior_order_n4) \n END \n ELSE (days_since_prior_order_n3 + days_since_prior_order_n4)\n END\n ELSE days_since_prior_order_n4\n END\n END AS order_days_n4,\n \n CASE WHEN bought_n4 = 0 THEN\n CASE WHEN bought_n3 = 0 THEN\n CASE WHEN bought_n2 = 0 THEN\n CASE WHEN bought_n1 = 0 THEN\n (days_since_prior_order_n1 + days_since_prior_order_n2 +\n days_since_prior_order_n3 + days_since_prior_order_n4 + \n IFNULL(days_since_prior_order_n5, 0))\n ELSE (days_since_prior_order_n2 + days_since_prior_order_n3 +\n days_since_prior_order_n4 + \n IFNULL(days_since_prior_order_n5, 0)) \n END \n ELSE (days_since_prior_order_n3 + days_since_prior_order_n4 + \n IFNULL(days_since_prior_order_n5, 0))\n END\n ELSE (days_since_prior_order_n4 + IFNULL(days_since_prior_order_n5, 0))\n END\n ELSE IFNULL(days_since_prior_order_n5, 0)\n END AS order_days_n5\n \n FROM new_table_2\n )\n GROUP BY up_pair\n ''')\n\n# Save (commit) the changes\nconn.commit()\n\n\nprint(\"Saving 'new_table_3' to 'final_data_table.csv'...\")\n\n# Create a list of column names\ncol_names = [x['name'] for x in Inspector.from_engine(engine).get_columns('new_table_3')]\n\n\n# Create the csv file that will contain the final, processed Instacart data\ndata = c.execute(\"SELECT * FROM new_table_3\")\nwith open(final_csv_path, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(col_names)\n writer.writerows(data)\n\nprint(\"Finished! 'final_data_table.csv' has been created\")\n" } ]
4
L1ttlY/NoteBot
https://github.com/L1ttlY/NoteBot
7770240d9ab5e1ff2766b5821a2c4cfee53b9b01
c81d47bd7e3ac4a12c95bd1d28ff8ff0c779b0d6
44cf3e3ef964e5eaccb568b838529b778df56625
refs/heads/master
2020-05-24T21:58:22.561652
2019-06-12T16:36:39
2019-06-12T16:36:39
187,487,302
0
0
null
2019-05-19T14:29:02
2019-06-09T10:19:11
2019-06-09T11:42:37
Python
[ { "alpha_fraction": 0.5324314832687378, "alphanum_fraction": 0.5939272046089172, "avg_line_length": 58.02836990356445, "blob_id": "ef59d268ae8fc00f3d2fdeeb9a8c3a06d2a2c475", "content_id": "a674744923f2628948d165cc8ffbf61de5ac9338", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16928, "license_type": "no_license", "max_line_length": 119, "num_lines": 282, "path": "/bot.py", "repo_name": "L1ttlY/NoteBot", "src_encoding": "UTF-8", "text": "import telebot, emoji\r\nfrom telebot import types\r\n\r\n\r\nbot_token = '764198186:AAGPu1-Bc8gVQDmL1ZO0sTgHkV8bLmjv2DU'\r\n\r\nbot = telebot.TeleBot(token=bot_token)\r\n\r\n\r\n# COMMANDS\r\n\r\n\r\[email protected]_handler(commands=['start'])\r\ndef send_welcome(message):\r\n bot.send_message(message.chat.id,\r\n emoji.emojize('Hi! I am NoteBot :musical_note: '\r\n '- Telegram Bot that can send notes for musical instruments \\n'\r\n 'Type /features to see what i can do\\n'\r\n 'If you have found any bugs:'\r\n ' please contact us at [email protected]'))\r\n\r\n\r\[email protected]_handler(commands=['help'])\r\ndef send_help(message):\r\n bot.send_message(message.chat.id, 'All available commands:'\r\n '/start - introduction\\n'\r\n '/features - things that i can do\\n'\r\n '/songs_harmonica, /songs_piano, /songs_guitar - songs\\n'\r\n '/learn_harmonica, /learn_piano, /learn_guitar - playlists on YT for beginners\\n'\r\n '\"hello\", \"bye\", \"i love you\", \"hse\" - messages that you can use to '\r\n 'interact with me(the last one is an easter egg for HSE students (: )\\n'\r\n '/future_work - priorities for us to make NoteBot more useful to you')\r\n\r\n\r\[email protected]_handler(commands=['future_work'])\r\ndef send_features(message):\r\n bot.send_message(message.chat.id, 'Our plans for future are:\\n'\r\n '- Use API\\n'\r\n '- Add more songs\\n'\r\n '- Add more useful and interesting features')\r\n\r\n\r\[email protected]_handler(commands=['features'])\r\ndef send_features(message):\r\n bot.send_message(message.chat.id, 'I can send musical notes for Harmonica, Piano and Guitar,'\r\n ' but their number is limited '\r\n 'because I do not use API at the moment.\\n'\r\n 'To see songs for these instruments, please use commands:\\n'\r\n '/songs_harmonica for Harmonica songs\\n'\r\n '/songs_piano for Piano songs\\n'\r\n '/songs_guitar for Guitar songs\\n'\r\n 'You can learn the basics of these musical instruments by using '\r\n 'commands: /learn_harmonica, /learn_piano and /learn_guitar.\\n'\r\n 'You can see all available commands by using /help.')\r\n\r\n\r\[email protected]_handler(commands=['songs_harmonica']) # harmonica\r\ndef handle_start(message):\r\n markup = types.ReplyKeyboardMarkup()\r\n markup.row('Godfather', 'Imperial march')\r\n markup.row('March of Mendelssohn', 'Dancing in the dark')\r\n markup.row('Jingle Bells', 'Twinkle Twinkle Little Star')\r\n markup.row('I Believe I Can Fly', 'Smells Like Teen Spirit')\r\n markup.row('Nothing Else Matters', 'What a Wonderful World')\r\n bot.send_message(message.chat.id, \"Choose one song:\", reply_markup=markup)\r\n\r\n\r\[email protected]_handler(commands=['songs_piano']) # piano\r\ndef handle_start(message):\r\n markup = types.ReplyKeyboardMarkup()\r\n markup.row(emoji.emojize('Godfather :musical_keyboard:'),\r\n emoji.emojize('Chopin - Prelude in E minor Op.28 No.4 :musical_keyboard:'))\r\n markup.row(emoji.emojize('The Entertainer :musical_keyboard:'),\r\n emoji.emojize('Greensleeves :musical_keyboard:'))\r\n markup.row(emoji.emojize('Fur Elise :musical_keyboard:'),\r\n emoji.emojize('Por Una Cabeza :musical_keyboard:'))\r\n markup.row(emoji.emojize('Waltz from Sleeping Beauty :musical_keyboard:'),\r\n emoji.emojize('Eine Kleine Nachtmusik :musical_keyboard:'))\r\n markup.row(emoji.emojize('O Holy Night :musical_keyboard:'),\r\n emoji.emojize('Ode to Joy :musical_keyboard:'))\r\n bot.send_message(message.chat.id, \"Choose one song:\", reply_markup=markup)\r\n\r\n\r\[email protected]_handler(commands=['songs_guitar']) # guitar\r\ndef handle_start(message):\r\n markup = types.ReplyKeyboardMarkup()\r\n markup.row(emoji.emojize('Godfather :guitar:'),\r\n emoji.emojize('Aladdin - A Whole New World :guitar:'))\r\n markup.row(emoji.emojize('Jingle Bells :guitar:'),\r\n emoji.emojize('Happy Birthday :guitar:'))\r\n markup.row(emoji.emojize('Old MacDonald Had a Farm :guitar:'),\r\n emoji.emojize('Prelude in D :guitar:'))\r\n markup.row(emoji.emojize('Lullaby (Wiegenlied) :guitar:'),\r\n emoji.emojize('Country Dance :guitar:'))\r\n markup.row(emoji.emojize('Bolero :guitar:'),\r\n emoji.emojize('Turkish March :guitar:'))\r\n bot.send_message(message.chat.id, \"Choose one song:\", reply_markup=markup)\r\n\r\n\r\n# FUNCTIONS\r\n\r\n\r\ndef send_all(message, url_id, photo_id):\r\n keyboard = types.InlineKeyboardMarkup()\r\n url_button = types.InlineKeyboardButton(text=\"Go to website with notes\",\r\n url=url_id)\r\n keyboard.add(url_button)\r\n bot.send_message(message.chat.id, \"Hello! You can see the notes by clicking on the button below =)\",\r\n reply_markup=keyboard)\r\n bot.send_photo(chat_id=message.chat.id,\r\n photo=photo_id)\r\n\r\n\r\ndef send_all_2_photos(message, url_id, photo_id, photo_id_2):\r\n keyboard = types.InlineKeyboardMarkup()\r\n url_button = types.InlineKeyboardButton(text=\"Go to website with notes\",\r\n url=url_id)\r\n keyboard.add(url_button)\r\n bot.send_message(message.chat.id, \"Hello! You can see the notes by clicking on the button below =)\",\r\n reply_markup=keyboard)\r\n bot.send_photo(chat_id=message.chat.id,\r\n photo=photo_id)\r\n bot.send_photo(chat_id=message.chat.id,\r\n photo=photo_id_2)\r\n\r\n\r\ndef learn(message, url_id):\r\n keyboard = types.InlineKeyboardMarkup()\r\n url_button = types.InlineKeyboardButton(text=\"Start learning\",\r\n url=url_id)\r\n keyboard.add(url_button)\r\n bot.send_message(message.chat.id, \"Hey! You can learn basics of this musical instrument\"\r\n \" by clicking on the button below\",\r\n reply_markup=keyboard)\r\n\r\n# LEARNING\r\n\r\n\r\[email protected]_handler(commands=['learn_guitar'])\r\ndef send_learning(message):\r\n send_link = learn(message, \"https://www.youtube.com/playlist?list=PL-RYb_OMw7GfqsbipaR65GDDzA1rP5deq\")\r\n\r\n\r\[email protected]_handler(commands=['learn_piano'])\r\ndef send_learning(message):\r\n send_link = learn(message, \"https://www.youtube.com/playlist?list=PLP9cbwDiLzdL6IS4-rmzR42ghq3T56XnK\")\r\n\r\n\r\[email protected]_handler(commands=['learn_harmonica'])\r\ndef send_learning(message):\r\n send_link = learn(message, \"https://www.youtube.com/playlist?list=PLKONji9dlomQtLpyMM4vT9K1mx_jUNxLp\")\r\n\r\n\r\n# TEXT FEATURES\r\n\r\n\r\[email protected]_handler(content_types=['text'])\r\ndef send_text(message):\r\n if message.text.lower() == 'hello':\r\n bot.send_message(message.chat.id, 'Hello my friend!')\r\n elif message.text.lower() == 'bye':\r\n bot.send_message(message.chat.id, 'Bye! Hope to see you soon again =)')\r\n elif message.text.lower() == 'i love you':\r\n bot.send_sticker(message.chat.id, 'CAADAgADewEAAk-cEwKCccJvIsWEBwI')\r\n elif message.text.lower() == 'hse':\r\n bot.send_sticker(message.chat.id, 'CAADAgADVwEAAk-cEwKdCE6LUElPhAI')\r\n\r\n # HARMONICA SONGS\r\n\r\n elif message.text.lower() == 'godfather':\r\n data = send_all(message, \"https://www.harmonica.com/the-godfather-by-nino-rota-1822.html\",\r\n 'https://pp.userapi.com/c855016/v855016562/65c9f/40Nph1jK3UI.jpg')\r\n elif message.text.lower() == 'jingle bells':\r\n data = send_all(message, \"https://www.harmonica.com/jingle-bells-by-unknown-2014.html\",\r\n \"https://pp.userapi.com/c855020/v855020705/646ce/ans525gkw9Y.jpg\")\r\n elif message.text.lower() == 'twinkle twinkle little star':\r\n data = send_all(message, 'https://www.harmonica.com/'\r\n 'free-harmonica-tabs-for-twinkle-twinkle-little-star-by-unknown-2668.html',\r\n 'https://pp.userapi.com/c855020/v855020705/6471f/IUJbtHUhsLQ.jpg')\r\n elif message.text.lower() == 'i believe i can fly':\r\n data = send_all_2_photos(message, \"https://www.harmonica.com/i-believe-i-can-fly-by-r-kelly-2519.html\",\r\n \"https://pp.userapi.com/c855020/v855020705/647bd/LHSUBcErS48.jpg\",\r\n \"https://pp.userapi.com/c855020/v855020705/647c4/MP5H6pr9qD4.jpg\")\r\n elif message.text.lower() == 'smells like teen spirit':\r\n data = send_all_2_photos(message, \"https://www.harmonica.com/smells-like-teen-spirit-by-nirvana-1654.html\",\r\n \"https://pp.userapi.com/c855020/v855020705/647e7/B0OxD97lpK4.jpg\",\r\n \"https://pp.userapi.com/c855020/v855020705/647ee/jCFkL41HF5k.jpg\")\r\n elif message.text.lower() == 'nothing else matters':\r\n data = send_all_2_photos(message, \"https://www.harmonica.com/nothing-else-matters-by-metallica-2234.html\",\r\n \"https://pp.userapi.com/c855020/v855020705/647ff/WZ3SWdIVHDw.jpg\",\r\n \"https://pp.userapi.com/c855020/v855020705/64807/jbetMMai3Bk.jpg\")\r\n elif message.text.lower() == 'what a wonderful world':\r\n data = send_all_2_photos(message, \"https://www.harmonica.com/\"\r\n \"what-a-wonderful-world-by-louis-armstrong-1660.html\",\r\n \"https://pp.userapi.com/c855020/v855020965/68290/yX3T5B5hrUQ.jpg\",\r\n \"https://pp.userapi.com/c855020/v855020965/68298/v4tcQppfE3g.jpg\")\r\n elif message.text.lower() == 'imperial march':\r\n data = send_all(message, \"https://www.harmonica.com/darth-vader-imperial-march-by-john-williams-1788.html\",\r\n 'https://pp.userapi.com/c855016/v855016562/65c7c/Ptv2M44sAXE.jpg')\r\n elif message.text.lower() == 'march of mendelssohn':\r\n data = send_all(message, \"https://antropinum.ru/tabs/12678\",\r\n 'https://pp.userapi.com/c855016/v855016562/65c8a/dzXxnAyQ054.jpg')\r\n elif message.text.lower() == 'dancing in the dark':\r\n data = send_all(message, \"https://www.harmonica.com/dancing-in-the-dark-by-bruce-springsteen-2559.html\",\r\n 'https://pp.userapi.com/c855016/v855016562/65c56/ZFSjdEnIiEg.jpg')\r\n\r\n # PIANO SONGS\r\n\r\n elif message.text.lower() == emoji.emojize('godfather :musical_keyboard:'):\r\n data = send_all(message, \"https://musescore.com/user/9265496/scores/2049321\",\r\n 'https://pp.userapi.com/c856032/v856032448/6567c/VgRmqqvAxdE.jpg')\r\n elif message.text.lower() == emoji.emojize('chopin - prelude in e minor op.28 no.4 :musical_keyboard:'):\r\n data = send_all_2_photos(message, \"https://www.8notes.com/scores/9765.asp\",\r\n 'https://pp.userapi.com/c849128/v849128883/1ae7ba/ybJz0QyhPkI.jpg',\r\n 'https://pp.userapi.com/c849128/v849128883/1ae7c2/NLK3jqJlT5U.jpg')\r\n elif message.text.lower() == emoji.emojize('the entertainer :musical_keyboard:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/13178.asp\",\r\n 'https://pp.userapi.com/c855016/v855016676/67f99/q7O2R9p_0QE.jpg')\r\n elif message.text.lower() == emoji.emojize('greensleeves :musical_keyboard:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/12179.asp\",\r\n 'https://pp.userapi.com/c855016/v855016676/67fd2/fSkZHXx4Bm0.jpg')\r\n elif message.text.lower() == emoji.emojize('fur elise :musical_keyboard:'):\r\n data = send_all_2_photos(message, \"https://www.8notes.com/scores/457.asp\",\r\n 'https://pp.userapi.com/c855016/v855016676/67fda/51NKeBRAfe4.jpg',\r\n 'https://pp.userapi.com/c855016/v855016676/67fe2/7ycehEkbaj0.jpg')\r\n elif message.text.lower() == emoji.emojize('por una cabeza :musical_keyboard:'):\r\n data = send_all_2_photos(message, \"https://www.8notes.com/scores/18093.asp\",\r\n 'https://pp.userapi.com/c855016/v855016046/6814b/BNBvI6jIDgA.jpg',\r\n 'https://pp.userapi.com/c855016/v855016046/68143/O04hvB7UFyQ.jpg')\r\n elif message.text.lower() == emoji.emojize('waltz from sleeping beauty :musical_keyboard:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/13169.asp\",\r\n 'https://pp.userapi.com/c851028/v851028394/1411a8/f6KalVJTVX0.jpg')\r\n elif message.text.lower() == emoji.emojize('eine kleine nachtmusik :musical_keyboard:'):\r\n data = send_all_2_photos(message, \"https://www.8notes.com/scores/418.asp\",\r\n 'https://pp.userapi.com/c851028/v851028394/1411ba/FB6D7nCRnTs.jpg',\r\n 'https://pp.userapi.com/c851028/v851028394/1411c2/QwdsEHYnK3A.jpg')\r\n elif message.text.lower() == emoji.emojize('o holy night :musical_keyboard:'):\r\n data = send_all_2_photos(message, \"https://www.8notes.com/scores/13800.asp\",\r\n 'https://pp.userapi.com/c851028/v851028394/1411ee/hRKHueqJ_lY.jpg',\r\n 'https://pp.userapi.com/c851028/v851028394/1411f7/QdiZRkauIXU.jpg')\r\n elif message.text.lower() == emoji.emojize('ode to joy :musical_keyboard:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/12180.asp\",\r\n 'https://pp.userapi.com/c850628/v850628717/140545/IoZim1zBanc.jpg')\r\n\r\n # GUITAR SONGS\r\n\r\n elif message.text.lower() == emoji.emojize('godfather :guitar:'):\r\n data = send_all(message, \"https://tabs.ultimate-guitar.com/tab/nino_rota/godfather_tabs_334933\",\r\n 'https://pp.userapi.com/c849128/v849128448/1afa7b/B-xtBwHf29M.jpg')\r\n elif message.text.lower() == emoji.emojize('aladdin - a whole new world :guitar:'):\r\n data = send_all_2_photos(message, \"https://tabs.ultimate-guitar.com/tab/misc_cartoons/\"\r\n \"aladdin_-_a_whole_new_world_tabs_342734\",\r\n 'https://pp.userapi.com/c849128/v849128883/1ae75f/oTGYubndX-Y.jpg',\r\n 'https://pp.userapi.com/c849128/v849128883/1ae766/eU9PDwMkRS4.jpg')\r\n elif message.text.lower() == emoji.emojize('jingle bells :guitar:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/11624.asp\",\r\n 'https://pp.userapi.com/c855620/v855620241/6a160/GeZxKqoC90E.jpg')\r\n elif message.text.lower() == emoji.emojize('happy birthday :guitar:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/15676.asp\",\r\n 'https://pp.userapi.com/c855620/v855620241/6a171/9RDpd25jW-c.jpg')\r\n elif message.text.lower() == emoji.emojize('lullaby (wiegenlied) :guitar:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/17659.asp\",\r\n 'https://pp.userapi.com/c855620/v855620241/6a179/RnngwLuEdqs.jpg')\r\n elif message.text.lower() == emoji.emojize('country dance :guitar:'):\r\n data = send_all_2_photos(message, \"https://www.8notes.com/scores/16780.asp\",\r\n 'https://pp.userapi.com/c855620/v855620241/6a18b/eP-HDpG3mhQ.jpg',\r\n 'https://pp.userapi.com/c855620/v855620241/6a19b/RwOhE5eFYxg.jpg')\r\n elif message.text.lower() == emoji.emojize('old macdonald had a farm :guitar:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/15036.asp\",\r\n 'https://pp.userapi.com/c855620/v855620241/6a1c1/UV9H0v0M5fo.jpg')\r\n elif message.text.lower() == emoji.emojize('prelude in d :guitar:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/23526.asp\",\r\n 'https://pp.userapi.com/c855620/v855620241/6a1dc/omCFll-G3qk.jpg')\r\n elif message.text.lower() == emoji.emojize('bolero :guitar:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/17231.asp\",\r\n 'https://pp.userapi.com/c855620/v855620241/6a1e4/noZOaxZyURw.jpg')\r\n elif message.text.lower() == emoji.emojize('turkish march :guitar:'):\r\n data = send_all(message, \"https://www.8notes.com/scores/29551.asp\",\r\n 'https://pp.userapi.com/c855620/v855620241/6a209/CU-ujaemvDU.jpg')\r\n\r\n\r\nbot.polling()\r\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5067567825317383, "avg_line_length": 21.36842155456543, "blob_id": "d8e580bfcdc24435fe83248c622f3aa348bd159c", "content_id": "bc0229c0ea0ec3892db272b5f02ab3d782254195", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 444, "license_type": "no_license", "max_line_length": 60, "num_lines": 19, "path": "/main.py", "repo_name": "L1ttlY/NoteBot", "src_encoding": "UTF-8", "text": "def process_file(file_name):\r\n data = []\r\n with open(file_name) as f:\r\n for line in f:\r\n parts = line.split()\r\n data.append(parts)\r\n # row = [\r\n # parts[0], parts[1], parts[2]\r\n # ]\r\n data.append(parts)\r\n return data\r\n\r\n\r\ndata = process_file('NoteData.csv')\r\nprint(data)\r\n\r\n\r\n# def telegram_bot():\r\n# There should be code for telegram bot :p(work in progress)\r\n" } ]
2
xuejj/python_traning
https://github.com/xuejj/python_traning
7f0781b892a292a05ebb628a14801e4b71d87e51
f6dfa4c3bd584684723a0e5b49af756940e62b0a
2c2bbe560ea1abdaf7628870f7cdecdd48e29117
refs/heads/master
2018-01-12T06:40:25.635053
2016-03-19T12:33:32
2016-03-19T12:33:32
53,835,201
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6228346228599548, "alphanum_fraction": 0.6330708861351013, "avg_line_length": 33.79452133178711, "blob_id": "e875f17b2dbbccbce7c7c96d9c090f53a0d3f343", "content_id": "2d39b4e6742e2f93efa32cc9374feb15488ce0e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2540, "license_type": "no_license", "max_line_length": 258, "num_lines": 73, "path": "/web_app/using_flask/app.py", "repo_name": "xuejj/python_traning", "src_encoding": "UTF-8", "text": "from flask import Flask, request, render_template\nimport time\nimport datetime\nimport sqlite3\nimport urllib\nimport json\n\n\napp = Flask(__name__)\n\ndef inser_to_db(time,ip,ip_info):\n conn = sqlite3.connect('time_ip_ipinfo.db')\n cursor = conn.cursor()\n cursor.execute('insert into time_ip_ipinfo_table (time, ip, ip_info) values (\"%s\", \"%s\",\"%s\")'%(time,ip,ip_info))\n cursor.execute('select * from time_ip_ipinfo_table')\n values = cursor.fetchall()\n conn.commit()\n cursor.close()\n conn.close()\n\ndef read_from_db():\n conn = sqlite3.connect('time_ip_ipinfo.db')\n cursor = conn.cursor()\n cursor.execute('select * from time_ip_ipinfo_table order by time desc')\n values = cursor.fetchall()\n cursor.close()\n conn.close()\n return values\n\ndef ip_location(ip):\n url = \"http://ip.taobao.com/service/getIpInfo.php?ip=\"\n\n data = urllib.urlopen(url + ip).read()\n datadict=json.loads(data)\n\n if datadict['code'] == 0:\n ip_info = datadict['data']['region'].encode('utf8') + '\\t' + datadict['data']['isp'].encode('utf8') + '\\t' + datadict['data']['country'].encode('utf8')+ '\\t' + datadict['data']['area'].encode('utf8') + '\\t' + datadict['data']['city'].encode('utf8')\n return ip_info\n else:\n return null_ip_info\n\[email protected]('/', methods=['GET', 'POST'])\ndef home():\n ISOTIMEFORMAT='%Y-%m-%d %X'\n request_time = time.strftime(ISOTIMEFORMAT, time.localtime())\n request_ip = request.remote_addr\n ip_info = ip_location(request_ip)\n# request_message = request.environ\n inser_to_db(request_time,request_ip,ip_info)\n data_from_db = read_from_db()\n# print data_from_db\n list_to_show = []\n for i in range(10):\n tmp_key = str(i) + '\\t' + data_from_db[i][0] + '\\t' + data_from_db[i][1] + '\\t' + data_from_db[i][2]\n list_to_show.append(tmp_key)\n# print data_from_db[i][2]\n# print list_to_show \n return render_template('home.html',time=request_time,message=request_ip,history_list=list_to_show)\n\[email protected]('/signin', methods=['GET'])\ndef signin_form():\n return render_template('form.html',message='ok!')\n\[email protected]('/signin', methods=['POST'])\ndef signin():\n username = request.form['username']\n password = request.form['password']\n if username=='admin' and password=='password':\n return render_template('signin-ok.html', username=username)\n return render_template('form.html', message='Bad username or password', username=username)\n\nif __name__ == '__main__':\n app.run(host='104.224.147.174',port='80')\n" }, { "alpha_fraction": 0.5925925970077515, "alphanum_fraction": 0.6218323707580566, "avg_line_length": 37.53845977783203, "blob_id": "e823ecdf215e6b664ba2550b098b32b550e22dae", "content_id": "f37e62588d94300eeb1ceb6c8d50cf84b83ea1fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 513, "license_type": "no_license", "max_line_length": 249, "num_lines": 13, "path": "/web_app/using_flask/test_ip_u.py", "repo_name": "xuejj/python_traning", "src_encoding": "UTF-8", "text": "# the script is used to query the location of every ip\n\nimport urllib\nimport json\n\nurl = \"http://ip.taobao.com/service/getIpInfo.php?ip=\"\n\nip = \"218.189.127.8\"\ndata = urllib.urlopen(url + ip).read()\ndatadict=json.loads(data)\n\nif datadict['code'] == 0:\n print datadict['data']['city'].encode('utf8') + '\\t' + datadict['data']['area'].encode('utf8') + '\\t' + datadict['data']['country'].encode('utf8')+ '\\t' + datadict['data']['isp'].encode('utf8') + '\\t' + datadict['data']['region'].encode('utf8')\n \n\n" } ]
2
injirez/cyberTournaments
https://github.com/injirez/cyberTournaments
09d7ee7f18579d01096c7b840f1e2b649a35b34b
82a225835942ea113ad252a9e6a1e19d019b7b6f
be1456c77a4a475143fcf38f1df592879e6c89ba
refs/heads/master
2023-08-11T09:10:32.568368
2021-09-21T17:58:21
2021-09-21T17:58:21
348,760,347
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.512135922908783, "alphanum_fraction": 0.5922330021858215, "avg_line_length": 21.88888931274414, "blob_id": "21b427bf59e55855a110e6e80f740439f606e87a", "content_id": "304f8fa54a1be9ca9c6d90ad8a67ee92d778d307", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 412, "license_type": "no_license", "max_line_length": 81, "num_lines": 18, "path": "/Dota/migrations/0008_alter_reward_type.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-08-16 20:23\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0007_auto_20210816_2311'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='reward',\n name='type',\n field=models.CharField(max_length=15, verbose_name='Type of reward'),\n ),\n ]\n" }, { "alpha_fraction": 0.6236934065818787, "alphanum_fraction": 0.6236934065818787, "avg_line_length": 38.39215850830078, "blob_id": "48cbb447989483b254a73b523928db987781e983", "content_id": "33ec4edade446e0931363fcc086f18334bfefe75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2009, "license_type": "no_license", "max_line_length": 117, "num_lines": 51, "path": "/Dota/serializers.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom .models import Dota, Link, Reward\n\n\nclass LinkListSerializer(serializers.ModelSerializer):\n class Meta:\n model = Link\n fields = ('image', 'tournament')\n\nclass RewardListSerializer(serializers.ModelSerializer):\n class Meta:\n model = Reward\n fields = ('type', 'count', 'currency')\n\nclass DotaListSerializer(serializers.ModelSerializer):\n siteName = serializers.SlugRelatedField(read_only=True, slug_field='name')\n gameMode = serializers.SlugRelatedField(read_only=True, slug_field='mode')\n links = LinkListSerializer(read_only=True)\n reward = RewardListSerializer(read_only=True)\n class Meta:\n model = Dota\n fields = ('title', 'status', 'startTime', 'gameMode', 'participant', 'reward', 'siteName', 'links', 'ip')\n\nclass DotaTestListSerializer(serializers.ModelSerializer):\n class Meta:\n model = Dota\n fields = '__all__'\n\n# #\n# class CreateParticipantSerializer(serializers.ModelSerializer):\n# class Meta:\n# model = Dota\n# # fields = (\"title\", \"img\", \"status\", \"startTime\", \"gameMode\", \"participant\", \"reward\", \"siteName\", \"link\")\n# fields = (\"title\", \"participant\")\n\n # def create(self, validated_data):\n # participantNum = Dota.objects.update_or_create(\n # # id=validated_data.get('id', None),\n # title=validated_data.get('title', None),\n # # img=validated_data.get('img', None),\n # # status=validated_data.get('status', None),\n # # startTime=validated_data.get('startTime', None),\n # # gameMode=validated_data.get('gameMode', None),\n # # reward=validated_data.get('reward', None),\n # # siteName=validated_data.get('siteName', None),\n # # link=validated_data.get('link', None),\n # # ip=validated_data.get('ip', None),\n # defaults={'participant': validated_data.get(\"participant\")}\n # )\n\n # return participantNum\n" }, { "alpha_fraction": 0.5534647703170776, "alphanum_fraction": 0.562126636505127, "avg_line_length": 38.38823699951172, "blob_id": "564f65f56908cb7847f54ea4ee118d90469a8c60", "content_id": "2c74a94cea933dc2669f3502185eaa31647cf6e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3348, "license_type": "no_license", "max_line_length": 173, "num_lines": 85, "path": "/Dota/migrations/0006_auto_20210816_2307.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-08-16 20:07\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0005_alter_dota_currency'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='GameMode',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('mode', models.CharField(max_length=10, verbose_name='Mode of the game')),\n ],\n ),\n migrations.CreateModel(\n name='Link',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('image', models.URLField(unique=True, verbose_name='URL of tournament')),\n ('tournament', models.URLField(unique=True, verbose_name='URL of tournament')),\n ],\n ),\n migrations.CreateModel(\n name='Reward',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('type', models.CharField(max_length=10, verbose_name='Type of reward')),\n ('count', models.CharField(max_length=10, verbose_name='Count of reward')),\n ('currency', models.CharField(max_length=3, verbose_name='Currency of reward')),\n ],\n ),\n migrations.CreateModel(\n name='SiteName',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=10, verbose_name='Name of the site')),\n ],\n ),\n migrations.RemoveField(\n model_name='dota',\n name='Tournlink',\n ),\n migrations.RemoveField(\n model_name='dota',\n name='currency',\n ),\n migrations.RemoveField(\n model_name='dota',\n name='img',\n ),\n migrations.AddField(\n model_name='dota',\n name='imgLink',\n field=models.ForeignKey(default=django.utils.timezone.now, on_delete=django.db.models.deletion.CASCADE, related_name='images', to='Dota.link', to_field='image'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='dota',\n name='tournLink',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, related_name='tournaments', to='Dota.link', to_field='tournament'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='dota',\n name='gameMode',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Dota.gamemode'),\n ),\n migrations.AlterField(\n model_name='dota',\n name='reward',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Dota.reward'),\n ),\n migrations.AlterField(\n model_name='dota',\n name='siteName',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Dota.sitename'),\n ),\n ]\n" }, { "alpha_fraction": 0.5511627793312073, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 22.88888931274414, "blob_id": "6dc9c4fcbd105f6c7a410b0d2851f9fa2e725756", "content_id": "8936f1f2163750ea41447839f3ec536c470438b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 96, "num_lines": 18, "path": "/Dota/migrations/0017_alter_sitename_name.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-09-21 17:42\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0016_alter_gamemode_mode'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='sitename',\n name='name',\n field=models.CharField(max_length=15, unique=True, verbose_name='Name of the site'),\n ),\n ]\n" }, { "alpha_fraction": 0.6942675113677979, "alphanum_fraction": 0.6942675113677979, "avg_line_length": 33.88888931274414, "blob_id": "adc45490d24fffc7cf391bcffe71d86643dfca39", "content_id": "cfa3940c482d3abe81a30620d5c26f8b9c84fdd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 314, "license_type": "no_license", "max_line_length": 75, "num_lines": 9, "path": "/Dota/urls.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.DotaListView.as_view()),\n path('siteName/<str:siteName>/', views.DotaListViewSiteName.as_view()),\n path('status/<str:status>/', views.DotaListViewStatus.as_view()),\n path('testDota/', views.DotaListViewTest.as_view())\n]\n" }, { "alpha_fraction": 0.5953038930892944, "alphanum_fraction": 0.6215469837188721, "avg_line_length": 29.16666603088379, "blob_id": "59c424d6bc4bf8dfe52b08719fc31613832bd25b", "content_id": "491fa84b5242bca4691865a8299803bb951e4495", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 724, "license_type": "no_license", "max_line_length": 127, "num_lines": 24, "path": "/Dota/migrations/0015_auto_20210905_1806.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-09-05 15:06\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0014_alter_dota_sitename'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dota',\n name='gameMode',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='gameModes', to='Dota.gamemode'),\n ),\n migrations.AlterField(\n model_name='dota',\n name='siteName',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='siteNames', to='Dota.sitename'),\n ),\n ]\n" }, { "alpha_fraction": 0.590436577796936, "alphanum_fraction": 0.6299376487731934, "avg_line_length": 24.3157901763916, "blob_id": "1cc18acdf4f80b6fdeb302446533ae5cced9080f", "content_id": "9ef778a0f0e71cb09d04b123dd0a9b2efeab2feb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 481, "license_type": "no_license", "max_line_length": 114, "num_lines": 19, "path": "/Dota/migrations/0013_alter_dota_sitename.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-09-05 13:55\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0012_alter_sitename_name'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dota',\n name='siteName',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Dota.sitename', unique=True),\n ),\n ]\n" }, { "alpha_fraction": 0.7064564824104309, "alphanum_fraction": 0.7259759902954102, "avg_line_length": 46.53571319580078, "blob_id": "81c676883d48f27536e04a7b6bbdcb2abbe70a91", "content_id": "f60a2d8ec1df97e5fab58e69e519c5ce333ec983", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1332, "license_type": "no_license", "max_line_length": 96, "num_lines": 28, "path": "/Dota/models.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Dota(models.Model):\n title = models.CharField('Title of tournament', max_length=100, unique=True)\n status = models.CharField('Status of tournament', max_length=15)\n startTime = models.CharField('Date of tournament start', max_length=25)\n gameMode = models.ForeignKey('GameMode', on_delete=models.CASCADE, related_name='gameModes')\n participant = models.CharField('Number of participants', max_length=10)\n reward = models.ForeignKey('Reward', on_delete=models.CASCADE)\n siteName = models.ForeignKey('SiteName', on_delete=models.CASCADE, related_name='siteNames')\n links = models.ForeignKey('Link', on_delete=models.CASCADE)\n ip = models.CharField('IP address', max_length=15)\n\nclass Reward(models.Model):\n type = models.CharField('Type of reward', max_length=15)\n count = models.CharField('Count of reward', max_length=10)\n currency = models.CharField('Currency of reward', max_length=3)\n\nclass GameMode(models.Model):\n mode = models.CharField('Mode of the game', max_length=10, unique=True)\n\nclass SiteName(models.Model):\n name = models.CharField('Name of the site', max_length=15, unique=True)\n\nclass Link(models.Model):\n image = models.URLField('URL of image', max_length=200)\n tournament = models.URLField('URL of tournament', max_length=200)\n\n" }, { "alpha_fraction": 0.5561206340789795, "alphanum_fraction": 0.5831287503242493, "avg_line_length": 47.735042572021484, "blob_id": "1b0eae292dab6a1a3cec455ab658122f57a253fc", "content_id": "56c9e82d38fe054bc568d4203e20e47c9d65d909", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11495, "license_type": "no_license", "max_line_length": 230, "num_lines": 234, "path": "/Dota/tasks.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "from celery import shared_task\nfrom .models import Dota, Reward, GameMode, SiteName, Link\nfrom django.db import IntegrityError\n\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\n\n\n\n@shared_task\ndef addDotaWeplay():\n linkDota = 'https://weplay.tv/ru/tournaments/dota2'\n linkDotaPast = 'https://compete.weplay.tv/ru/dota2-tournaments?timeline=past'\n bot = webdriver.Chrome(r'C:\\Users\\injir\\Documents\\cyberTournaments\\chromedriver.exe')\n wait = WebDriverWait(bot, 10)\n\n bot.get(linkDota)\n # bot.maximize_window()\n\n for i in range(1, 10):\n title = wait.until(EC.element_to_be_clickable((By.XPATH,\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[1]/div/div/a\".format(\n i)))).text\n status = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[2]/span\".format(i)).text\n image = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[1]/div/a/div/img\".format(\n i)).get_attribute('src')\n startTime = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[2]/p\".format(i)).text\n gameMode = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[3]/p[1]/a\".format(i)).text\n participant = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[5]/p\".format(i)).text\n reward = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[6]/p\".format(i)).text\n reward = reward.split()\n\n if reward == 'Уважение':\n reward = 0\n currency = 0\n typeReward = 0\n elif reward != 'Уважение':\n if len(reward) > 2:\n # reward = reward.split()\n typeReward = (reward[1] + ' ' + reward[2]).replace('(', '').replace(')', '')\n reward = reward[0].replace('$', '')\n currency = '$'\n else:\n # reward = reward.split()\n typeReward = 'Деньги'\n reward = reward[0]\n currency = reward[1]\n\n\n\n link = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[1]/div/div/a\".format(\n i)).get_attribute('href')\n\n\n\n print(title, status, startTime, gameMode, participant, reward, 'WePlay', link, image, currency, typeReward)\n siteNameObject = SiteName.objects.get(name='WePlay')\n gameModeObject = GameMode.objects.get(mode=gameMode)\n\n try:\n rewardObject = Reward.objects.create(type=typeReward, count=reward, currency=currency)\n # gameModeObject = GameMode.objects.create(mode=gameMode)\n linkObject = Link.objects.create(image=image, tournament=link)\n newObject = Dota.objects.create(title=title, status=status, startTime=startTime, gameMode=gameModeObject, participant=participant, reward=rewardObject, siteName=siteNameObject, links=linkObject, ip='127.0.0.1')\n except IntegrityError:\n print(\"Updating row...\")\n Dota.objects.filter(title=title).update(status=status, participant=participant)\n bot.quit()\n return True\n\n\n@shared_task\ndef addDotaGamelix():\n linkDota = 'https://gamelix.com/dota-2/tournaments/1'\n bot = webdriver.Chrome(r'C:\\Users\\injir\\Documents\\cyberTournaments\\chromedriver.exe')\n wait = WebDriverWait(bot, 10)\n\n # bot.get(linkDota)\n # bot.maximize_window()\n\n for i in range(1, 10):\n bot.get(linkDota)\n title = wait.until(EC.element_to_be_clickable((By.XPATH,\n \"/html/body/div[1]/div[1]/main/div/div[2]/div/div[2]/a[{}]/div/div[1]/p\".format(\n i)))).text\n\n status = bot.find_element_by_xpath(\n \"/html/body/div[1]/div[1]/main/div/div[2]/div/div[2]/a[{}]/div/div[5]/div/h4\".format(i)).text\n image = \"https://static-prod.weplay.tv/2020-09-06/w-2048/webp/973eedcbdec2f381fe92fd9199987288.120D2F-B20834-0AB9E4.jpeg\"\n\n gameMode = bot.find_element_by_xpath(\n \"/html/body/div[1]/div[1]/main/div/div[2]/div/div[2]/a[{}]/div/div[2]/p/span\".format(i)).text\n participant = bot.find_element_by_xpath(\n \"/html/body/div[1]/div[1]/main/div/div[2]/div/div[2]/a[{}]/div/div[3]/p\".format(i)).text\n reward = bot.find_element_by_xpath(\n \"/html/body/div[1]/div[1]/main/div/div[2]/div/div[2]/a[{}]/div/div[4]/span\".format(i)).text\n\n siteName = 'GameLix'\n typeReward = 'Деньги'\n reward = reward.split()\n reward = reward[0]\n currency = reward[1]\n\n\n # if reward == 'Уважение':\n # reward = 0\n # currency = 0\n # typeReward = 0\n # elif reward != 'Уважение':\n # reward = reward.split()\n # typeReward = (reward[1] + ' ' + reward[2]).replace('(', '').replace(')', '')\n # reward = reward[0].replace('$', '')\n # currency = '$'\n\n\n\n link = bot.find_element_by_xpath(\n \"/html/body/div[1]/div[1]/main/div/div[2]/div/div[2]/a[{}]\".format(\n i)).get_attribute('href')\n bot.get(link)\n startTime = bot.find_element_by_xpath(\n \"/html/body/div[1]/div[1]/main/div/div[2]/div/div/div[2]/div/div[2]/p\".format(i)).text\n startTime = startTime.split()\n startTime = startTime[3] + ' ' + startTime[4]\n\n\n\n\n print(title, status, startTime, gameMode, participant, reward, siteName, link, image, currency, typeReward)\n\n siteNameObject = SiteName.objects.get(name='GameLix')\n if gameMode == '1x1':\n gameModeObject = GameMode.objects.get(mode='1v1')\n elif gameMode == '5x5':\n gameModeObject = GameMode.objects.get(mode='5v5')\n\n try:\n if status != 'Завершен':\n if status == 'Начался':\n status = 'Текущий'\n rewardObject = Reward.objects.create(type=typeReward, count=reward, currency=currency)\n linkObject = Link.objects.create(image=image, tournament=link)\n newObject = Dota.objects.create(title=title, status=status, startTime=startTime, gameMode=gameModeObject, participant=participant, reward=rewardObject, siteName=siteNameObject, links=linkObject, ip='127.0.0.1')\n\n except IntegrityError:\n if status == 'Завершен':\n print('Deleting row...')\n delObject = Dota.objects.get(title=title)\n delObject.delete()\n else:\n print(\"Updating row...\")\n Dota.objects.filter(title=title).update(status=status, participant=participant)\n\n bot.quit()\n return True\n\n\n@shared_task\ndef addDotaCmode():\n linkDota = 'https://www.challengermode.com/dota2/tournaments?state=upcoming'\n bot = webdriver.Chrome(r'C:\\Users\\injir\\Documents\\cyberTournaments\\chromedriver.exe')\n wait = WebDriverWait(bot, 10)\n\n for i in range(1, 10):\n bot.get(linkDota)\n\n tournamentLink = wait.until(EC.element_to_be_clickable((By.XPATH,\n \"/html/body/div[2]/div/div/div[1]/div[2]/div[2]/div[1]/div[1]/div/div/div[1]/div/div/div/div[1]/div[3]/div/div/div[{}]/span/div/div/a\".format(\n i)))).get_attribute('href')\n # imageLink = bot.find_element_by_xpath(\n # \"/html/body/div[2]/div/div/div/div[2]/div[1]/div/div/div/div[1]/div/div/div[2]/div/div[2]/div/div/div[{}]/div/div/div[1]/div/div[1]/div/div/div/a/div/div/div/img\".format(i)).get_attribute('href')\n imageLink = 'https://static-prod.weplay.tv/2020-09-06/w-2048/webp/973eedcbdec2f381fe92fd9199987288.120D2F-B20834-0AB9E4.jpeg'\n bot.get(tournamentLink)\n time.sleep(5)\n try:\n title = wait.until(EC.element_to_be_clickable((By.XPATH,\n \"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[2]/div[2]/div/div[1]/div[2]/div[1]/div[2]/h1\"))).text\n except TimeoutException:\n title = bot.find_element_by_xpath(\"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[2]/div[2]/div/div[1]/div/div[1]/div[2]/h1\").text\n status = \"Будущий\"\n startTime = \"TEST\"\n gameMode = bot.find_element_by_xpath(\n \"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[4]/div/div/div/div[2]/div[1]/div[1]/div[2]/div[3]/div/div[2]/span[2]/span/span\").text\n participantReg = bot.find_element_by_xpath(\n \"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[4]/div/div/div/div[2]/div[2]/div[1]/div[2]/a/div/div/div[2]/div[2]/span\").text\n participantAll = bot.find_element_by_xpath(\n \"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[4]/div/div/div/div[2]/div[2]/div[1]/div[2]/a/div/div/div[3]/div[2]/span\").text\n participant = participantReg + '/' + participantAll\n countReward = bot.find_element_by_xpath(\n \"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[4]/div/div/div/div[2]/div[1]/div[1]/div[2]/div[5]/div/div[2]/span[2]/span/span\").text.replace(\n '€', '')\n countReward = countReward.split('.')\n countReward = countReward[0]\n countReward = countReward.split()\n countReward = countReward[0]\n name = 'ChallengerMode'\n gameMode = gameMode.split(' ')\n gameMode = gameMode[0]\n if countReward.isalpha():\n countReward = 0\n currencyReward = 0\n typeReward = 0\n else:\n typeReward = 'Деньги'\n currencyReward = '€'\n\n print(title, status, startTime, gameMode, participant, countReward, name, tournamentLink, imageLink,\n currencyReward, typeReward)\n\n siteNameObject = SiteName.objects.get(name='ChallengerMode')\n gameModeObject = GameMode.objects.get(mode=gameMode)\n\n try:\n rewardObject = Reward.objects.create(type=typeReward, count=countReward, currency=currencyReward)\n linkObject = Link.objects.create(image=imageLink, tournament=tournamentLink)\n newObject = Dota.objects.create(title=title, status=status, startTime=startTime, gameMode=gameModeObject,\n participant=participant, reward=rewardObject, siteName=siteNameObject,\n links=linkObject, ip='127.0.0.1')\n\n except IntegrityError:\n print(\"Updating row...\")\n Dota.objects.filter(title=title).update(status=status, participant=participant)\n" }, { "alpha_fraction": 0.7349397540092468, "alphanum_fraction": 0.7349397540092468, "avg_line_length": 15.600000381469727, "blob_id": "4325715a0d7fbe9329d1808b53a0161d1806a995", "content_id": "ff2abe96a481094526414599090d14174b8122a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 83, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/Dota/apps.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass DotaConfig(AppConfig):\n name = 'Dota'\n" }, { "alpha_fraction": 0.7553191781044006, "alphanum_fraction": 0.7553191781044006, "avg_line_length": 30.399999618530273, "blob_id": "2640c659e560011bd7e10757be24323a9d574eff", "content_id": "73b8ca1715ca4f832a1e3fb9b5899d486cb7b9ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/cyberTournaments/urls.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path, include\nfrom rest_framework import permissions\nfrom .yasg import urlpatterns as yasgUrls\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\n\nurlpatterns = [\n path('dota/', include('Dota.urls')),\n path('admin/', admin.site.urls),\n path('api-auth/', include('rest_framework.urls'))\n] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\nurlpatterns += yasgUrls" }, { "alpha_fraction": 0.6074582934379578, "alphanum_fraction": 0.6180078387260437, "avg_line_length": 29.863636016845703, "blob_id": "c6132f35352ab4429c2dfbcaa31295c2fb3ffc73", "content_id": "9384eec523b7d7af6d1d20b7eae7a58e7b72026f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4076, "license_type": "no_license", "max_line_length": 116, "num_lines": 132, "path": "/Dota/views.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "from rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .models import Dota\nfrom .serializers import DotaListSerializer, DotaTestListSerializer\nfrom drf_yasg.utils import swagger_auto_schema\nfrom django.http import HttpResponse\n\n\nclass DotaListView(APIView):\n\n @swagger_auto_schema(operation_summary=\"This is all data from Dota db\")\n\n def get(self, request):\n tournaments = Dota.objects.select_related('siteName', 'gameMode', 'links').all()\n serializer = DotaListSerializer(tournaments, many=True)\n\n return Response(serializer.data)\n\n\nclass DotaListViewSiteName(APIView):\n\n @swagger_auto_schema(operation_summary=\"This is all tournaments from specific site\",\n operation_description=\"Enter site name\")\n def get(self, request, siteName):\n tournaments = Dota.objects.filter(siteName=siteName)\n serializer = DotaListSerializer(tournaments, many=True)\n\n return Response(serializer.data)\n\nclass DotaListViewStatus(APIView):\n\n @swagger_auto_schema(operation_summary=\"This is all tournaments with specific status\",\n operation_description=\"Enter status\")\n def get(self, request, status):\n tournaments = Dota.objects.filter(status=status)\n serializer = DotaListSerializer(tournaments, many=True)\n\n return Response(serializer.data)\n\nclass DotaListViewTest(APIView):\n\n @swagger_auto_schema(operation_summary=\"This is data for tests\")\n\n def get(self, request):\n tournaments = Dota.objects.all()\n serializer = DotaTestListSerializer(tournaments, many=True)\n\n return Response(serializer.data)\n\n# class AddParticipant(APIView):\n#\n# def get_client_ip(self, request):\n# x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n# if x_forwarded_for:\n# ip = x_forwarded_for.split(',')[0]\n# else:\n# ip = request.META.get('REMOTE_ADDR')\n# return ip\n#\n# def post(self, request):\n# serializer = CreateParticipantSerializer(data=request.data)\n# if serializer.is_valid():\n# serializer.save(ip=self.get_client_ip(request))\n# return Response(status=201)\n# else:\n# return Response(status=400)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# cursor = connections['default'].cursor()\n#\n#\n# def index(request):\n# cursor.execute('SELECT * FROM \"Dota_dota\"')\n# data = cursor.fetchall()\n# jsonData = []\n# for obj in data:\n# jsonData.append({\"id\": obj[0], \"title\": obj[1], \"status\": obj[2], \"startTime\": obj[3], \"gameMode\": obj[4],\n# \"participant\": obj[5], \"reward\": obj[6], \"siteName\": obj[7], \"link\": obj[8],\n# \"dateTime\": obj[9], \"img\": obj[10]})\n#\n# return JsonResponse(jsonData, safe=False, json_dumps_params={'ensure_ascii': False})\n#\n# def byDateDota(request):\n# cursor.execute('SELECT * FROM \"Dota_dota\" ORDER BY \"dateTime\"')\n# data = cursor.fetchall()\n# jsonData = []\n# for obj in data:\n# jsonData.append({\"id\": obj[0], \"title\": obj[1], \"status\": obj[2], \"startTime\": obj[3], \"gameMode\": obj[4],\n# \"participant\": obj[5], \"reward\": obj[6], \"siteName\": obj[7], \"link\": obj[8],\n# \"dateTime\": obj[9], \"img\": obj[10]})\n#\n# return JsonResponse(jsonData, safe=False, json_dumps_params={'ensure_ascii': False})\n#\n#\n# def byRewardDota(request):\n# cursor.execute('SELECT * FROM \"Dota_dota\" ORDER BY \"reward\"')\n# data = cursor.fetchall()\n# jsonData = []\n# for obj in data:\n# jsonData.append({\"id\": obj[0], \"title\": obj[1], \"status\": obj[2], \"startTime\": obj[3], \"gameMode\": obj[4],\n# \"participant\": obj[5], \"reward\": obj[6], \"siteName\": obj[7], \"link\": obj[8],\n# \"dateTime\": obj[9], \"img\": obj[10]})\n# print(jsonData)\n#\n# return JsonResponse(jsonData, safe=False, json_dumps_params={'ensure_ascii': False})\n# # return HttpResponse(\"Dota tournaments ordered by reward\")\n\n\n" }, { "alpha_fraction": 0.5181195139884949, "alphanum_fraction": 0.7051910161972046, "avg_line_length": 17.563636779785156, "blob_id": "2ef46adb780474920bba395c1f1af4e5448f34f8", "content_id": "d06edc439f19b4397137dc8071aca078c7a62811", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1021, "license_type": "no_license", "max_line_length": 28, "num_lines": 55, "path": "/requirements.txt", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "amqp==5.0.6\nasgiref==3.4.1\nbilliard==3.6.4.0\ncelery==5.1.2\ncertifi==2021.5.30\nchardet==4.0.0\nclick==7.1.2\nclick-didyoumean==0.0.3\nclick-plugins==1.1.1\nclick-repl==0.2.0\ncoreapi==2.3.3\ncoreschema==0.0.4\ndj-database-url==0.5.0\nDjango==3.2.5\ndjango-celery-beat==2.2.1\ndjango-celery-results==2.2.0\ndjango-cors-headers==3.8.0\ndjango-heroku==0.3.1\ndjango-ninja==0.13.2\ndjango-rest-swagger==2.2.0\ndjango-timezone-field==4.2.1\ndjangorestframework==3.12.4\ndrf-yasg==1.20.0\ngunicorn==20.1.0\nidna==2.10\ninflection==0.5.1\nitypes==1.2.0\nJinja2==3.0.1\nkombu==5.1.0\nMarkupSafe==2.0.1\nopenapi-codec==1.3.2\npackaging==21.0\nPillow==8.3.0\nprompt-toolkit==3.0.19\npsycopg2==2.9.1\npsycopg2-binary==2.9.1\npydantic==1.8.2\npyparsing==2.4.7\npython-crontab==2.5.1\npython-dateutil==2.8.1\npytz==2021.1\nredis==3.5.3\nrequests==2.25.1\nruamel.yaml==0.17.10\nruamel.yaml.clib==0.2.6\nselenium==3.141.0\nsimplejson==3.17.2\nsix==1.16.0\nsqlparse==0.4.1\ntyping-extensions==3.10.0.0\nuritemplate==3.0.1\nurllib3==1.26.6\nvine==5.0.0\nwcwidth==0.2.5\nwhitenoise==5.2.0\n" }, { "alpha_fraction": 0.551886796951294, "alphanum_fraction": 0.6014150977134705, "avg_line_length": 22.55555534362793, "blob_id": "0a8a0b7b4cd2025ffa8ab9ea2f0b5ca6656d7148", "content_id": "7f18af3450e0f2ce091a7f0dafa6124855b60600", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "no_license", "max_line_length": 91, "num_lines": 18, "path": "/Dota/migrations/0009_alter_dota_starttime.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-09-04 13:25\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0008_alter_reward_type'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dota',\n name='startTime',\n field=models.CharField(max_length=25, verbose_name='Date of tournament start'),\n ),\n ]\n" }, { "alpha_fraction": 0.5318182110786438, "alphanum_fraction": 0.6045454740524292, "avg_line_length": 23.44444465637207, "blob_id": "b84036d7ed92485b44c8aa266c58f39422aef282", "content_id": "17c3cc1e71da6757fa70fe230534dde64dac8683", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 440, "license_type": "no_license", "max_line_length": 107, "num_lines": 18, "path": "/Dota/migrations/0005_alter_dota_currency.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-07-12 16:30\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0004_auto_20210712_1927'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dota',\n name='currency',\n field=models.CharField(blank=True, max_length=5, null=True, verbose_name='Currence of reward'),\n ),\n ]\n" }, { "alpha_fraction": 0.5460526347160339, "alphanum_fraction": 0.6381579041481018, "avg_line_length": 16, "blob_id": "2514dd71c00b169fb47b4c862d16dac9ca249246", "content_id": "04ac867755d9e50b6988a286f3d80504410480cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/timeTest.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "import time\n\na = time.localtime()\nx = time.strftime(\"%d.%m.%Y, %H:%M:%S\", a)\nprint(x) \n# 18.03.2021, 20:47:30\n\nimport django\nprint(django.get_version())" }, { "alpha_fraction": 0.5244755148887634, "alphanum_fraction": 0.6013985872268677, "avg_line_length": 22.83333396911621, "blob_id": "29af24a2b9f5468ae56d2ebdf6173af3465e3727", "content_id": "ae87278f74c66b80d637cff1a7257094569db277", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 99, "num_lines": 18, "path": "/Dota/migrations/0011_alter_dota_title.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-09-05 13:12\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0010_auto_20210904_1630'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dota',\n name='title',\n field=models.CharField(max_length=50, unique=True, verbose_name='Title of tournament'),\n ),\n ]\n" }, { "alpha_fraction": 0.5522041916847229, "alphanum_fraction": 0.6032482385635376, "avg_line_length": 22.94444465637207, "blob_id": "161d63c1ce4ab3d5192529f25daf604816510990", "content_id": "e3162eb890413376cbfb929b0c5c66a51b3dc142", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 100, "num_lines": 18, "path": "/Dota/migrations/0018_alter_dota_title.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-09-21 17:48\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0017_alter_sitename_name'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dota',\n name='title',\n field=models.CharField(max_length=100, unique=True, verbose_name='Title of tournament'),\n ),\n ]\n" }, { "alpha_fraction": 0.5328884720802307, "alphanum_fraction": 0.5519542694091797, "avg_line_length": 26.605262756347656, "blob_id": "b9c1b8b44b6f41c82e6f1e3abea0a8c351517020", "content_id": "7b73f97d8b66280a5a810fcdcb9effe995652e1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1049, "license_type": "no_license", "max_line_length": 108, "num_lines": 38, "path": "/Dota/migrations/0010_auto_20210904_1630.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-09-04 13:30\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0009_alter_dota_starttime'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='dota',\n name='imgLink',\n ),\n migrations.RemoveField(\n model_name='dota',\n name='tournLink',\n ),\n migrations.AddField(\n model_name='dota',\n name='links',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='Dota.link'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='link',\n name='image',\n field=models.URLField(verbose_name='URL of image'),\n ),\n migrations.AlterField(\n model_name='link',\n name='tournament',\n field=models.URLField(verbose_name='URL of tournament'),\n ),\n ]\n" }, { "alpha_fraction": 0.6736725568771362, "alphanum_fraction": 0.6836283206939697, "avg_line_length": 26.42424201965332, "blob_id": "80af05b763ad9ec2307003a92b3af1574f31e96b", "content_id": "b046a7a7c6e2211f07d4cd711c8ee8c3f91dd9c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 904, "license_type": "no_license", "max_line_length": 76, "num_lines": 33, "path": "/cyberTournaments/celery.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "import os\n\nfrom celery import Celery\n\n# Set the default Django settings module for the 'celery' program.\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cyberTournaments.settings')\n\napp = Celery('cyberTournaments')\n\n# Using a string here means the worker doesn't have to serialize\n# the configuration object to child processes.\n# - namespace='CELERY' means all celery-related configuration keys\n# should have a `CELERY_` prefix.\napp.config_from_object('django.conf:settings', namespace='CELERY')\n\n# Load task modules from all registered Django apps.\napp.autodiscover_tasks()\n\n\napp.conf.beat_schedule = {\n 'addDotaWeplay': {\n 'task': 'Dota.tasks.addDotaWeplay',\n 'schedule': 40.0\n },\n 'addDotaGamelix': {\n 'task': 'Dota.tasks.addDotaGamelix',\n 'schedule': 40.0\n },\n 'addDotaCmode': {\n 'task': 'Dota.tasks.addDotaCmode',\n 'schedule': 40.0\n }\n}" }, { "alpha_fraction": 0.5761356949806213, "alphanum_fraction": 0.6067459583282471, "avg_line_length": 52.4375, "blob_id": "5943408e3fe682029b9c633bf7f0830881230a75", "content_id": "6379e3f1dfa5ccf3cce1fe9c702b0c8ab545aa5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5146, "license_type": "no_license", "max_line_length": 209, "num_lines": 96, "path": "/addData.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "from celery import shared_task\n\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException\n\n# con = psycopg2.connect(\n# host='localhost',\n# database='cybertournaments',\n# port='5432',\n# user='rodionibragimov',\n# password='3470')\n# cur = con.cursor()\n#\n# def addData(title, status, startTime, gameMode, participant, reward, siteName, link, img):\n# cur.execute(\n# 'insert into \"Dota_dota\" (\"title\", \"status\", \"startTime\", \"gameMode\", \"participant\", \"reward\", \"siteName\", \"link\", \"dateTime\", \"img\") values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',\n# (title, status, startTime, gameMode, participant, reward,\n# siteName, link,\n# datetime.now(), img))\n#\n# con.commit()\n#\n# cur.close()\n# con.close()\n\ndef addDotaCmode():\n linkDota = 'https://www.challengermode.com/dota2/tournaments?state=upcoming'\n bot = webdriver.Chrome(r'C:\\Users\\injir\\Documents\\cyberTournaments\\chromedriver.exe')\n wait = WebDriverWait(bot, 10)\n\n for i in range(1, 10):\n bot.get(linkDota)\n\n tournamentLink = wait.until(EC.element_to_be_clickable((By.XPATH,\n \"/html/body/div[2]/div/div/div[1]/div[2]/div[2]/div[1]/div[1]/div/div/div[1]/div/div/div/div[1]/div[3]/div/div/div[{}]/span/div/div/a\".format(\n i)))).get_attribute('href')\n # imageLink = bot.find_element_by_xpath(\n # \"/html/body/div[2]/div/div/div/div[2]/div[1]/div/div/div/div[1]/div/div/div[2]/div/div[2]/div/div/div[{}]/div/div/div[1]/div/div[1]/div/div/div/a/div/div/div/img\".format(i)).get_attribute('href')\n imageLink = 'https://static-prod.weplay.tv/2020-09-06/w-2048/webp/973eedcbdec2f381fe92fd9199987288.120D2F-B20834-0AB9E4.jpeg'\n bot.get(tournamentLink)\n time.sleep(5)\n try:\n title = wait.until(EC.element_to_be_clickable((By.XPATH,\n \"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[2]/div[2]/div/div[1]/div[2]/div[1]/div[2]/h1\"))).text\n except NoSuchElementException:\n title = bot.find_element_by_xpath(\"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[2]/div[2]/div/div[1]/div/div[1]/div[2]/h1\").text\n status = \"Будущий\"\n startTime = \"HUI\"\n gameMode = bot.find_element_by_xpath(\n \"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[4]/div/div/div/div[2]/div[1]/div[1]/div[2]/div[3]/div/div[2]/span[2]/span/span\").text\n participantReg = bot.find_element_by_xpath(\n \"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[4]/div/div/div/div[2]/div[2]/div[1]/div[2]/a/div/div/div[2]/div[2]/span\").text\n participantAll = bot.find_element_by_xpath(\n \"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[4]/div/div/div/div[2]/div[2]/div[1]/div[2]/a/div/div/div[3]/div[2]/span\").text\n participant = participantReg + '/' + participantAll\n countReward = bot.find_element_by_xpath(\n \"/html/body/div[2]/div/div/div/div[2]/div[2]/div[1]/div[1]/div/div/div/div/div[4]/div/div/div/div[2]/div[1]/div[1]/div[2]/div[5]/div/div[2]/span[2]/span/span\").text.replace(\n '€', '')\n countReward = countReward.split('.')\n countReward = countReward[0]\n countReward = countReward.split()\n countReward = countReward[0]\n name = 'ChallengerMode'\n gameMode = gameMode.split(' ')\n gameMode = gameMode[0]\n if countReward.isalpha():\n countReward = 0\n currencyReward = 0\n typeReward = 0\n else:\n typeReward = 'Деньги'\n currencyReward = '€'\n\n print(title, status, startTime, gameMode, participant, countReward, name, tournamentLink, imageLink,\n currencyReward, typeReward)\n\n # siteNameObject = SiteName.objects.get(name='ChallengerMode')\n # gameModeObject = GameMode.objects.get(mode=gameMode)\n #\n # try:\n # rewardObject = Reward.objects.create(type=typeReward, count=countReward, currency=currencyReward)\n # linkObject = Link.objects.create(image=imageLink, tournament=tournamentLink)\n # newObject = Dota.objects.create(title=title, status=status, startTime=startTime, gameMode=gameModeObject,\n # participant=participant, reward=rewardObject, siteName=siteNameObject,\n # links=linkObject, ip='127.0.0.1')\n #\n # except IntegrityError:\n # print(\"Updating row...\")\n # Dota.objects.filter(title=title).update(status=status, participant=participant)\n\naddDotaCmode()" }, { "alpha_fraction": 0.5746209025382996, "alphanum_fraction": 0.5881883502006531, "avg_line_length": 40.766666412353516, "blob_id": "4db828e935333be2682edc5ed8c58ef74de025b2", "content_id": "c0a2cd2b1d161c1f5d6abb188231c6938df0738e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 114, "num_lines": 30, "path": "/Dota/migrations/0001_initial.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-07-07 15:07\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Dota',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.TextField(verbose_name='Title of tournament')),\n ('img', models.TextField(verbose_name='Image of tournament')),\n ('status', models.TextField(verbose_name='Status of tournament')),\n ('startTime', models.TextField(verbose_name='Date of tournament start')),\n ('gameMode', models.TextField(verbose_name='Game mode of tournament')),\n ('participant', models.TextField(verbose_name='Number of participants')),\n ('reward', models.TextField(verbose_name='Tournament reward')),\n ('siteName', models.TextField(verbose_name='Name of site')),\n ('link', models.URLField(verbose_name='URL of tournament')),\n ('ip', models.CharField(max_length=15, verbose_name='IP address')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5386363863945007, "alphanum_fraction": 0.5840908885002136, "avg_line_length": 22.157894134521484, "blob_id": "2cf7ee4d66187860d51fabae87255f9a5a2bed3d", "content_id": "6abfe28b7c7605c4c70f752667a685df2bf545c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 440, "license_type": "no_license", "max_line_length": 79, "num_lines": 19, "path": "/Dota/migrations/0003_dota_link.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-07-07 15:22\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0002_remove_dota_link'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='dota',\n name='link',\n field=models.URLField(default=0, verbose_name='URL of tournament'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.5203390121459961, "alphanum_fraction": 0.5559322237968445, "avg_line_length": 23.58333396911621, "blob_id": "f21ee1e9fe16262d78036fe0fc4b840e067df5a2", "content_id": "b3669c429b036f9796ae8dc68bcc2da4a7616cb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 590, "license_type": "no_license", "max_line_length": 95, "num_lines": 24, "path": "/Dota/migrations/0004_auto_20210712_1927.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-07-12 16:27\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0003_dota_link'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='dota',\n old_name='link',\n new_name='Tournlink',\n ),\n migrations.AddField(\n model_name='dota',\n name='currency',\n field=models.CharField(default=0, max_length=5, verbose_name='Currence of reward'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5612903237342834, "avg_line_length": 17.235294342041016, "blob_id": "a88d3f672e541763028cfe53bb211574e10d5429", "content_id": "c598e561f55ff2b7d25065684fdb758152130dc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 310, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/Dota/migrations/0002_remove_dota_link.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-07-07 15:20\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='dota',\n name='link',\n ),\n ]\n" }, { "alpha_fraction": 0.5221444964408875, "alphanum_fraction": 0.5990676283836365, "avg_line_length": 22.83333396911621, "blob_id": "42e65a57df624e7f19a8edb52d9ff6eef029b852", "content_id": "e0c943b1e2717f29197722e706c4fc2b3038d8d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 96, "num_lines": 18, "path": "/Dota/migrations/0016_alter_gamemode_mode.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-09-05 16:18\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0015_auto_20210905_1806'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='gamemode',\n name='mode',\n field=models.CharField(max_length=10, unique=True, verbose_name='Mode of the game'),\n ),\n ]\n" }, { "alpha_fraction": 0.5324786305427551, "alphanum_fraction": 0.5658119916915894, "avg_line_length": 29.789474487304688, "blob_id": "097728ecbf9695f205877d49b6e529fcc91b9d9a", "content_id": "5509e11b2277f091451ba3dbdf2609e7aa599db9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1170, "license_type": "no_license", "max_line_length": 91, "num_lines": 38, "path": "/Dota/migrations/0007_auto_20210816_2311.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-08-16 20:11\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Dota', '0006_auto_20210816_2307'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dota',\n name='participant',\n field=models.CharField(max_length=10, verbose_name='Number of participants'),\n ),\n migrations.AlterField(\n model_name='dota',\n name='startTime',\n field=models.CharField(max_length=15, verbose_name='Date of tournament start'),\n ),\n migrations.AlterField(\n model_name='dota',\n name='status',\n field=models.CharField(max_length=15, verbose_name='Status of tournament'),\n ),\n migrations.AlterField(\n model_name='dota',\n name='title',\n field=models.CharField(max_length=50, verbose_name='Title of tournament'),\n ),\n migrations.AlterField(\n model_name='link',\n name='image',\n field=models.URLField(unique=True, verbose_name='URL of image'),\n ),\n ]\n" }, { "alpha_fraction": 0.5554550886154175, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 41.52564239501953, "blob_id": "76f8adf026a4c212bc2b009ebb2e1026bb1adeff", "content_id": "16a67d8ea1b94d5b957dd698da2ad669f5d9378f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3318, "license_type": "no_license", "max_line_length": 193, "num_lines": 78, "path": "/wePlayParser.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n# from addData import addData\nimport psycopg2\nfrom datetime import datetime\n\nlinkDota = 'https://weplay.tv/ru/tournaments/dota2'\n\ncon = psycopg2.connect(\n host='localhost',\n database='cybertournaments',\n port='5432',\n user='postgres',\n password='3470')\ncon.set_client_encoding('win1251')\ncur = con.cursor()\n\nclass WePlay:\n\n def __init__(self, link):\n chromeOptions = Options()\n # chromeOptions.add_argument('--headless')\n\n self.bot = webdriver.Chrome(r'C:\\Users\\injir\\Documents\\cyberTournaments\\chromedriver.exe')\n\n self.link = link\n\n def parser(self):\n bot = self.bot\n wait = WebDriverWait(bot, 10)\n\n bot.get(self.link)\n # bot.maximize_window()\n\n for i in range(1, 10):\n title = wait.until(EC.element_to_be_clickable((By.XPATH,\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[1]/div/div/a\".format(i)))).text\n status = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[2]/span\".format(i)).text\n image = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[1]/div/a/div/img\".format(i)).get_attribute('src')\n startTime = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[2]/p\".format(i)).text\n gameMode = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[3]/p[1]/a\".format(i)).text\n participant = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[5]/p\".format(i)).text\n reward = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[6]/p\".format(i)).text\n siteName = title.split()\n # rewardCount = reward.replace('$', '')\n # reward = reward.split()\n # reward = '$ ' + reward[1]\n\n link = bot.find_element_by_xpath(\n \"//*[@id='app']/div/main/div[1]/div/div/div/div[2]/table/tbody/tr[{}]/td[1]/div/div/a\".format(\n i)).get_attribute('href')\n print(title, status, startTime, gameMode, participant, reward, siteName[0], link, image)\n # addData(title, status, startTime, gameMode, participant, reward, siteName[0], link, image)\n # time.sleep(30)\n cur.execute(\n 'insert into \"Dota_dota\" (\"title\", \"status\", \"startTime\", \"gameMode\", \"participant\", \"reward\", \"siteName\", \"link\", \"img\", \"ip\") values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',\n (title, status, startTime, gameMode, participant, reward,\n siteName[0], link, image, '127.0.0.1'))\n\n con.commit()\n\n cur.close()\n con.close()\n\n\nrod = WePlay(linkDota)\nrod.parser()\n\n" }, { "alpha_fraction": 0.805343508720398, "alphanum_fraction": 0.805343508720398, "avg_line_length": 28.11111068725586, "blob_id": "0daa42cbfec4b55b37f2583081e97461d5d3d893", "content_id": "4245ac6b436058b679d8205251de1568d53abeb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 262, "license_type": "no_license", "max_line_length": 58, "num_lines": 9, "path": "/Dota/admin.py", "repo_name": "injirez/cyberTournaments", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Dota, Reward, GameMode, SiteName, Link\n\nadmin.site.register(Dota)\nadmin.site.register(Reward)\nadmin.site.register(SiteName)\nadmin.site.register(GameMode)\nadmin.site.register(Link)\n# Register your models here.\n" } ]
29
Atomu2014/uda
https://github.com/Atomu2014/uda
88a84c45e329a11173ade93a4519ebdbde0732cd
9acf872bbea41669499ea1109a740eded3f65f00
80b96bcdd2f2e8d099107b4117d80dba60d7a46c
refs/heads/master
2020-07-26T14:24:30.756629
2019-12-17T08:43:35
2019-12-17T08:43:35
208,674,450
0
0
Apache-2.0
2019-09-15T23:59:41
2019-09-15T23:59:34
2019-08-21T10:23:59
null
[ { "alpha_fraction": 0.6384658813476562, "alphanum_fraction": 0.6508741974830627, "avg_line_length": 26.27692222595215, "blob_id": "0c2fd819ba281fefedbf1a1271e6d4bfc62678d1", "content_id": "dfde386c500a07755407d9df995d4e36d63a602b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1773, "license_type": "permissive", "max_line_length": 65, "num_lines": 65, "path": "/text/scripts/prepro.sh", "repo_name": "Atomu2014/uda", "src_encoding": "UTF-8", "text": "#!/bin/bash\nbert_vocab_file=pretrained_models/bert_base/vocab.txt\n\n\n#python3 preprocess.py \\\n# --raw_data_dir=data/IMDB_raw/csv/train.csv \\\n# --output_base_dir=../back_translate/imdb.txt \\\n# --data_type=back_trans \\\n# --vocab_file=$bert_vocab_file\n\n\n#python3 preprocess.py \\\n# --raw_data_dir=data/IMDB_raw/csv \\\n# --output_base_dir=data/proc_data/IMDB/pseudo \\\n# --back_translation_dir=data/back_translation/imdb_back_trans \\\n# --data_type=pseudo \\\n# --sub_set=unsup_in \\\n# --aug_ops=bt-1 \\\n# --aug_copy_num=0 \\\n# --vocab_file=$bert_vocab_file \\\n# --max_seq_length=${MAX_SEQ_LENGTH}\n\n\n## Preprocess supervised training set\n#python3 preprocess.py \\\n# --raw_data_dir=data/IMDB_raw/csv \\\n# --output_base_dir=data/proc_data/IMDB/train_20 \\\n# --data_type=sup \\\n# --sub_set=train \\\n# --sup_size=20 \\\n# --vocab_file=$bert_vocab_file \\\n# --max_seq_length=${MAX_SEQ_LENGTH}\n\npython3 preprocess.py \\\n --task_name=yelp-2 \\\n --raw_data_dir=data/yelp-2 \\\n --output_base_dir=data/proc_data/yelp-2/train \\\n --data_type=sup \\\n --sub_set=train \\\n --sup_size=-1 \\\n --vocab_file=$bert_vocab_file \\\n --max_seq_length=${MAX_SEQ_LENGTH}\n\n# Preprocess test set\npython3 preprocess.py \\\n --task_name=yelp-2 \\\n --raw_data_dir=data/yelp-2 \\\n --output_base_dir=data/proc_data/yelp-2/dev \\\n --data_type=sup \\\n --sub_set=dev \\\n --vocab_file=$bert_vocab_file \\\n --max_seq_length=${MAX_SEQ_LENGTH}\n\n\n## Preprocess unlabeled set\n#python3 preprocess.py \\\n# --raw_data_dir=data/IMDB_raw/csv \\\n# --output_base_dir=data/proc_data/IMDB/unsup \\\n# --back_translation_dir=data/back_translation/imdb_back_trans \\\n# --data_type=unsup \\\n# --sub_set=unsup_in \\\n# --aug_ops=bt-0.9 \\\n# --aug_copy_num=0 \\\n# --vocab_file=$bert_vocab_file \\\n# --max_seq_length=${MAX_SEQ_LENGTH}\n" }, { "alpha_fraction": 0.63456791639328, "alphanum_fraction": 0.6580246686935425, "avg_line_length": 28.962963104248047, "blob_id": "446e009d998cd16ecca8b96b001a301e7dafdf3b", "content_id": "13742aaebca346013ff799330e78538ca5869c01", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 810, "license_type": "permissive", "max_line_length": 78, "num_lines": 27, "path": "/text/scripts/run_pseudo.sh", "repo_name": "Atomu2014/uda", "src_encoding": "UTF-8", "text": "bert=imdb_bert_ft\ndata=bt-1\nckpt=bt_1_0\nsteps=30000\nwarmup=3000\nlr=1e-5\ntrain_bsz=16\neval_bsz=8\n\npython3 main.py \\\n --use_tpu=False \\\n --tpu_name=kevin \\\n --do_train=True \\\n --do_eval=True \\\n --sup_train_data_dir=$GS/uda/text/data/proc_data/IMDB/pseudo/${data}/0 \\\n --eval_data_dir=$GS/uda/text/data/proc_data/IMDB/dev \\\n --bert_config_file=$GS/uda/text/pretrained_models/${bert}/bert_config.json \\\n --vocab_file=$GS/uda/text/pretrained_models/${bert}/vocab.txt \\\n --init_checkpoint=$GS/uda/text/pretrained_models/${bert}/bert_model.ckpt \\\n --task_name=IMDB \\\n --model_dir=$GS/uda/text/ckpt/${ckpt} \\\n --num_train_steps=${steps} \\\n --learning_rate=${lr} \\\n --num_warmup_steps=${warmup} \\\n --max_seq_length=${MAX_SEQ_LENGTH} \\\n --train_batch_size=${train_bsz} \\\n --eval_batch_size=${eval_bsz}\n\n" }, { "alpha_fraction": 0.6929824352264404, "alphanum_fraction": 0.7105262875556946, "avg_line_length": 21.799999237060547, "blob_id": "520cf5f6f021f5aba1af135214f30f10b69fa69e", "content_id": "1dcb924e4d5c516d7bc07d8cbf307ea1d8646feb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 114, "license_type": "permissive", "max_line_length": 50, "num_lines": 5, "path": "/text/unzip.py", "repo_name": "Atomu2014/uda", "src_encoding": "UTF-8", "text": "import sys\nimport zipfile\n\nwith zipfile.ZipFile(sys.argv[1], 'r') as zip_ref:\n zip_ref.extractall(sys.argv[2])\n" }, { "alpha_fraction": 0.6998394727706909, "alphanum_fraction": 0.7191011309623718, "avg_line_length": 40.53333282470703, "blob_id": "5ed64c4b2893b912fe09ba39c7e6798f7fb11920", "content_id": "df79bbc163110542751a8e855e305ccdcc3ba319", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1246, "license_type": "permissive", "max_line_length": 83, "num_lines": 30, "path": "/text/scripts/eval.sh", "repo_name": "Atomu2014/uda", "src_encoding": "UTF-8", "text": "# coding=utf-8\n# Copyright 2019 The Google UDA Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\npython3 main.py \\\n --use_tpu=False \\\n --tpu_name=kevin \\\n --do_train=False \\\n --do_eval=True \\\n --sup_train_data_dir=$GS/uda/text/data/proc_data/IMDB/train \\\n --eval_data_dir=$GS/uda/text/data/proc_data/IMDB/dev \\\n --bert_config_file=$GS/uda/text/pretrained_models/imdb_bert_ft/bert_config.json \\\n --vocab_file=$GS/uda/text/pretrained_models/imdb_bert_ft/vocab.txt \\\n --init_checkpoint=$GS/uda/text/pretrained_models/imdb_bert_ft/bert_model.ckpt \\\n --task_name=IMDB \\\n --model_dir=$GS/uda/text/ckpt/base_13 \\\n --num_train_steps=30000 \\\n --learning_rate=3e-06 \\\n --num_warmup_steps=3000 \\\n --max_seq_length=${MAX_SEQ_LENGTH}\n" }, { "alpha_fraction": 0.6306892037391663, "alphanum_fraction": 0.6514954566955566, "avg_line_length": 29.760000228881836, "blob_id": "af5d1bb6a47a2ec1d8977131a7def660d387ce6f", "content_id": "ae274a0b10d63c4fa10541c24e3e2f3dbbfb3664", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 769, "license_type": "permissive", "max_line_length": 78, "num_lines": 25, "path": "/text/scripts/run_base.sh", "repo_name": "Atomu2014/uda", "src_encoding": "UTF-8", "text": "data=yelp-2\nbert=bert_large\nckpt=large_0\nstep=10000\nlr=1e-5\nwarmup=1000\n\npython3 main.py \\\n --use_tpu=False \\\n --tpu_name=kevin \\\n --do_train=True \\\n --do_eval=True \\\n --sup_train_data_dir=$GS/uda/text/data/proc_data/${data}/train \\\n --eval_data_dir=$GS/uda/text/data/proc_data/${data}/dev \\\n --bert_config_file=$GS/uda/text/pretrained_models/${bert}/bert_config.json \\\n --vocab_file=$GS/uda/text/pretrained_models/${bert}/vocab.txt \\\n --init_checkpoint=$GS/uda/text/pretrained_models/${bert}/bert_model.ckpt \\\n --task_name=${data} \\\n --model_dir=$GS/uda/text/ckpt/${data}/${ckpt} \\\n --num_train_steps=${step} \\\n --learning_rate=${lr} \\\n --num_warmup_steps=${warmup} \\\n --max_seq_length=${MAX_SEQ_LENGTH} \\\n --train_batch_size=4 \\\n --eval_batch_size=8\n" }, { "alpha_fraction": 0.6645230650901794, "alphanum_fraction": 0.6864951848983765, "avg_line_length": 33.55555725097656, "blob_id": "f36b772e5c9a3138d838d7601c596a1c9d891edd", "content_id": "861f9ca404e29ae65eacb72878cf476a08242770", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1866, "license_type": "permissive", "max_line_length": 74, "num_lines": 54, "path": "/text/scripts/train_large_tpu.sh", "repo_name": "Atomu2014/uda", "src_encoding": "UTF-8", "text": "# coding=utf-8\n# Copyright 2019 The Google UDA Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\ntrain_tpu=kevin\neval_tpu=kevin\nbert_model_dir=$GS/uda/text/pretrained_models/bert_large\nmodel_dir=$GS/uda/text/ckpt/large_exp_5\n\npython3 main.py \\\n --use_tpu=True \\\n --tpu_name=${train_tpu} \\\n --do_train=True \\\n --do_eval=False \\\n --sup_train_data_dir=$GS/uda/text/data/proc_data/IMDB/train_20 \\\n --eval_data_dir=$GS/uda/text/data/proc_data/IMDB/dev \\\n --bert_config_file=${bert_model_dir}/bert_config.json \\\n --vocab_file=${bert_model_dir}/vocab.txt \\\n --init_checkpoint=${bert_model_dir}/bert_model.ckpt \\\n --task_name=IMDB \\\n --model_dir=${model_dir} \\\n --max_seq_length=${MAX_SEQ_LENGTH} \\\n --num_train_steps=3000 \\\n --learning_rate=3e-05 \\\n --train_batch_size=32 \\\n --num_warmup_steps=300\n\npython3 main.py \\\n --use_tpu=True \\\n --tpu_name=${eval_tpu} \\\n --do_train=False \\\n --do_eval=True \\\n --sup_train_data_dir=$GS/uda/text/data/proc_data/IMDB/train_20 \\\n --eval_data_dir=$GS/uda/text/data/proc_data/IMDB/dev \\\n --bert_config_file=${bert_model_dir}/bert_config.json \\\n --vocab_file=${bert_model_dir}/vocab.txt \\\n --task_name=IMDB \\\n --model_dir=${model_dir} \\\n --max_seq_length=${MAX_SEQ_LENGTH} \\\n --eval_batch_size=8 \\\n --num_train_steps=3000 \\\n --learning_rate=3e-05 \\\n --train_batch_size=32 \\\n --num_warmup_steps=300\n" } ]
6
HotHunter/PYTHON-__-begin-to-learn
https://github.com/HotHunter/PYTHON-__-begin-to-learn
a0d16862bb4b55332cf54045a06167a34bbc5a34
8a44057ab847585a335626dd885ac62aa57c3dda
0f769649f2455f95aa43b7deb50e2f01ed6821d9
refs/heads/master
2020-03-08T08:24:14.960834
2018-04-24T03:36:31
2018-04-24T03:36:31
128,021,294
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.40441176295280457, "alphanum_fraction": 0.5661764740943909, "avg_line_length": 14.222222328186035, "blob_id": "66f84ac393d6bb4c3d43a146eb006b7c25cc4a1a", "content_id": "7276aea55eeb8500ee2fbaac8e166cb143a9852f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 136, "license_type": "no_license", "max_line_length": 35, "num_lines": 9, "path": "/Python2Test/d8-3.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 03 22:31:33 2015\n\n@author: Administrator\n\"\"\"\n\nx= [[1,2],1,1,[2,1,[1,2]]]\nprint x.count(1)" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.6523809432983398, "avg_line_length": 20.100000381469727, "blob_id": "f687c3710ac0290c38c2dd952723731e2e8ad9aa", "content_id": "e8dd5b964d047eee5c02b3aed84d1cb4a9fbcd7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 210, "license_type": "no_license", "max_line_length": 40, "num_lines": 10, "path": "/Python2Test/d8-31(1--(error).py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nfrom random import *\n\nnum = input('How many dice?')\nsides = input('How many sides per die?')\nsum = 0\nfor i in range(num):\n sum += randrange(sides) + 1\nprint 'The result is', sum" }, { "alpha_fraction": 0.5638265013694763, "alphanum_fraction": 0.5742848515510559, "avg_line_length": 20.785234451293945, "blob_id": "3490ed593d8c6eb42fb025508e0d483d6e5c08d6", "content_id": "fe83d12a88a6f432e25b0e1294f7e34f749ca644", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3257, "license_type": "no_license", "max_line_length": 83, "num_lines": 149, "path": "/Python2Test/MyAddressBook.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 15 14:16:15 2015\n\n@author: Administrator\n\"\"\"\n#通讯录\n\n#Filename:MyAddressBook.py\n\nimport cPickle as p\nimport os\n\n#Class Item\n\nclass Item:\n def __init__(self,name,age,gender):\n self.name = name\n self.age = age\n self.gender = gender\n \n#the main menu of address book\n \ndef menu():\n ''' the main menu of address book'''\n \n print ''\n print '1.Insert an item'\n print '2.Delete an item'\n print '3.Modify an item'\n print '4.Display all items'\n print '5.Sort all items'\n print '6.Exit the program'\n print 'Want do you want to do?'\n \n#initialization of system , load the member list\n \ndef begin():\n '''initialization of system , load the menber list'''\n \n global itemlist\n if os.path.exists('memberlist.data') == True: #to judge whether the file exists\n listfile = file('memberlist.data', 'r')\n if len(listfile.read())!=0:\n itemlist = p.load(listfile)\n listfile.close()\n \n#exitance of system, store the menber list\n \ndef end():\n '''exitance of system , store the menber list'''\n \n global itemlist\n listfile = file('memberlist.data','w+')\n p.dump(itemlist,listfile)\n listfile.close()\n \n#insert an item into the member list\n \ndef insert():\n '''inser an item into the member list'''\n \n name = raw_input('Enter name:')\n age = int(raw_input('Enter age:'))\n gender = raw_input('Enter gander:')\n item = Item(name , age , gender)\n global itemlist\n itemlist.append(item)\n \n#print an item\n \ndef output(item):\n '''print an item'''\n \n print '%-15s%-5d%s'%(item.name,item.age,item.gender)\n \n#print all items\n \ndef display():\n '''print all items'''\n \n global itemlist\n i = len(itemlist)\n print 'name age gender'\n for i in range(0,1):\n output(itemlist[i])\n print ''\n \n#delete an item by name from member list\n \ndef delete():\n '''delete an item by name from member list'''\n \n name = raw_input('Enter the name you want to delete')\n global itemlist\n i = len(itemlist)\n for i in range(0,1):\n if(itemlist[i].name == name):\n itemlist.pop(i)\n \n#update an item\n\ndef update(item):\n '''update an item'''\n item.name = raw_input('Enter name:')\n item.age = int(raw_input('Enter age:'))\n item.gander = raw_input('Enter gander:')\n \n \n#update an item's informain by name\n \ndef modify():\n '''update an item's informain by name'''\n \n name = raw_input('Enter the name you want to modify:')\n global itemlist\n i = len(itemlist)\n for i in range(0,1):\n if(itemlist[i].name == name):\n update(itemlist[i])\n print 'Update success!'\n \n#sort all items by name\n \ndef sort():\n global itemlist\n itemlist.sort(None , key = lambda item:item.name)\n \n#here are the scripts\n \nitemlist = [] #Notice here!!!!!\nbegin()\nwhile True:\n menu()\n sel = int(raw_input())\n if sel == 1:\n insert()\n elif sel == 2:\n delete()\n elif sel == 3:\n modify()\n elif sel == 4:\n display()\n elif sel == 5:\n sort()\n else:\n break\nend()\nprint 'Good Bye!'\n\n " }, { "alpha_fraction": 0.4375, "alphanum_fraction": 0.5192307829856873, "avg_line_length": 13.928571701049805, "blob_id": "aeeaf7c01c54e7bc7bd1579c4c553fcb61e67adc", "content_id": "44ceb998dad917eda0e1552a8d1fc5b03ceb7a66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 35, "num_lines": 14, "path": "/Python2Test/power.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 09 21:24:06 2015\n\n@author: Administrator\n\"\"\"\n\ndef power(x,n):\n if n == 1:\n return x\n else:\n return x * power(x,n-1)\n \nprint power(2,5)" }, { "alpha_fraction": 0.45348837971687317, "alphanum_fraction": 0.5232558250427246, "avg_line_length": 13.5, "blob_id": "d0220cc3809987c0c2e91be100f92151e5e43e97", "content_id": "836c42f786ae8821fea3bb393c5a62f52ebc9811", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 86, "license_type": "no_license", "max_line_length": 28, "num_lines": 6, "path": "/Python2Test/d8-19(4.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nn = 1\nfor i in range(9, 0, -1):\n n = (n+1)<<1\nprint n" }, { "alpha_fraction": 0.49180328845977783, "alphanum_fraction": 0.618852436542511, "avg_line_length": 19.41666603088379, "blob_id": "8f313a564b858ddfe7c5dae14c32fc1a38e9ce17", "content_id": "f83ba7ac645216f8109a4151eb3fdda101563110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 244, "license_type": "no_license", "max_line_length": 42, "num_lines": 12, "path": "/Python2Test/hello.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author: [YXL] <[email protected]>\n# @Date: 2015-08-16 20:47:25\n# @Last Modified by: [YXL] <[email protected]>\n# @Last Modified time: 2015-08-16 20:52:21\n\nfrom random import choice\n\nx = range(10)\n\nprint choice(x)" }, { "alpha_fraction": 0.46000000834465027, "alphanum_fraction": 0.5666666626930237, "avg_line_length": 18.60869598388672, "blob_id": "0405ca3db8138b46bbb901611dea9c845d6d4787", "content_id": "6c848906ea06c1ec3d784fabd5b0bb9ecbb2e5b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 450, "license_type": "no_license", "max_line_length": 64, "num_lines": 23, "path": "/Python2Test/d8-17(3.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nyear = int(raw_input('Enter year:'))\nmonth = int(raw_input('Enter month:'))\nday = int(raw_input('Enter day:'))\n\nmonths = (0,31,59,120,151,181,212,143,273,304,334)\n\nif 0 <= month <= 12:\n sum = months[month - 1]\nelse:\n print 'data error'\n\nsum += day\n\nleap = 0\n\nif (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):\n leap = 1\nif (leap == 1) and (month > 2):\n sum += 1\n\nprint 'it is the %dth day' %sum" }, { "alpha_fraction": 0.5474137663841248, "alphanum_fraction": 0.625, "avg_line_length": 15.642857551574707, "blob_id": "4cc865e27114e033feb5f7dca2ccc777394aed55", "content_id": "880c05810fca7075448bff83d3164a4ad8824b67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 53, "num_lines": 14, "path": "/Python2Test/fibs.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 07 22:23:22 2015\n\n@author: Administrator\n\"\"\"\n\nfibs = [0,1]\n\nnum = input('How may Fibonacci numbers do you want?')\n\nfor i in range(num-2):\n fibs.append(fibs[-2] + fibs[-1])\nprint fibs" }, { "alpha_fraction": 0.41871920228004456, "alphanum_fraction": 0.49753695726394653, "avg_line_length": 14.692307472229004, "blob_id": "c76b58ba0bfc562d13e3a813a2654f19fdf9572d", "content_id": "7dff8cd8ef8fdc802b4a706c0158910a5c32e1b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 32, "num_lines": 13, "path": "/Python2Test/d8-30(2.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "GB18030", "text": "__author__ = 'Administrator'\n\n#卧槽这个方法思路好牛逼,筛选法求质数\n\n\na = [0]*101\n\nfor i in range(2, 11):\n for j in range(i+i, 101, i):\n a[j] = -1\nfor i in range(2, 101):\n if a[i] != -1:\n print ' ', i," }, { "alpha_fraction": 0.5569105744361877, "alphanum_fraction": 0.6097561120986938, "avg_line_length": 18, "blob_id": "af8a334675cb1a658829bc0c599b904882164da6", "content_id": "01a4bc2954a8ec5029bf802f0e4fdb04f09a157a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 42, "num_lines": 13, "path": "/Python2Test/exception_3.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 10 22:52:42 2015\n\n@author: Administrator\n\"\"\"\n\ntry:\n x = input('enter the first number: ')\n y = input('enter the senond number: ')\n print x/y\nexcept:\n print \"Something wrong happened.....\"" }, { "alpha_fraction": 0.5162601470947266, "alphanum_fraction": 0.6097561120986938, "avg_line_length": 17.923076629638672, "blob_id": "f58d4fceaca5070578e94ce4f024b54f35da48a8", "content_id": "78f23e3e841253f2a35d9eb55268353f5004b64a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 44, "num_lines": 13, "path": "/Python2Test/test2.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 29 21:54:29 2015\n\n@author: Administrator\n\"\"\"\n\nyear = input(\"give me a year:\")\n\nif year%400==0 or year%4==0 and year%100<>0:\n print \"%s is runnian \" %year\nelse:\n print \"%s is not runnian\" %year " }, { "alpha_fraction": 0.7339955568313599, "alphanum_fraction": 0.7373068332672119, "avg_line_length": 22.842105865478516, "blob_id": "87626128c2f2cd9a650cfb4760e95c403357019c", "content_id": "0af2c13ae3f8057b6136ad9dc26348139e9d2ec1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "no_license", "max_line_length": 71, "num_lines": 38, "path": "/Python2Test/d9-7(8.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nfrom Tkinter import *\n\nroot = Tk()\n\ndef hello():\n print('fuck me!')\n\ndef about():\n w = Label(root, text=\"hahahhahah\\oooooooo\\fuck you\\my girl friend\")\n w.pack(side=TOP)\n\n\nmenubar = Menu(root)\n\nfilemenu = Menu(menubar,tearoff=0)\nfilemenu.add_command(label=\"Open\",command=hello)\nfilemenu.add_command(label=\"Save\",command=hello)\nfilemenu.add_separator()\nfilemenu.add_command(label=\"Exit\",command=root.quit)\nmenubar.add_cascade(label=\"File\", menu=filemenu)\n\neditmenu = Menu(menubar, tearoff=0)\neditmenu.add_command(label=\"Cut\", command=hello)\neditmenu.add_command(label=\"Copy\", command=hello)\neditmenu.add_command(label=\"Paste\", command=hello)\nmenubar.add_cascade(label=\"Edit\", menu=editmenu)\n\n\nhelpmenu = Menu(menubar, tearoff=0)\nhelpmenu.add_command(label=\"About\", command=about)\nmenubar.add_cascade(label=\"Help\", menu=helpmenu)\n\n\nroot.config(menu=menubar)\n\nmainloop()\n" }, { "alpha_fraction": 0.4051724076271057, "alphanum_fraction": 0.4612068831920624, "avg_line_length": 18.41666603088379, "blob_id": "ce0367ff7b98fcfc61d79de675065c4d9f5f30e6", "content_id": "c5919c8d733826cb00f1ef8adcb2f8bf928834d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 38, "num_lines": 12, "path": "/Python2Test/d8-30(1.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\ncount = 0\n\nfor i in range(1, 5):\n for j in range(1, 5):\n for k in range(1, 5):\n if i!=j and i!=k and j!=k:\n print i*100+j*10+k\n count += 1\n\nprint count" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.5680473446846008, "avg_line_length": 24.399999618530273, "blob_id": "4b3c3be8ddda247f1d639bc74c1be94119a85fe1", "content_id": "56275f183243b00cc8793937bdc1fade0a226e42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 507, "license_type": "no_license", "max_line_length": 44, "num_lines": 20, "path": "/Python2Test/def_lookup.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 09 16:43:05 2015\n\n@author: Administrator\n\"\"\"\ndef lookup(data, label , name):\n return data[label].get(name)\n\n\ndef store(data , full_name):\n names = full_name.split();\n if len(names) == 2 : names.insert(1, '')\n labels = 'first' , 'middle' , 'last'\n for label , name in zip(labels , names):\n people = lookup(data, label , name)\n if people:\n people.append(full_name)\n else:\n data[label][name] = [full_name]" }, { "alpha_fraction": 0.5031847357749939, "alphanum_fraction": 0.6709129214286804, "avg_line_length": 15.275861740112305, "blob_id": "6027923f9373dced0c02f18db6bd0d101017280b", "content_id": "97585a1310c4c550cd6d808fc40a759ac52f9605", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license_type": "no_license", "max_line_length": 64, "num_lines": 29, "path": "/Python2Test/SMath.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 29 22:10:28 2015\n\n@author: Administrator\n\"\"\"\n\n\"\"\"利用python作为科学计算器。熟悉Python中的常用运算符,并分别求出表达\n式12*34+78-132/6、(12*(34+78)-132)/6、(86/40)**5的值。并利用math模块进行数学计算,\n分别求出145/23的余数,0.5的sin和cos值\n(注意sin和cos中参数是弧度制表示)提醒:可通过import math; help(\"math\")查看math帮助.\"\"\"\n\nimport math\n\nx = 12*34+78-132/6\ny = (12*(34+78)-132)/6\nz = (86/40)**5\n\nprint x\nprint y\nprint z\n\na = math.fmod(145,23)\nb = math.sin(0.5)\nc = math.cos(0.5)\n\nprint a\nprint b\nprint c" }, { "alpha_fraction": 0.5565217137336731, "alphanum_fraction": 0.5693581700325012, "avg_line_length": 28.439023971557617, "blob_id": "dd062b60fb43ee78e8f14f08a40436b44cb812bc", "content_id": "fc25bb957b2f254b48df0d929aca4591f651ab93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2415, "license_type": "no_license", "max_line_length": 83, "num_lines": 82, "path": "/Python2Test/wxpy_text1.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nfrom os import *\nfrom sys import *\nfrom wx import *\nID_OPEN = 101\nID_EXIT = 110\nID_SAVE = 111\nID_BUTTON = 112\n\nclass MainWindow(wx.Frame):\n \"\"\" We simply derive a new class of Frame. \"\"\"\n def __init__(self, parent, id, title):\n wx.Frame.__init__(self, parent, id, title, size=(500,100))\n self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)\n self.CreateStatusBar()\n filemenu = wx.Menu()\n filemenu.Append(ID_OPEN, \"open_file\", \"open file\")\n filemenu.AppendSeparator()\n filemenu.Append(ID_SAVE, \"save_file\", \"save file\")\n filemenu.AppendSeparator()\n filemenu.Append(ID_EXIT, \"exit\", \"exit\")\n menuBar = wx.MenuBar()\n menuBar.Append(filemenu, \"files\")\n self.SetMenuBar(menuBar)\n wx.EVT_MENU(self, ID_OPEN, self.open)\n wx.EVT_MENU(self, ID_SAVE, self.save)\n wx.EVT_MENU(self, ID_EXIT, self.exit)\n self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)\n self.buttons = []\n\n for i in range(0,6):\n self.buttons.append(wx.Button(self,ID_BUTTON+i,\"Button &\"+'i'))\n self.sizer2.Add(self.buttons[i],1,wx.EXPAND)\n\n self.sizer = wx.BoxSizer(wx.VERTICAL)\n self.sezer.Add(self.control, 1, wx.EXPAND)\n self.sizer.Add(self.sizer2, 0, wx.EXPAND)\n self.SetSizer(self.sizer)\n self.SetAutoLayout(1)\n self.sizer.Fit(self)\n\n self.Show(True)\n\n def exit(self):\n self.Close(True)\n\n def open(self):\n\n self.dirname = ''\n dlg = wx.FileDialog(self, \"chose a file\", self.dirname, \"\", \"*.*\", wx.OPEN)\n\n if dlg.ShowModal() == wx.ID_OK:\n self.filename = dlg.GetFilename()\n self.dirname = dlg.GetDirectory()\n f = open(os.path.join(self.dirname, self.filename), 'r')\n self.control.SetValue(f.read())\n f.close()\n dlg.Destroy()\n\n def save(self):\n\n try:\n f = open(os.path.join(self.dirname, self.filename), 'w')\n\n except AttributeError:\n print 'file is not exist'\n sys.exit(0)\n\n content = self.control.GetValue()\n try:\n f.write(content)\n\n except UnboundLocalError:\n print 'file is not exist'\n sys.exit(0)\n finally:\n f.close()\n\napp = wx.PySimpleApp()\nframe = MainWindow(None, -1, 'Small editor')\napp.MainLoop()\n\n" }, { "alpha_fraction": 0.4853556454181671, "alphanum_fraction": 0.5146443247795105, "avg_line_length": 17.461538314819336, "blob_id": "ec8de333080d39223518187baa4f95d069ba326f", "content_id": "0d37477039ed21022f3980fc4d96fbb77554d2d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 54, "num_lines": 13, "path": "/Python2Test/d8-24(6.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\ndef fun(i, cut):\n if i == 0:\n print 'There are %d digit in the number' % cut\n return\n print i % 10,\n i /= 10\n cut += 1\n fun(i, cut)\n\ni = int(raw_input('Enter a number:'))\nfun(i, 0)" }, { "alpha_fraction": 0.4463667869567871, "alphanum_fraction": 0.4913494884967804, "avg_line_length": 15.11111068725586, "blob_id": "ed17f29e704ec4d60b190e0aa4c564a08c9e6877", "content_id": "17b793b2f3e9feb9084394ccef9d067bea9f003f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 289, "license_type": "no_license", "max_line_length": 37, "num_lines": 18, "path": "/Python2Test/d9-6(1.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nl = [0, 10, 20, 30, 40, 50]\n\ncnt = len(l)\n\nn = int(raw_input('print a number:'))\n\nl.append(n)\n\nfor i in range(cnt):\n if n<l[i]:\n for j in range(cnt, i, -1):\n l[j] = l[j-1]\n l[i] = n\n break\n\nprint 'The new sorted list is:', l" }, { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.6018518805503845, "avg_line_length": 19.3125, "blob_id": "888aa2460cb1da3b3aeaccd0c0f20c2fee0a62af", "content_id": "dd5cbc1f0668c3679802ee07d48f44666d43f66e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 324, "license_type": "no_license", "max_line_length": 56, "num_lines": 16, "path": "/Python2Test/for 1.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 07 21:33:39 2015\n\n@author: Administrator\n\"\"\"\n\ngirls = ['alice' , 'bernice' , 'clarice']\nboys = ['chris' , 'arnold' , 'bob']\n\nletterGirls = {}\n\nfor girl in girls:\n letterGirls.setdefault(girl[0] , []).append(girl)\n \nprint [b+'+'+g for b in boys for g in letterGirls[b[0]]]" }, { "alpha_fraction": 0.4912280738353729, "alphanum_fraction": 0.5614035129547119, "avg_line_length": 19.727272033691406, "blob_id": "8cc77a48048637d71a7adea207bc40f0d3b0fe01", "content_id": "7dad333761b66589bebf19dbc4f079ad8520c1be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 228, "license_type": "no_license", "max_line_length": 117, "num_lines": 11, "path": "/Python2Test/d8-17.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nimport math\n\nnum = 1\n\nwhile True:\n if math.sqrt(num+100) - int(math.sqrt(num + 100)) == 0 and math.sqrt(num + 268) - int(math.sqrt(num + 268)) == 0:\n print(num)\n break\n num += 1\n" }, { "alpha_fraction": 0.6964285969734192, "alphanum_fraction": 0.6964285969734192, "avg_line_length": 16.5625, "blob_id": "5819d2424fb031a302dedafe66afbe1e8df8fa4a", "content_id": "f52a2b79545f03a37223a39cc79d40e6b452e007", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "no_license", "max_line_length": 51, "num_lines": 16, "path": "/Python2Test/d9-7(7.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nfrom Tkinter import *\n\nroot = Tk()\n\ndef hello():\n print('i love you wanglianhui!!!')\n\nmenubar = Menu(root)\nmenubar.add_command(label=\"Fuck!\", command=hello)\nmenubar.add_command(label=\"ME!\", command=root.quit)\n\nroot.config(menu=menubar)\n\nmainloop()" }, { "alpha_fraction": 0.6071428656578064, "alphanum_fraction": 0.6071428656578064, "avg_line_length": 27.05555534362793, "blob_id": "f6d87b29305748ba880b2fdb63961f916951f42a", "content_id": "3f7371936b8b79c0e7f6ece6e5934a839ebdb570", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "no_license", "max_line_length": 86, "num_lines": 18, "path": "/Python2Test/d9-7(6.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nfrom Tkinter import *\nclass App:\n def __init__(self, master):\n frame = Frame(master)\n frame.pack()\n self.button = Button(frame, text=\"QUIT\", fg = 'red', command=frame.quit)\n self.button.pack(side=LEFT)\n self.hi_there = Button(frame, text=\"who are your lover?\", command=self.say_hi)\n self.hi_there.pack(side=LEFT)\n\n def say_hi(self):\n print \"must you my lady,nice to meet you~~\"\n\nwin = Tk()\napp = App(win)\nwin.mainloop()" }, { "alpha_fraction": 0.4656716287136078, "alphanum_fraction": 0.5343283414840698, "avg_line_length": 16.63157844543457, "blob_id": "0145f7dd4a0d14ccd815d981f64836fe2cc0cdae", "content_id": "cd8d2f18e6c4f10b3ef12c8435bacaf30241f952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 43, "num_lines": 19, "path": "/Python2Test/0-100sqrt.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 29 22:33:14 2015\n\n@author: Administrator\n\"\"\"\n\nfrom math import sqrt\n\nresult1 = []\nfor num in range(2, 100):\n f = True\n for snu in range(2, int(sqrt(num))+1):\n if num % snu == 0:\n f = False\n break\n if f:\n result1.append(num)\nprint result1\n" }, { "alpha_fraction": 0.4586288332939148, "alphanum_fraction": 0.47044917941093445, "avg_line_length": 21.3157901763916, "blob_id": "927b8fc41064565302d289d9877c2f0baab4fd46", "content_id": "11c6b30c8712d041fad2aac64392d005bee3a6ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 423, "license_type": "no_license", "max_line_length": 60, "num_lines": 19, "path": "/Python2Test/d8-19(2.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\ndef main():\n basis = int(raw_input('Input the basis number:'))\n n = int(raw_input('Input the logest length of number:'))\n b = basis\n sum = 0\n for i in range(0, n):\n if i == n-1:\n print \"%d\" % basis,\n else:\n print \"%d +\" % basis,\n\n sum += basis\n basis = basis*10 + b\n print '= %d' % sum,\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.311345636844635, "alphanum_fraction": 0.3245382606983185, "avg_line_length": 19, "blob_id": "aba9ebe497f06d0e5834d164f94ccf3e6fdb6ca1", "content_id": "4c23adb84095277811d7fffba5d40f48428adfa9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "no_license", "max_line_length": 41, "num_lines": 19, "path": "/Python2Test/d8-18fenjie.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\n\ndef main():\n n = int(raw_input('Enter a number:'))\n print n, '=',\n\n while(n != 1):\n for i in range(2, n+1):\n if(n % i) == 0:\n n /= i\n if(n == 1):\n print i,\n else:\n print i, '*',\n break\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.4436090290546417, "alphanum_fraction": 0.518796980381012, "avg_line_length": 11.181818008422852, "blob_id": "faf709959dde658906d75e6307500e13d136abb1", "content_id": "39558f9f078ba5a85dba22cb9aa67530c611d873", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 133, "license_type": "no_license", "max_line_length": 28, "num_lines": 11, "path": "/Python2Test/d8-19(3.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\ns = 100\nh = 50.0\n\nfor i in range(2,11):\n s += h\n h /= 2\n\nprint 'length:%f' % s\nprint 'last:%f' %h" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6899224519729614, "avg_line_length": 16.266666412353516, "blob_id": "aae287c05ed0963dc8b633e2f763c1475a788d7f", "content_id": "9569089b342c1071c8ac47922e7daa7a0ec31f2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "no_license", "max_line_length": 55, "num_lines": 15, "path": "/Python2Test/d9-7(5.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nfrom Tkinter import *\ndef hello():\n print('hello world')\n\nwin = Tk()\nwin.title('hellomotherfucker')\nwin.geometry('400x200')\n\nbtn = Button(win, text='Click my dick!', command=hello)\n\nbtn.pack(expand=YES, fill=BOTH)\n\nmainloop()" }, { "alpha_fraction": 0.4749999940395355, "alphanum_fraction": 0.49038460850715637, "avg_line_length": 20.70833396911621, "blob_id": "9399562fa53841419b805b4dcd059e5560407666", "content_id": "987e91cd32bc5164e1b4c84b08eba595772bacf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 520, "license_type": "no_license", "max_line_length": 124, "num_lines": 24, "path": "/Python2Test/d8-19.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\n#import string\n\ndef main():\n s = raw_input('Input a string:')\n letter = 0\n space = 0\n digit = 0\n other = 0\n for c in s:\n if c.isalpha():\n letter += 1\n elif c.isspace():\n space += 1\n elif c.isdigit():\n digit += 1\n else:\n other += 1\n\n print 'There are %d letters,%d spaces, %d digits and %d other characters in your string.' %(letter, space, digit, other)\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.660516619682312, "alphanum_fraction": 0.678966760635376, "avg_line_length": 23.727272033691406, "blob_id": "d0282b6306ce1fe7ce4279b4b615b6d8b4bff327", "content_id": "80ee23bd5be6c44a2ae5f32672bd5680dd93f15b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 59, "num_lines": 11, "path": "/Python2Test/d8-31(2.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nfrom pprint import pprint\nfrom random import shuffle\n\nvalues = range(1, 11) + 'Jack Queen King'.split()\nsults = 'diamonds clubs hearts spades'.split()\ndeck = ['%s of %s' % (v, s) for v in values for s in sults]\n\nshuffle(deck)\npprint(deck[:54])" }, { "alpha_fraction": 0.39516130089759827, "alphanum_fraction": 0.4677419364452362, "avg_line_length": 9.416666984558105, "blob_id": "f30b6220abedf844f86d50f595d82e0db0412de9", "content_id": "84031175a6682a1af635feba0a1783ff18887e55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 124, "license_type": "no_license", "max_line_length": 28, "num_lines": 12, "path": "/Python2Test/d8-24(1.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\na = 2.0\nb = 1.0\ns = 0.0\n\nfor i in range(0, 50):\n s = s+a/b\n a = a+b\n b = a-b\n\nprint s" }, { "alpha_fraction": 0.5607843399047852, "alphanum_fraction": 0.6117647290229797, "avg_line_length": 17.285715103149414, "blob_id": "7487998c757ac9e0ada462a44e2e17a4db921bd0", "content_id": "8b2a99aa2ab11d2cf32f825c7808c8cd57d2967f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 255, "license_type": "no_license", "max_line_length": 42, "num_lines": 14, "path": "/Python2Test/exception_2.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 10 22:49:25 2015\n\n@author: Administrator\n\"\"\"\n\ntry:\n x = input('enter the first number: ')\n y = input('enter the senond number: ')\n print x/y\n \nexcept (ZeroDivisionError, TypeError), e:\n print e" }, { "alpha_fraction": 0.469696968793869, "alphanum_fraction": 0.4962121248245239, "avg_line_length": 19.30769157409668, "blob_id": "34f00b6ff41cad8998eb44930ed5ca3a8e3cbf8f", "content_id": "3bcc5f039b6f21a8d83200d66b880d75227b1489", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 264, "license_type": "no_license", "max_line_length": 42, "num_lines": 13, "path": "/tasksBy PY3/task1-p19.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "arr = [0 for x in range(0, 3)]\nrst = []\n\nfor a in arr:\n arr[a] = input(\"input a int number :\")\n if int(arr[a]) % 2 == 1:\n rst.append(arr[a])\n # print(arr[a])\nif len(rst) > 0 :\n rst.sort()\n print(rst[-1]) \nelse:\n print('no odd number') " }, { "alpha_fraction": 0.3819444477558136, "alphanum_fraction": 0.4652777910232544, "avg_line_length": 23.16666603088379, "blob_id": "44f2fa9534fd14536f5d566f048e16cc65be4a1c", "content_id": "6ccac9731d6d73eddf11a4d49b4c801835591aca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 144, "license_type": "no_license", "max_line_length": 31, "num_lines": 6, "path": "/Python2Test/d8-19(6.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nfor i in range(1, 8, 2):\n print ' '*(4-(i+1)/2)+'*'*i\nfor i in range(5, 0, -2):\n print ' '*(4-(i+1)/2)+'*'*i" }, { "alpha_fraction": 0.43388429284095764, "alphanum_fraction": 0.45041322708129883, "avg_line_length": 21.090909957885742, "blob_id": "e1e9818a06de9357b89f69a9d26f8834a20e24e9", "content_id": "9629de45183948852789e5135d4cb4d502613946", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "no_license", "max_line_length": 47, "num_lines": 11, "path": "/Python2Test/d9-7(2.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\n\nMAXONE = lambda x,y : (x > y) * x + (x < y) * y\nMINONE = lambda x,y : (x > y) * y + (x < y) * x\n\nif __name__ == '__main__':\n a = 10\n b = 20\n print \"max:%d\" % MAXONE(a,b)\n print \"min:%d\" % MINONE(a,b)" }, { "alpha_fraction": 0.32098764181137085, "alphanum_fraction": 0.4038800597190857, "avg_line_length": 18.586206436157227, "blob_id": "dfecc59c544312717295d9f8ff8715baf4b3143e", "content_id": "4d423b3474b99200095852e44d115e76a441bb96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 597, "license_type": "no_license", "max_line_length": 51, "num_lines": 29, "path": "/Python2Test/d8-17(2.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n# -*- coding: utf-8 -*-\n\ny = input('Enter the year:')\nm = input('Enter the month:')\nd = input('Enter the day:')\n\nsum = 0\nend = 0\n\nfor i in range(1,m+1):\n if y % 400 == 0 or y % 4 == 0 and y % 100 != 0:\n if i == (1, 3, 5, 7, 8, 10, 12):\n sum += 31\n elif i == 2:\n sum += 29\n else:\n sum += 30\n else:\n if i == (1, 3, 5, 7, 8, 10, 12):\n sum += 31\n elif i == 2:\n sum += 28\n else:\n sum += 30\nend = sum+d\nprint end\n\n#草泥马的我就是个弱智啊!!!!" }, { "alpha_fraction": 0.44711539149284363, "alphanum_fraction": 0.4663461446762085, "avg_line_length": 12.933333396911621, "blob_id": "252d536ff6a405cafc67d547c559b21b8a645e83", "content_id": "89f67f1af835e0876123fbd160ee0c73507fbebf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 40, "num_lines": 15, "path": "/Python2Test/d8-18grade.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\ndef main():\n s = int(raw_input('Enter a grade:'))\n\n if s>=90:\n grade = 'A'\n elif s>=60:\n grade = 'B'\n else:\n grade = 'C'\n print grade\n\n\nmain()" }, { "alpha_fraction": 0.5750916004180908, "alphanum_fraction": 0.622710645198822, "avg_line_length": 18.571428298950195, "blob_id": "fc6e5a0cb457effaebedc8909a5c998bbfbd458c", "content_id": "a7830cbf635100e7df0a896996b8c5bbaeb8188a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 273, "license_type": "no_license", "max_line_length": 45, "num_lines": 14, "path": "/Python2Test/exception_1.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 10 22:03:29 2015\n\n@author: Administrator\n\"\"\"\n\ntry:\n x = input('enter the first number: ')\n y = input('enter the senond number: ')\n print x/y\n \nexcept ZeroDivisionError:\n print \"The second number can't be zero!!\"" }, { "alpha_fraction": 0.47212544083595276, "alphanum_fraction": 0.5104529857635498, "avg_line_length": 26.380952835083008, "blob_id": "71f9be66640aded8033563bd7a397de8be59de97", "content_id": "f344a9150a24bfbef7079ef17d3d766cb236f6bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 574, "license_type": "no_license", "max_line_length": 65, "num_lines": 21, "path": "/Python2Test/box_sentence.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 03 22:19:38 2015\n\n@author: Administrator\n\"\"\"\n\nsentence = raw_input(\"sentence:\")\n\nscreen_width = 80\ntext_width = len(sentence)\nbox_width = text_width + 6\nleft_margin = (screen_width - box_width) // 2\n\nprint\nprint ' ' *left_margin + '+' + '-' *(box_width - 2) + '+'\nprint ' ' *(left_margin + 1) + '| ' + ' ' * text_width + ' |'\nprint ' ' *(left_margin + 1) + '| ' + sentence + ' |'\nprint ' ' *(left_margin + 1) + '| ' + ' ' * text_width + ' |'\nprint ' ' *left_margin + '+' + '-' *(box_width - 2) + '+'\nprint" }, { "alpha_fraction": 0.4525993764400482, "alphanum_fraction": 0.4709480106830597, "avg_line_length": 14.571428298950195, "blob_id": "9b886844413c311dc7a9bda80e0ff16d613e0c31", "content_id": "d497ac9df250937f2583b4cfe22fbc61617e26ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "no_license", "max_line_length": 34, "num_lines": 21, "path": "/Python2Test/d8-24(4.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\ndef fun(n, s):\n if s == 0:\n return\n print n[s-1]\n fun(n, s-1)\n\nn = raw_input('Input a string:')\ns = len(n)\nfun(n, s)\n\n# def output(s, l):\n# if l == 0:\n# return\n# print s[l-1]\n# output(s, l-1)\n#\n# s = raw_input('Input a string:')\n# l = len(s)\n# output(s, l)\n" }, { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 20, "blob_id": "2520249774b6dc606e62f46a0c43f42c4ba4c1ca", "content_id": "e1292bf77b2b45146f3c47dba9bdd58524e34aec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 58, "license_type": "no_license", "max_line_length": 26, "num_lines": 2, "path": "/README.md", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# PYTHON-__-begin-to-learn\n这才是我的python学习库\n" }, { "alpha_fraction": 0.5652173757553101, "alphanum_fraction": 0.5797101259231567, "avg_line_length": 33.5, "blob_id": "bbf13d6bc6b93431442ef7acafccee28ebc10a9c", "content_id": "938e2474fbc97f68c5f1d673b1c6e23e2e7bfdb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 69, "license_type": "no_license", "max_line_length": 44, "num_lines": 2, "path": "/Python2Test/dddddddd.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'KISS_MY_ASS_YOU_MOTHER_FUCKER'\n# -*- coding: utf-8 -*-\n" }, { "alpha_fraction": 0.42335766553878784, "alphanum_fraction": 0.510948896408081, "avg_line_length": 12.800000190734863, "blob_id": "0b2155723cb831803c6e67bb4063aea23356035f", "content_id": "dee3fd162dea102d53e15fe202307c4be2155408", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 137, "license_type": "no_license", "max_line_length": 35, "num_lines": 10, "path": "/Python2Test/d9-7(1--error_but_run.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\na = [1,2,3,4,5,6,7,8,9]\nl = len(a)\nprint a\n\nfor i in range(5):\n a[i], a[l-i-1] = a[l-i-1], a[i]\n\nprint a" }, { "alpha_fraction": 0.43146416544914246, "alphanum_fraction": 0.4813084006309509, "avg_line_length": 15.921052932739258, "blob_id": "a704439d821195b8339e88bd04e16ce9b54b1acd", "content_id": "e1e10dc27f73b2f0a1eb8ef03873f712e7f50bf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 642, "license_type": "no_license", "max_line_length": 53, "num_lines": 38, "path": "/Python2Test/addrbook.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 07 21:05:07 2015\n\n@author: Administrator\n\"\"\"\n\npeople = {\n 'Alice':{\n 'phone':2344234,\n 'addr':'hahah'\n },\n \n 'Beth':{\n 'phone':979789,\n 'addr':'okokok'\n },\n \n 'Jay':{\n 'phone':687876,\n 'addr':'bybyby'\n }\n}\n\nlabels = {\n 'phone' : 'phone number',\n 'addr' : 'address'\n }\n \nname = raw_input('Name:')\n\nrequest = raw_input('phone number(p) or address(a)?')\n\nif request == 'p' : key = 'phone'\nif request == 'a' : key = 'addr'\n\nif name in people : print \"%s's %s is %s .\" %\\\n (name, labels[key], people[name][key])" }, { "alpha_fraction": 0.40186914801597595, "alphanum_fraction": 0.4579439163208008, "avg_line_length": 9.800000190734863, "blob_id": "84f15ef74c6439360d3c7015d175a93a0e1082ec", "content_id": "4e451d4548562d1f4e0b9a582778d173b61c8b8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 107, "license_type": "no_license", "max_line_length": 28, "num_lines": 10, "path": "/Python2Test/d8-18_rabbit.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\na = 1\nb = 1\n\nfor i in range(1, 21, 2):\n print a, b,\n\n a += b\n b += a" }, { "alpha_fraction": 0.4063745141029358, "alphanum_fraction": 0.45816734433174133, "avg_line_length": 18.384614944458008, "blob_id": "c315e6b6f01d01cd56ede9d2ee6ef70db39df579", "content_id": "991b4caea73c8ac5e20dadc39a5579a497abfcc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "no_license", "max_line_length": 38, "num_lines": 13, "path": "/Python2Test/threeWords.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\n\ncnt = 0 #count the sum of result\n\nfor i in range(1,5):\n for j in range(1,5):\n for k in range(1,5):\n if i != j and j != k :\n print i*100 + j*10 + k\n cnt += 1\n\nprint cnt" }, { "alpha_fraction": 0.6192358136177063, "alphanum_fraction": 0.6403161883354187, "avg_line_length": 18, "blob_id": "3afd37e0db296fe9cb70f2a0bebf9b0cb4ffe6e2", "content_id": "05b1b5efcc1a6e6f12e6fbcd928333649f7093ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 825, "license_type": "no_license", "max_line_length": 61, "num_lines": 40, "path": "/Python2Test/SPAMFilter.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 10 21:46:52 2015\n\n@author: Administrator\n\"\"\"\n#屏蔽某些字符的类 Filter(超类) ****Filter(子类)\nclass Filter:\n def init(self):\n self.blocked = []\n \n def filter(self, sequence):\n return [x for x in sequence if x not in self.blocked]\n \nclass SPAMFilter(Filter):\n def init(self):\n self.blocked = ['SPAM']\n \nf = Filter()\nf.init()\nprint f.filter([1,2,3])\n\n\ns = SPAMFilter()\ns.init()\nprint s.filter(['SPAM', 'SPAM', 'hello'])\n\n#检查继承\nprint issubclass(SPAMFilter , Filter)\nprint issubclass(Filter , SPAMFilter)\n\n#基类\nprint SPAMFilter.__bases__\nprint Filter.__bases__\n\n#检查一个方法是否是一个类的实例\ns = SPAMFilter()\nprint isinstance(s, SPAMFilter)\nprint isinstance(s, Filter)\nprint isinstance(s, str)" }, { "alpha_fraction": 0.5273972749710083, "alphanum_fraction": 0.6369863152503967, "avg_line_length": 11.25, "blob_id": "e2cc10ba8c4011d2f715d25fe1192617ec6e07ec", "content_id": "5691c433aecb058e14f24a5ae78ae02a51baaa02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 146, "license_type": "no_license", "max_line_length": 35, "num_lines": 12, "path": "/Python2Test/random.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 10 18:39:50 2015\n\n@author: Administrator\n\"\"\"\n\nfrom random import *\n\nx = range(100)\n\nprint choice(x)" }, { "alpha_fraction": 0.48253968358039856, "alphanum_fraction": 0.5047619342803955, "avg_line_length": 15.578947067260742, "blob_id": "946eac73b6d234e523b03f9c179c948c2352402c", "content_id": "a02f18fba97654293bd2b457a4c6092aedc387ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 315, "license_type": "no_license", "max_line_length": 47, "num_lines": 19, "path": "/Python2Test/d8-30(3.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\n#from math import *\n\nprint 'input ten numbers please:'\n\nl = []\n\nfor i in range(0,10):\n l.append(int(raw_input('Input a number:')))\n\nfor i in range(9):\n for j in range(i+1,10):\n if l[j]<l[i]:\n temp = l[j]\n l[j] = l[i]\n l[i] = temp\n\nprint l\n" }, { "alpha_fraction": 0.44843047857284546, "alphanum_fraction": 0.5246636867523193, "avg_line_length": 13.933333396911621, "blob_id": "7cc0f105bde5883c353fe1b84157aea4d30913c3", "content_id": "372bc17d94ccfe640aa05fe979c66870a60e5c8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "no_license", "max_line_length": 35, "num_lines": 15, "path": "/Python2Test/factorial.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 09 21:15:52 2015\n\n@author: Administrator\n\"\"\"\n\ndef factorial(n):\n if n == 1:\n return 1\n else:\n return n * factorial(n-1)\n \n \nprint factorial(4)" }, { "alpha_fraction": 0.4183673560619354, "alphanum_fraction": 0.5034013390541077, "avg_line_length": 18.66666603088379, "blob_id": "d311b55a9a999255e41b84f233b396a823bd1723", "content_id": "6cbf84e678373c2472b287c8c7236cc784508ea8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 50, "num_lines": 15, "path": "/Python2Test/d8-25(7.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\nans = ['Yes', 'No']\n\ni = int(raw_input('Input a number(10000~99999):'))\nif i<10000 or i>99999:\n print 'Input Error'\nelse:\n i = str(i)\n flag = 0\n for j in range(0, 2):\n if i[j] != i[4-j]:\n flag = 1\n break\n print ans[flag]" }, { "alpha_fraction": 0.4488188922405243, "alphanum_fraction": 0.4960629940032959, "avg_line_length": 11.800000190734863, "blob_id": "9bd5aebafc04bec0514d9c623e2d67364f61fe65", "content_id": "7286dc582940fa96008245ae9787ffd7e6e8bb76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 127, "license_type": "no_license", "max_line_length": 28, "num_lines": 10, "path": "/Python2Test/d8-24(5.py", "repo_name": "HotHunter/PYTHON-__-begin-to-learn", "src_encoding": "UTF-8", "text": "__author__ = 'Administrator'\n\n\ndef fun(n):\n if n == 1:\n return 10\n else:\n return fun(n-1) + 2\n\nprint fun(5)" } ]
51
Seeker1911/MathMagician
https://github.com/Seeker1911/MathMagician
b60fae9b7adb51d78704f547fe3f2055494dbb3b
7bf6539169392020698a461e3d384ef452307b7d
3e8695c1943913e76c239658bd4d9d7d5265bdca
refs/heads/master
2021-01-20T22:09:59.050366
2016-07-26T19:44:28
2016-07-26T19:44:28
64,165,251
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5172004699707031, "alphanum_fraction": 0.5320284962654114, "avg_line_length": 22.41666603088379, "blob_id": "0e5ede5dd498de1effaf82ab5e073b9626aad529", "content_id": "8cb899315d30a5ccbe6ec89fc4cb10e8924189ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1686, "license_type": "no_license", "max_line_length": 56, "num_lines": 72, "path": "/mathmagician.py", "repo_name": "Seeker1911/MathMagician", "src_encoding": "UTF-8", "text": "import time\n\nclass Mathmagician:\n\n def __init__(self):\n self.number = 0\n\n def menu(self):\n\n print(\"1. integer\")\n print(\"2. prime\")\n print(\"3. fibonacci\")\n print(\"4. quit\")\n choice = input(\"Type 1,2,3, or 4 here...> \")\n\n\n if choice == \"1\":\n number_to_output = input(\"How many numbers? \")\n self.print_integers(number_to_output)\n\n\n if choice == \"2\":\n number_to_output = input(\"How many numbers? \")\n self.print_prime(number_to_output)\n\n if choice == \"3\":\n number_to_output = input(\"How many numbers? \")\n self.print_fibonacci(number_to_output)\n\n if choice != \"4\":\n self.menu()\n\n\n def print_integers(self, number_to_output):\n numberList = []\n for num in range(1, int(number_to_output) + 1):\n numberList.append(num)\n\n self.slow_printer(numberList)\n return numberList\n\n def print_prime(self, number_to_output):\n primeList = []\n for num in range(2, int(number_to_output) + 1):\n if num % 2 == 1:\n primeList.append(num)\n\n self.slow_printer(primeList)\n return primeList\n\n def print_fibonacci(self, number_to_output):\n fibonacciList = []\n fib, n = 0, 1\n for num in range(1, int(number_to_output) + 1):\n fib, n = n, fib + n \n fibonacciList.append(fib)\n\n\n self.slow_printer(fibonacciList)\n return fibonacciList\n\n def slow_printer(self, printList):\n for i in printList:\n print(i)\n time.sleep(0.5)\n\n\n\n\nif __name__ == '__main__':\n math = Mathmagician()\n math.menu()\n" }, { "alpha_fraction": 0.594059407711029, "alphanum_fraction": 0.6251767873764038, "avg_line_length": 24.25, "blob_id": "24cc4610104b056ebdac90e088276a13787bb3f6", "content_id": "657e06e6b3b945f55b43a30640c3450008d19555", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 707, "license_type": "no_license", "max_line_length": 61, "num_lines": 28, "path": "/test_mathmagician.py", "repo_name": "Seeker1911/MathMagician", "src_encoding": "UTF-8", "text": "import unittest\nfrom mathmagician import *\n# Test integer\n# Test prime\n# Test fibonacci\n# Test argument determines number of output\n# Test verify output of each method\nclass test_math(unittest.TestCase):\n \"\"\" Test math.\n \"\"\"\n def test_print_integers(self):\n math = Mathmagician()\n self.assertEqual([1,2,3,4,5], math.print_integers(5))\n\n def test_print_prime(self):\n math = Mathmagician()\n prime = math.print_prime(9)\n self.assertEqual([3,5,7,9], prime)\n\n def test_print_fibonacci(self):\n math = Mathmagician()\n fib = math.print_fibonacci(8)\n self.assertEqual([1,1,2,3,5,8,13,21], fib)\n\n\n\nif __name__ == '__main__': \n unittest.main()\n" }, { "alpha_fraction": 0.7379491925239563, "alphanum_fraction": 0.7445223331451416, "avg_line_length": 43.74509811401367, "blob_id": "d3db8a2e21a1d60bd6cb6d6f6cd5c1e67528f6df", "content_id": "2ce59b9b98a037cde5bac6cdd46020aaa30ce0c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2290, "license_type": "no_license", "max_line_length": 301, "num_lines": 51, "path": "/README.md", "repo_name": "Seeker1911/MathMagician", "src_encoding": "UTF-8", "text": "# MathMagician\n\n## Setup\n\n```\nmkdir -p ~/workspace/python/exercises/cli && cd $_\ntouch mathmagician.py\n```\n\n## Instructions\n\n### Step 1\n\nWrite your unit tests to reflect what classes, methods, and I/O is expected for each feature.\n\n### Step 2\n\nYour program will have one class with a **minimum** of three methods on it:\nEach method should also accept an argument that determines how many times the function should output a number.\n\n1. `print_integers(self, number_to_output)`\n2. `print_fibonacci(self, number_to_output)`\n3. `print_primes(self, number_to_output)`\n\nWrite unit tests that will verify the output of each method. Do not write any implementation code until you have a unit test for each method that fails.\n\n### Step 3\nBuild menu, make last option '4. Quit Program'\nWrite basic code to terminate the program on key press, displays prompt to user, and listens for a key press.\nCreate a simple implementation of a console application that displays a prompt to the user, and listens for a key press.\n\n1. Use `print()` to output the message `Press any key to exit`.\n1. Use `input` to accept user input, so that when your program runs, you press a key and it exits.\n\n### Step 4\n\nNow you'll write the implementation code for your three methods, and the operation of the program itself.\n\n1. You want it to do one of three mathematical operations. Update your prompt to be *I am the Math Magician. What would you like me to do?* The options will be Fibonacci, Primes, or Integers.\n \n ```\n user_choice = input('I am the Math Magician. What would you like me to do? ')\n ```\n1. The goal here is that once the user tells the program what operation to perform, it will spit out the numbers forever until you “ctrl+c”.\n `print(“Ok. I’m going to help produce \" + user_choice);`\n1. Use `time.sleep(seconds)` when you output each number to the console to make each number legible (otherwise it goes too fast).\n1. Make sure that your code validates user input. As a software developer, part of your job will be to handle edge cases. Think about possible things that the user can do that don't match what you expect of them, because they will. For example, at the prompt, they could type in the string `Integers`.\n\n### Step 5\n\nDocument your implementation code with docstrings.\n" } ]
3
sfiligoi/cms-git-set
https://github.com/sfiligoi/cms-git-set
1a5984ec191ac21042de72c486a82f6faeae40ca
ad2bae81185c5b286bfb3d8cd83664c016fe2c7e
1cc79b81969f9605848f20cbd3c374d6562190ad
refs/heads/master
2020-05-06T15:25:56.093305
2019-04-02T20:00:31
2019-04-02T20:00:31
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6875, "alphanum_fraction": 0.7124999761581421, "avg_line_length": 19, "blob_id": "b51f6354c73dd0fee85932de8370796c0d8392e2", "content_id": "d68a065e0b8960515a6a0fe134a921e8b406d7c4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 80, "license_type": "permissive", "max_line_length": 33, "num_lines": 4, "path": "/convertNB2Script.sh", "repo_name": "sfiligoi/cms-git-set", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#ipython nbconvert --to=python $1\njupyter nbconvert --to python $1\n" }, { "alpha_fraction": 0.4859813153743744, "alphanum_fraction": 0.7196261882781982, "avg_line_length": 34.66666793823242, "blob_id": "f8a6112ee4e2817e0372d6985b68ee2d3ecb1399", "content_id": "bd7d7249d3c8f2c9c8efac43c1658035e56b506e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 107, "license_type": "permissive", "max_line_length": 93, "num_lines": 3, "path": "/remoteWork.sh", "repo_name": "sfiligoi/cms-git-set", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nssh -tt [email protected] ssh -N -f -L localhost:8887:localhost:8888 [email protected]\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.6351351141929626, "avg_line_length": 17.5, "blob_id": "2aadf1b82415321ddc7b2479f5c4b1a7a7a59e9c", "content_id": "bf563c8a80ef531ed0281602f3dd1610d813446e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 74, "license_type": "permissive", "max_line_length": 30, "num_lines": 4, "path": "/closePort.sh", "repo_name": "sfiligoi/cms-git-set", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#lsof -ti:8888 | xargs kill -9\nlsof -ti:8887 | xargs kill -9\n" }, { "alpha_fraction": 0.4935064911842346, "alphanum_fraction": 0.7402597665786743, "avg_line_length": 24.66666603088379, "blob_id": "b06e3bd8302dd0ae82ca08f3ea215d22757e3fe1", "content_id": "79cfc42bf4c78777f2614c2d41c98d102f17ed22", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 77, "license_type": "permissive", "max_line_length": 63, "num_lines": 3, "path": "/remoteLocalWork.sh", "repo_name": "sfiligoi/cms-git-set", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nssh -N -L localhost:8888:localhost:8887 [email protected]\n" }, { "alpha_fraction": 0.6526602506637573, "alphanum_fraction": 0.6726828217506409, "avg_line_length": 26.837696075439453, "blob_id": "9b0d3539685a294436ed00cc0acb9131b88a31a1", "content_id": "305f16366da1465f58da3d53b474ec6516f558da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10638, "license_type": "permissive", "max_line_length": 114, "num_lines": 382, "path": "/working_set.py", "repo_name": "sfiligoi/cms-git-set", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom __future__ import print_function\nimport datetime\nfrom functools import reduce\nimport os\n\nimport pandas as pd\nimport numpy as np\n#get_ipython().run_line_magic('matplotlib', 'nbagg')\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nplt.ioff()\n\n\n# In[2]:\n\n\n# Data collected from a spark query at CERN, in pandas pickle format\n# CRAB jobs only have data after Oct. 2017\nws = pd.read_pickle(\"data/working_set_day.pkl.gz\")\n# spark returns lists, we want to use sets\nws['working_set_blocks'] = ws.apply(lambda x: set(x.working_set_blocks), 'columns')\nws['working_set'] = ws.apply(lambda x: set(x.working_set), 'columns')\n\n\n# In[3]:\n\n\n# DBS BLOCKS table schema:\n# BLOCK_ID NOT NULL NUMBER(38)\n# BLOCK_NAME NOT NULL VARCHAR2(500)\n# DATASET_ID NOT NULL NUMBER(38)\n# OPEN_FOR_WRITING NOT NULL NUMBER(38)\n# ORIGIN_SITE_NAME NOT NULL VARCHAR2(100)\n# BLOCK_SIZE NUMBER(38)\n# FILE_COUNT NUMBER(38)\n# CREATION_DATE NUMBER(38)\n# CREATE_BY VARCHAR2(500)\n# LAST_MODIFICATION_DATE NUMBER(38)\n# LAST_MODIFIED_BY VARCHAR2(500)\nif not os.path.exists('data/block_size.npy'):\n blocksize = pd.read_csv(\"data/dbs_blocks.csv.gz\", dtype='i8', usecols=(0,5), names=['block_id', 'block_size'])\n np.save('data/block_size.npy', blocksize.values)\n blocksize = blocksize.values\nelse:\n blocksize = np.load('data/block_size.npy')\n\n# We'll be accessing randomly, make a dictionary\nblocksize = {v[0]:v[1] for v in blocksize}\n\n\n# In[4]:\n\n\n# join the data tier definitions\ndatatiers = pd.read_csv('data/dbs_datatiers.csv').set_index('id')\nws['data_tier'] = datatiers.loc[ws.d_data_tier_id].data_tier.values\n\n\n# In[5]:\n\n\ndate_index = np.arange(np.min(ws.day.values//86400), np.max(ws.day.values//86400)+1)\ndate_index_ts = np.array(list(datetime.date.fromtimestamp(day*86400) for day in date_index))\n\n\n# In[6]:\n\n\nws_filtered = ws[(ws.crab_job==True) & (ws.data_tier.str.contains('MINIAOD'))]\n\nblocks_day = []\nfor i, day in enumerate(date_index):\n today = (ws_filtered.day==day*86400)\n blocks_day.append(reduce(lambda a,b: a.union(b), ws_filtered[today].working_set_blocks, set()))\n\nprint(\"Done assembling blocklists\")\n\nnrecords = np.zeros_like(date_index)\nlifetimes = {\n '1w': 7,\n '1m': 30,\n '3m': 90,\n '6m': 120,\n}\nws_size = {k: np.zeros_like(date_index) for k in lifetimes}\nnrecalls = {k: np.zeros_like(date_index) for k in lifetimes}\nrecall_size = {k: np.zeros_like(date_index) for k in lifetimes}\nprevious = {k: set() for k in lifetimes}\n\nfor i, day in enumerate(date_index):\n nrecords[i] = ws_filtered[(ws_filtered.day==day*86400)].size\n for key in lifetimes:\n current = reduce(lambda a,b: a.union(b), blocks_day[max(0,i-lifetimes[key]):i+1], set())\n recall = current - previous[key]\n nrecalls[key][i] = len(recall)\n ws_size[key][i] = sum(blocksize[bid] for bid in current)\n recall_size[key][i] = sum(blocksize[bid] for bid in recall)\n previous[key] = current\n if i%30==0:\n print(\"Day \", i)\n\nprint(\"Done\")\n\n\n# In[7]:\n\n\nfig, ax = plt.subplots(1,1)\nax.plot(date_index_ts, recall_size['1w']/1e15, label='1 week')\nax.plot(date_index_ts, recall_size['1m']/1e15, label='1 month')\nax.plot(date_index_ts, recall_size['3m']/1e15, label='3 months')\nax.legend(title='Block lifetime')\nax.set_title('Simulated block recalls for CRAB users')\nax.set_ylabel('Recall rate [PB/day]')\nax.set_xlabel('Date')\nax.set_ylim(0, None)\nax.set_xlim(datetime.date(2017,10,1), None)\n\n\n# In[27]:\n\n\nfig, ax = plt.subplots(1,1)\nax.plot(date_index_ts, ws_size['1w']/1e15, label='1 week')\nax.plot(date_index_ts, ws_size['1m']/1e15, label='1 month')\nax.plot(date_index_ts, ws_size['3m']/1e15, label='3 months')\nax.legend(title='Block lifetime')\nax.set_title('Working set for CRAB users, MINIAOD*')\nax.set_ylabel('Working set size [PB]')\nax.set_xlabel('Date')\nax.set_ylim(0, None)\nax.set_xlim(datetime.date(2017,10,1), None)\n\n\n# In[9]:\n\n\nrecall_size['3m'].mean()/1e12\n\n\n# In[10]:\n\n\nprint(ws_filtered)\n\n\n# In[11]:\n\n\n# block_dict is a dictionary that holds the lists of blocks\n# for all of the days for which the lists are nonzero\nblock_dict = {}\ni=0\nfor el in blocks_day:\n i=i+1\n if len(el)>0:\n block_dict[i] = el\n\nprint(\"Merging daily block lists into one block set\")\nblock_list = []\nfor i in range(len(blocks_day)):\n block_list += blocks_day[i]\n# block_set is a set of all unique blocks.\n# This can be used to isolate properties of individual blocks\n# (e.g. how many times a block is accessed)\nblock_set = set(block_list)\nprint(\"Block Set Created\")\n\n\n# In[12]:\n\n\n# block_m_access is a set of blocks that have been accessed \n# in more than one day\nblock_m_access = set()\n\nfirst = False\nsecond = False\nfor day in block_dict:\n if first is False:\n block_m_access.update(block_set.intersection(block_dict[day]))\n first = True\n elif (second is False):\n block_m_access = (block_m_access.intersection(block_dict[day]))\n second = True\n else:\n block_m_access.update(block_m_access.intersection(block_dict[day]))\nprint(\"Done\")\n\n\n# In[13]:\n\n\nprint(block_m_access)\n\n\n# In[14]:\n\n\n# Initializes all of the access lists and timers\n# \"timers\" are dictionaries with unique block keys and values that are\n# lists\n\n# block_access_timer\n# keys are unique blocks\n# values are the lists of times between first access and the subsequent accesses\nblock_access_timer = {}\nfor setBlock in block_set:\n block_access_timer[setBlock] = []\n \n# block_first_access\n# keys are unique blocks\n# values are the time of first access\nblock_first_access = {}\nfor setBlock in block_set:\n block_first_access[setBlock] = 0\n \n# block_sub_access\n# keys are unique blocks\n# values are the time of first access\nblock_sub_access = {}\nfor setBlock in block_set:\n block_sub_access[setBlock] = 0\n \n# block_abs_access\n# keys are unique blocks\n# values are the day of access\nblock_abs_access_timer = {}\nfor setBlock in block_set:\n block_abs_access_timer[setBlock] = []\n\n\n# In[15]:\n\n\n# Populates the dictionary, block_access_timer, with the time difference between the\n# first access and each subsequent access\ndef accessTime(block, day):\n if (block_first_access[block] == 0):\n # This stores the inital time (time at which the block was first accessed)\n block_first_access[block] = day\n elif (block_first_access[block] != 0):\n block_sub_access[block] = day\n # Holds the time difference between the first access and each subsequent access\n block_access_timer[block].append(block_sub_access[block] - block_first_access[block])\n else:\n return\n \n# Populates the dictionary, block_abs_access, with the day at which the block was \n# accessed\ndef absAccessTime(block, day):\n block_abs_access_timer[block].append(day)\n \n# Removes all of the blocks that did not repeat\ndef removeTimerRedundancies(timer):\n for block in list(timer.keys()):\n if not timer[block]:\n timer.pop(block)\n \n# Iterates over each day and for each block appends to its corresponding list every\n# day for which it is accessed\nfirst = False\nblock_t_access = set()\nfor day in block_dict:\n if first is False:\n block_t_access.update(block_set.intersection(block_dict[day]))\n first = True\n for block in block_t_access:\n accessTime(block, day)\n absAccessTime(block, day)\n else:\n block_t_access = (block_m_access.intersection(block_dict[day]))\n for block in block_t_access:\n accessTime(block, day)\n absAccessTime(block, day)\n if (day%50==0):\n print(\"Day\", day)\nprint(\"Done\")\n\n# Removes all of the blocks that did not repeat\nremoveTimerRedundancies(block_access_timer)\nremoveTimerRedundancies(block_abs_access_timer)\n\n\n# In[16]:\n\n\n# block_diff_access_timer\n# keys are unique blocks\n# values are the difference between subsequent days of access\nblock_diff_access_timer = {}\nfor block in set(block_abs_access_timer.keys()):\n block_diff_access_timer[block] = []\n\n# Populates block_diff_access_timer \n# Iterates through each block and takes the difference between the\n# subsequent times of access\nfor block in list(block_abs_access_timer.keys()):\n block_diff_access_timer[block] = [block_abs_access_timer[block][i + 1]\n -block_abs_access_timer[block][i] \n for i in range(len(block_abs_access_timer[block])-1)]\n\n\n# In[54]:\n\n\n# Counts the number of blocks that have been accessed consecutively under \n# the given number of days\ncons_occurrence_dict = {}\nfor block in list(block_diff_access_timer.keys()):\n if len(list(block_diff_access_timer[block])) > 0:\n threshold = max(block_diff_access_timer[block])\n if threshold in cons_occurrence_dict:\n for dayCount in range(0, threshold + 1):\n cons_occurrence_dict[dayCount] += 1\n else:\n for dayCount in range(0, threshold + 1):\n cons_occurrence_dict[dayCount] = 1\n\ncons_exact_occurrence_dict = {}\nfor block in list(block_diff_access_timer.keys()):\n if len(list(block_diff_access_timer[block])) > 0:\n threshold = max(block_diff_access_timer[block])\n if threshold in cons_exact_occurrence_dict:\n cons_exact_occurrence_dict[threshold] += 1\n else:\n cons_exact_occurrence_dict[threshold] = 1\n\n\n# In[59]:\n\n\nfig, ax = plt.subplots(1,1)\ni = np.arange(1,1000)\nexampleList = list(block_access_timer.keys())\nfor block in list(block_access_timer.keys()):\n i = np.arange(0,len(block_access_timer[block]))\n ax.plot(i, block_access_timer[block], label=(\"Block: \", block))\nax.legend(title='Block')\nax.set_title('Days Since First Access Vs. Access')\nax.set_ylabel('Days Since First Access')\nax.set_xlabel('Access #')\nax.set_ylim(0, None)\nax.set_xlim(0, None)\n\n\n# In[61]:\n\n\nfig, ax = plt.subplots(1,1)\nax.plot(sorted(cons_occurrence_dict.keys()), \n list(cons_occurrence_dict.values()))\nax.set_title('Block Quantity Accessed Continuously')\nax.set_ylabel('Number of Blocks Accessed Continuously')\nax.set_xlabel('Day Threshold for Continuous Access')\nax.set_ylim(0, None)\nax.set_xlim(0, 60)\nplt.savefig(\"Figure3.png\")\n\n\n# In[ ]:\n\n\nfig, ax = plt.subplots(1,1)\nax.plot(sorted(cons_exact_occurrence_dict.keys()), \n list(cons_exact_occurrence_dict.values()))\nax.set_title('Block Quantity Accessed Continuously')\nax.set_ylabel('Number of Blocks Accessed Continuously')\nax.set_xlabel('Day Threshold for Continuous Access')\nax.set_ylim(0, None)\nax.set_xlim(0, 60)\nplt.savefig(\"Figure4.png\")\n\n\n# In[ ]:\n\n\n\n\n" } ]
5
zvut/Web-Scraping-And-Prediction-Of-Selling-Prices-Using-BeautifulSoup-And-Random-Forest-Regressor
https://github.com/zvut/Web-Scraping-And-Prediction-Of-Selling-Prices-Using-BeautifulSoup-And-Random-Forest-Regressor
9f6ca0529d602f4348a423b8d91667c16835dd67
d4087f4cdbba9906ddc358c850068888a5e41b78
b35676b78f9f74e2cf28935c470b54470260ff20
refs/heads/main
2023-06-20T11:34:33.481937
2021-07-06T08:47:05
2021-07-06T08:47:05
383,393,869
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8526315689086914, "alphanum_fraction": 0.8526315689086914, "avg_line_length": 95, "blob_id": "1877e6cddc93af68fa028b86fabecc7f57aa4b7d", "content_id": "5d4f703a0e23b58f3a257c81f432a6d004a166af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 95, "license_type": "no_license", "max_line_length": 95, "num_lines": 1, "path": "/README.md", "repo_name": "zvut/Web-Scraping-And-Prediction-Of-Selling-Prices-Using-BeautifulSoup-And-Random-Forest-Regressor", "src_encoding": "UTF-8", "text": "# Web-Scraping-And-Prediction-Of-Selling-Prices-Using-BeautifulSoup-And-Random-Forest-Regressor" }, { "alpha_fraction": 0.6279406547546387, "alphanum_fraction": 0.6583423614501953, "avg_line_length": 14.765714645385742, "blob_id": "32b126bdbc5342f36d532d63cba41ffc73306d82", "content_id": "684f132851210f3ad8d2e66a74cc43b8c3e5befe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2763, "license_type": "no_license", "max_line_length": 175, "num_lines": 175, "path": "/reg2/CarPrice_Prediction.py", "repo_name": "zvut/Web-Scraping-And-Prediction-Of-Selling-Prices-Using-BeautifulSoup-And-Random-Forest-Regressor", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport datetime\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[2]:\n\n\ndf = pd.read_csv('car_data.csv')\n\n\n# In[3]:\n\n\ndf.head()\n\n\n# In[4]:\n\n\ndf.shape\n\n\n# In[5]:\n\n\nprint(df['Seller_Type'].unique())\nprint(df['Transmission'].unique())\nprint(df['Owner'].unique())\n\n\n# In[6]:\n\n\n##checking none or missing values\ndf.isnull().sum()\n\n\n# In[7]:\n\n\ndf.describe()\n\n\n# In[8]:\n\n\ndf['Years'] = int(datetime.datetime.now().year) - df['Year']\ndf=df.drop(['Car_Name', 'Year'], axis =1)\n\n\n# In[9]:\n\n\ndf.head()\n\n\n# In[10]:\n\n\ndf = pd.get_dummies(df, drop_first=True)\ndf.head()\n\n\n# In[11]:\n\n\ncorr_matrix = df.corr()\ntop_corr_features = corr_matrix.index\nplt.figure(figsize=(20,20))\nsns.heatmap(df[top_corr_features].corr(),annot=True, cmap='RdYlGn')\n\n\n# In[12]:\n\n\nX = df.iloc[:,1:]\nY = df.iloc[:,0]\n\n\n# In[13]:\n\n\nfrom sklearn.ensemble import ExtraTreesRegressor\nmodel = ExtraTreesRegressor()\nmodel.fit(X,Y)\n\n\n# In[14]:\n\n\nfeat_importance = pd.Series(model.feature_importances_, index= X.columns)\nfeat_importance.nlargest(5).plot(kind='barh')\nplt.show()\n\n\n# In[15]:\n\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size=0.2)\n\n\n# In[16]:\n\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import RandomizedSearchCV\nrf=RandomForestRegressor()\n\nn_estimators = [int(x) for x in np.linspace(start = 100, stop = 1200, num = 12)]\nmax_features = ['auto', 'sqrt']\nmax_depth = [int(x) for x in np.linspace(5, 30, num = 6)]\nmin_samples_split = [2, 5, 10, 15, 100]\nmin_samples_leaf = [1, 2, 5, 10]\nrandom_grid = {'n_estimators': n_estimators,\n 'max_features': max_features,\n 'max_depth': max_depth,\n 'min_samples_split': min_samples_split,\n 'min_samples_leaf': min_samples_leaf}\n\n\n# In[17]:\n\n\nrf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid,scoring='neg_mean_squared_error', n_iter = 25, cv = 5, verbose=2, random_state=42, n_jobs = 1)\n\n\n# In[18]:\n\n\nrf_random.fit(X_train,Y_train)\n\n\n# In[19]:\n\n\npredictions=rf_random.predict(X_test)\nsns.distplot(Y_test-predictions)\n\n\n# In[20]:\n\n\nfrom sklearn import metrics\nprint('MAE:', metrics.mean_absolute_error(Y_test, predictions))\nprint('MSE:', metrics.mean_squared_error(Y_test, predictions))\nprint('RMSE:', np.sqrt(metrics.mean_squared_error(Y_test, predictions)))\nrmse=np.sqrt(metrics.mean_squared_error(Y_test, predictions))\n\n\n# In[21]:\n\n\nprint(\"Accuracy= {}\".format(100*max(0,rmse)))\n\n\n# In[22]:\n\n\nimport pickle\nfile = open('random_forest_regression_model.pkl', 'wb')\npickle.dump(rf_random, file)\n\n\n# In[ ]:\n\n\n\n\n" } ]
2
AndreasJJ/Docker-nginx-flask-auto-ssl
https://github.com/AndreasJJ/Docker-nginx-flask-auto-ssl
3f27a30ef2af6b17af51f23930111ae775c02a47
7fcfd6d910f36af627050cb5793261d9ad4b966d
bb86943187b00512ebc823e2f0000a6f26596b0c
refs/heads/master
2020-05-30T13:58:47.887060
2019-06-20T22:10:20
2019-06-20T22:10:20
189,775,230
4
1
null
null
null
null
null
[ { "alpha_fraction": 0.760729968547821, "alphanum_fraction": 0.7637715339660645, "avg_line_length": 50.91228103637695, "blob_id": "1478bf5ac1e30f992a04df4c79eb68b2dafc86c1", "content_id": "991b99d95d21d5a98c00beead339454be7029b04", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3041, "license_type": "permissive", "max_line_length": 213, "num_lines": 57, "path": "/README.md", "repo_name": "AndreasJJ/Docker-nginx-flask-auto-ssl", "src_encoding": "UTF-8", "text": "# A Flask docker container with auto ssl boilerplate\nA simple docker(-compose) container with nginx and auto renewal ssl from letsencrypt for uwsgi applications.\n\n# How to use?\nReplace all occurrences of \\<domain\\> with your domain in the **flask-site-nginx.conf** and **init-letsencrypt.sh** files.\n \nReplace \\<email\\> with your email in the **init-letsencrypt.sh** file.\n\nPlace your application inside the application folder, or replace the application folder with whatever your application folder is called and modify the **wsgi.py** file to get the ***app*** object from your folder.\n\nChange the permissions on the init-letsencrypt.sh script such that you can run it, then run it.\n\n# File Structure and Explanation\n```\nRoot \n├── application\n│ ├── \\_\\_init\\_\\_.py\n│ └── router.py\n├── Dockerfile\n├── docker-compose.yml\n├── flask-site-nginx.conf\n├── nginx.conf\n├── init-letsencrypt.sh\n├── requirements.txt\n├── supervisord.conf\n├── uwsgi.ini\n├── wsgi.py\n└── [...]\n```\n* __application__: Simple test flask application. This is where you'd place your application\n* __Dockerfile__: Dockerfile to assemble image with nginx, supervisord and uwsgi\n* __docker-compose.yml__: Compose file for certbot and application container open on port 80 and 443\n* __flask-site-nginx.conf__: Basic nginx site configuration for application with https\n* __nginx.conf__: Standard nginx configuration with daemon off.\n* __init-letsencrypt.sh__: modified script from wmnnd to build container, fix ssl certificate and start the application and certbot container\n* __requirements.txt__: A document containing all required pip packages for your application\n* __supervisord.conf__: Basic supervisord configuration for uwsgi and nginx\n* __uwsgi.ini__: Uwsgi configuration\n* __wsgi.py__: Application start file that uwsgi will run\n\n# Contribute\nWhen contributing to this repository, please first discuss the change you wish to make via issue,\nemail, or any other method with the owners of this repository before making a change. \n\nPlease note we have a code of conduct, and follow it in all your interactions with the project.\n\n## Pull Request Process\n1. Ensure any install or build dependencies are removed before the end of the layer when doing a build.\n2. Update the README.md with details of changes to the interface, this includes new environment variables, exposed ports, useful file locations and container parameters.\n3. Increase the version numbers in any examples files and the README.md to the new version that this Pull Request would represent.\n4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you do not have permission to do that, you may request the second reviewer to merge it for you.\n\n## Code of Conduct\nThis project and everyone participating in it is governed by the Code of Conduct expected to uphold this code.\n\n# Credits\nHttps made possible by letsencrypt and [nginx-certbot](https://github.com/wmnnd/nginx-certbot)\n" }, { "alpha_fraction": 0.7254902124404907, "alphanum_fraction": 0.7254902124404907, "avg_line_length": 18.125, "blob_id": "8f186992031f851152e650d2dc5310f966aea64b", "content_id": "f280fd56c908e466adfcbebbd523cfb854744c8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 153, "license_type": "permissive", "max_line_length": 40, "num_lines": 8, "path": "/application/router.py", "repo_name": "AndreasJJ/Docker-nginx-flask-auto-ssl", "src_encoding": "UTF-8", "text": "#Imports\nfrom flask import Flask, render_template\nfrom application import app\n\n#Index page\[email protected]('/')\ndef hello_world():\n return 'Hello, World!'\n" }, { "alpha_fraction": 0.6382978558540344, "alphanum_fraction": 0.6382978558540344, "avg_line_length": 18, "blob_id": "4abc7f0f2bad7d56fa6f5de1ada3d08f8a31cee2", "content_id": "c0f941798b29856af95f1e6d6dcbec40ede1b0bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "permissive", "max_line_length": 27, "num_lines": 5, "path": "/wsgi.py", "repo_name": "AndreasJJ/Docker-nginx-flask-auto-ssl", "src_encoding": "UTF-8", "text": "from application import app\n\n# Starts the application\nif __name__ == \"__main__\":\n app.run()" }, { "alpha_fraction": 0.6505376100540161, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 13.384614944458008, "blob_id": "0468b0b2bb17b57f01e4677bec692f3811355661", "content_id": "2a9e223cbb084116d13bf8f7a1355bf148ef449c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 186, "license_type": "permissive", "max_line_length": 31, "num_lines": 13, "path": "/uwsgi.ini", "repo_name": "AndreasJJ/Docker-nginx-flask-auto-ssl", "src_encoding": "UTF-8", "text": "[uwsgi]\nwsgi-file = /home/host/wsgi.py \ncallable = app\n\nuid = nginx\ngid = nginx\n\nsocket = /run/uwsgi.sock\nchown-socket = nginx:nginx\nchmod-socket = 664\n\ncheaper = 1\nprocesses = %(%k + 1)" }, { "alpha_fraction": 0.7165932655334473, "alphanum_fraction": 0.7254038453102112, "avg_line_length": 23.321428298950195, "blob_id": "25bbf6fe45c2076fcb4a87b6efe8a06426beb5c2", "content_id": "d5ce76da1ad8bf6b7a924b4a131f170ece33216b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 681, "license_type": "permissive", "max_line_length": 101, "num_lines": 28, "path": "/Dockerfile", "repo_name": "AndreasJJ/Docker-nginx-flask-auto-ssl", "src_encoding": "UTF-8", "text": "FROM python:3.7\n\nRUN apt-get update\nRUN apt-get install -y --no-install-recommends \\\n libatlas-base-dev gfortran nginx supervisor\nRUN apt-get install sqlite3\n\nRUN pip3 install uwsgi\n\nCOPY ./requirements.txt /home/host/requirements.txt\n\nRUN pip3 install -r /home/host/requirements.txt\n\nRUN useradd --no-create-home nginx\n\nRUN rm /etc/nginx/sites-enabled/default\nRUN rm -r /root/.cache\n\nCOPY nginx.conf /etc/nginx/\nCOPY flask-site-nginx.conf /etc/nginx/conf.d/\nCOPY uwsgi.ini /etc/uwsgi/\nCOPY supervisord.conf /etc/supervisor/conf.d/\n\nCOPY . /home/host\n\nWORKDIR /home/host\n\nCMD [\"sh\",\"-c\", \"/usr/bin/supervisord && 'while :; do sleep 6h & wait $${!}; nginx -s reload; done'\"]\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 19.16666603088379, "blob_id": "6ea48708f83df622320b8e9515c74a249f98cea2", "content_id": "2fba3d6f6ed04adfb2bd36af0c80a80404bca778", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "permissive", "max_line_length": 41, "num_lines": 6, "path": "/application/__init__.py", "repo_name": "AndreasJJ/Docker-nginx-flask-auto-ssl", "src_encoding": "UTF-8", "text": "from flask import Flask\n\napp = Flask(__name__)\napp.secret_key = 'super-duper-secret-key'\n\nfrom application import router" }, { "alpha_fraction": 0.3333333432674408, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 14, "blob_id": "f92bf5992571c5bda62930930d9e583e83366a8d", "content_id": "1d15c4691fa48d469cff1c711cfcebbf37177324", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 15, "license_type": "permissive", "max_line_length": 14, "num_lines": 1, "path": "/requirements.txt", "repo_name": "AndreasJJ/Docker-nginx-flask-auto-ssl", "src_encoding": "UTF-8", "text": "flask >= 1.0.2\n" } ]
7
AlejandroKler/Sounds-of-Cyber-City
https://github.com/AlejandroKler/Sounds-of-Cyber-City
dca16874c1e140e3d34f33482f4d86a2fe91abea
3efedb4cf5fab8affd01bd9bafc3e0e0b7d82711
66f0b1f7e46597969c3e24970b7da092cf7903b2
refs/heads/master
2021-01-21T11:00:12.096309
2017-09-08T16:26:38
2017-09-08T16:26:38
91,717,755
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6054644584655762, "alphanum_fraction": 0.6076502799987793, "avg_line_length": 40.59090805053711, "blob_id": "e5d38c6e6c6314b22325cdcaf21627af97ed2b9b", "content_id": "95de2c87f782ce4e5eeb8c4eba54fb3f920feefb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 925, "license_type": "no_license", "max_line_length": 125, "num_lines": 22, "path": "/Pila.py", "repo_name": "AlejandroKler/Sounds-of-Cyber-City", "src_encoding": "UTF-8", "text": "class Pila:\n \"\"\"Modela el funcionamiento de una pila. En esta se puede apilar elementos, desapilar elementos, ver el tope de la pila o\n chequear si está vacía\"\"\"\n def __init__(self):\n \"\"\"Crea una nueva instancia de la clase Pila\"\"\"\n self.items = []\n def esta_vacia(self):\n \"\"\"Revisa si la pila está vacía y devuelve un booleano\"\"\"\n return len(self.items) == 0\n def apilar(self,dato):\n \"\"\"Apila un elemento en la pila\"\"\"\n self.items.append(dato)\n def desapilar(self):\n \"\"\"Desapila el último elemento que se apiló\"\"\"\n if self.esta_vacia():\n raise IndexError(\"La pila está vacía\")\n return self.items.pop()\n def ver_tope(self):\n \"\"\"Devuelve el tope de la pila, es decir, el último elemento que se apiló\"\"\"\n if self.esta_vacia():\n raise IndexError(\"La pila esta vacia\")\n return self.items[-1]\n" }, { "alpha_fraction": 0.5782997608184814, "alphanum_fraction": 0.5861297249794006, "avg_line_length": 26.9375, "blob_id": "5aa1229434267d6eed6c14bfa5606d216aac9cb4", "content_id": "ddea48c18ac479db20644f13a07c35e08930bd76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1790, "license_type": "no_license", "max_line_length": 96, "num_lines": 64, "path": "/pila/pila.c", "repo_name": "AlejandroKler/Sounds-of-Cyber-City", "src_encoding": "UTF-8", "text": "/*************************************\n\tALUMNO: Alejandro Kler \n\tPADRON:100596\n\tCORRECTOR: Federico del Mazo \n**************************************/\n#include \"pila.h\"\n#include <stdlib.h>\n\n/* Definición del struct pila proporcionado por la cátedra.\n */\nstruct pila {\n void** datos;\n size_t cantidad; // Cantidad de elementos almacenados.\n size_t capacidad; // Capacidad del arreglo 'datos'.\n};\n\n/* *****************************************************************\n * PRIMITIVAS DE LA PILA\n * *****************************************************************/\n\n// ...\npila_t* pila_crear(void){\n\tpila_t* pila = malloc(sizeof(pila_t));\n\tif (!pila) return NULL;\n\tpila->datos = malloc(sizeof(void) * 2);\n\tif (!pila->datos) {\n\t\tfree(pila);\n\t\treturn NULL;\n\t}\n\tpila->capacidad = 2;\n\tpila->cantidad = 0;\n\treturn pila;\n}\nbool pila_modificar(pila_t *pila, int capacidad){\n\treturn !(bool) realloc(pila->datos,sizeof(void) * capacidad);\n}\nvoid pila_destruir(pila_t *pila){\n\tfree(pila->datos);\n\tfree(pila);\n}\nbool pila_esta_vacia(const pila_t *pila){\n\treturn !(bool) pila->cantidad;\n}\nbool pila_apilar(pila_t *pila, void* valor){\n\tif (pila->cantidad == pila->capacidad){\n\t\tif (!pila_modificar(pila,(int)pila->capacidad * 2)) return false; //Incrementamos su capacidad\n\t}\n\tpila->datos[pila->cantidad] = valor; //Agregamos en el proximo lugar\n\tpila->cantidad++;\n\treturn true;\n}\nvoid* pila_ver_tope(const pila_t *pila){\n\tif (!pila->cantidad) return NULL;\n\treturn pila->datos[pila->cantidad - 1];\n}\nvoid* pila_desapilar(pila_t *pila){\n\tif (!pila->cantidad) return NULL;\n\tif (pila->cantidad == pila->capacidad/4){\n\t\tif (!pila_modificar(pila,(int)pila->capacidad/2)) return false; //Decrementamos su capacidad\n\t}\n\tvoid* valor = pila->datos[pila->cantidad - 1];\n\tpila->cantidad--;\n\treturn valor;\n}\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 36.92307662963867, "blob_id": "fe5f29a9a299e984a11e78bdf90ac1af04fda3be", "content_id": "d8d85edec4f8f3827dcee93d4118bad830a7cd24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 986, "license_type": "no_license", "max_line_length": 120, "num_lines": 26, "path": "/MarcaDeTiempo.py", "repo_name": "AlejandroKler/Sounds-of-Cyber-City", "src_encoding": "UTF-8", "text": "class MarcaDeTiempo():\n \"\"\"Una marca de tiempo consiste en un conjunto de tracks que deben sonar (habilitados) y la duracion de la misma.\"\"\"\n def __init__(self,duracion):\n \"\"\"\n Crea una instancia de la clase.\n Parametros:\n duracion (float) Duracion de la marca de tiempo\n \"\"\"\n self.duracion = duracion\n self.tracks_habilitados = [] # Almacena los numeros de los tracks habilitados\n\n def obtener_habilitados(self):\n \"\"\" Devuelve la lista de tracks habilitados\"\"\"\n return self.tracks_habilitados\n\n def obtener_duracion(self):\n \"\"\" Devuelve la duracion de la marca\"\"\"\n return self.duracion\n\n def habilitar_track(self,numero_de_track):\n \"\"\"Habilita un track por su numero\"\"\"\n self.tracks_habilitados.append(numero_de_track)\n\n def deshabilitar_track(self,numero_de_track):\n \"\"\"Deshabilita un track por su numero\"\"\"\n self.tracks_habilitados.remove(numero_de_track)\n" }, { "alpha_fraction": 0.5769911408424377, "alphanum_fraction": 0.5769911408424377, "avg_line_length": 27.736841201782227, "blob_id": "47c2d076eb40c05b028a8353169e5ee55980e1ee", "content_id": "811bd9138dd6cd6e3784f9a717c5a5381dec8e8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 565, "license_type": "no_license", "max_line_length": 47, "num_lines": 19, "path": "/Track.py", "repo_name": "AlejandroKler/Sounds-of-Cyber-City", "src_encoding": "UTF-8", "text": "class Track():\r\n \"\"\"Representa un track de una cancion\"\"\"\r\n def __init__(self,tipo,frecuencia,volumen):\r\n \"\"\"Constructor de la clase\"\"\"\r\n self.tipo = str(tipo).lower()\r\n self.frecuencia = int(frecuencia)\r\n self.volumen = float(volumen)\r\n\r\n def obtener_tipo(self):\r\n \"\"\"Devuelve el tipo\"\"\"\r\n return self.tipo\r\n\r\n def obtener_frecuencia(self):\r\n \"\"\"Devuelve la frecuencia\"\"\"\r\n return self.frecuencia\r\n\r\n def obtener_volumen(self):\r\n \"\"\"Devuelve el volumen\"\"\"\r\n return self.volumen\r\n" }, { "alpha_fraction": 0.7684659361839294, "alphanum_fraction": 0.8309659361839294, "avg_line_length": 49.28571319580078, "blob_id": "de4553956421c6412987e3e98443c94e22fa5c35", "content_id": "5e6ae3d96c914c22447040246c10672daed83fd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 705, "license_type": "no_license", "max_line_length": 304, "num_lines": 14, "path": "/README.md", "repo_name": "AlejandroKler/Sounds-of-Cyber-City", "src_encoding": "UTF-8", "text": "# Sounds Of Cyber City\nProyecto para la Facultad de Ingenieria de la Universidad de Buenos Aires. Para la materia Algoritmos y Programación I.\n\n# Instrucciones\n- Es necesario tener instalado el modulo pyaudio\n- Abrir python 3 en la carpeta del repositorio\n- Ejecutar: import Shell\n- Listo. Los comandos y su documentacion pueden ser listados con help o ?\n\n# Autores\nLeonardo Bellaera y Alejandro Kler\n\n# Documentacion\nhttps://e77d1912-a-62cb3a1a-s-sites.googlegroups.com/site/fiuba7540rw/material/tp3-2017-1.pdf?attachauth=ANoY7cq9oZmR0gu7_wRsgi1kdiAF2pmt_3oa1pnCBaVf0twvdslpCkp_6wUjHMesL4UM9cfyjvs_YBWExkRNLSrJdujpW7W_xJR9DFEWy3u0nY9xk3KtGYZ15yozvKM3BF7pn_srYnfDjddOBAz0OKSnYpQ-sIy9TVJS8crzK9JRNYqXihwlJK3uHdD7S_7gAxioACHXoxIbRdzFXIpytKLrGf-CKmhZ6o4o2y6joDR-NBfwjopjVCY%3D&attredirects=0\n" }, { "alpha_fraction": 0.6248201727867126, "alphanum_fraction": 0.6449640393257141, "avg_line_length": 41.121212005615234, "blob_id": "141c51997eec28373f046e982c339d848735475b", "content_id": "a71b7e0287b325da86db905eabeb3939d08a0525", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2780, "license_type": "no_license", "max_line_length": 69, "num_lines": 66, "path": "/pila/pruebas_alumno.c", "repo_name": "AlejandroKler/Sounds-of-Cyber-City", "src_encoding": "UTF-8", "text": "#include \"pila.h\"\n#include \"testing.h\"\n#include <stddef.h>\n\n\n/* ******************************************************************\n * PRUEBAS UNITARIAS ALUMNO\n * *****************************************************************/\n\nvoid pruebas_pila_alumno() {\n\tpila_t* pila = pila_crear();\n\tint uno = 1;\n\tint dos = 2;\n\tint tres = 3;\n\tint cuatro = 4;\n\tint cinco = 5;\n\tint seis = 6;\n\tint siete = 7;\n\tint ocho = 8;\n\tint nueve = 9;\n\tint* puntero_uno = &uno;\n\tint* puntero_dos = &dos;\n\tint* puntero_tres = &tres;\n\tint* puntero_cuatro = &cuatro;\n\tint* puntero_cinco = &cinco;\n\tint* puntero_seis = &seis;\n\tint* puntero_siete = &siete;\n\tint* puntero_ocho = &ocho;\n\tint* puntero_nueve = &nueve;\n\tprint_test(\"Ver tope 1\", pila_ver_tope(pila) == NULL);\n\tprint_test(\"Desapilar 1\",pila_desapilar(pila) == NULL);\n\tprint_test(\"Apilar 1\",pila_apilar(pila,puntero_uno) );\n\tprint_test(\"Redimension 1\",(int)pila->capacidad == 2 );\n\tprint_test(\"Apilar 2\",pila_apilar(pila,puntero_dos));\n\tprint_test(\"Redimension 2\",(int)pila->capacidad == 2 );\n\tprint_test(\"Apilar 3\",pila_apilar(pila,puntero_tres));\n\tprint_test(\"Ver tope 2\", pila_ver_tope(pila) == 3);\n\tprint_test(\"Redimension 3\",(int)pila->capacidad == 4 );\n\tprint_test(\"Apilar 4\",pila_apilar(pila,puntero_cuatro));\n\tprint_test(\"Redimension 4\",(int)pila->capacidad == 8 );\n\tprint_test(\"Apilar 5\",pila_apilar(pila,puntero_cinco));\n\tprint_test(\"Ver tope 3\",pila_ver_tope(pila) == 5);\n\tprint_test(\"Apilar 6\",pila_apilar(pila,puntero_seis));\n\tprint_test(\"Apilar 7\",pila_apilar(pila,puntero_siete));\n\tprint_test(\"Apilar 8\",pila_apilar(pila,puntero_ocho));\n\tprint_test(\"Apilar 9\",pila_apilar(pila,puntero_nueve));\n\tprint_test(\"Redimension 5\",(int)pila->capacidad* == 8 );\n\tprint_test(\"Desapilar 2\",pila_desapilar(pila) == puntero_nueve);\n\tprint_test(\"Desapilar 3\",pila_desapilar(pila) == puntero_ocho);\n\tprint_test(\"Desapilar 4\",pila_desapilar(pila) == puntero_siete);\n\tprint_test(\"Ver tope 4\",pila_ver_tope(pila) == puntero_seis);\n\tprint_test(\"Desapilar 5\",pila_desapilar(pila) == puntero_seis);\n\tprint_test(\"Desapilar 1\",pila_desapilar(pila) == puntero_cinco);\n\tprint_test(\"Ver tope 5\",pila_ver_tope(pila) == puntero_cuatro);\n\tprint_test(\"Desapilar 6\",pila_desapilar(pila) == puntero_cuatro);\n\tprint_test(\"Desapilar 7\",pila_desapilar(pila) == puntero_tres);\n\tprint_test(\"Redimension 6\",(int)pila->capacidad == 8 );\n\tprint_test(\"Desapilar 8\",pila_desapilar(pila) == puntero_dos);\n\tprint_test(\"Redimension 7\",(int)pila->capacidad == 4 );\n\tprint_test(\"Desapilar 9\",pila_desapilar(pila) == puntero_dos);\n\tprint_test(\"Desapilar 10\",pila_desapilar(pila) == NULL);\n\tprint_test(\"Redimension 8\",(int)pila->capacidad == 2 );\n\tprint_test(\"Desapilar 11\",pila_desapilar(pila) == NULL);\n\tprint_test(\"Ver tope 6\", pila_ver_tope(pila) == NULL);\n\tpila_destruir(pila);\n}\n" }, { "alpha_fraction": 0.5920026302337646, "alphanum_fraction": 0.5925518870353699, "avg_line_length": 41.737091064453125, "blob_id": "bb8ba779c25da2a39dfcaa8a4942c0a56dc3c7c2", "content_id": "bf5304dcb6eda81e47ec20038bff44a5dd73d701", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9104, "license_type": "no_license", "max_line_length": 140, "num_lines": 213, "path": "/Cancion.py", "repo_name": "AlejandroKler/Sounds-of-Cyber-City", "src_encoding": "UTF-8", "text": "from ListaEnlazada import ListaEnlazada\nfrom MarcaDeTiempo import MarcaDeTiempo\nfrom Track import Track\nimport soundPlayer as pysounds\n\nclass Cancion():\n \"\"\"Representa un conjunto de marcas de tiempo y sonidos (tracks)\"\"\"\n FUNCIONES_DISPONIBLES = [\"sine\",\"triangular\",\"square\"] # Constante con los tipos de tracks\n def __init__(self):\n \"\"\"Crea una instancia de la clase.\"\"\"\n self.tiempos = ListaEnlazada() # Marcas de tiempo\n self.tracks = [] # Lista de tracks\n\n def store(self,name):\n \"\"\"Guarda la cancion, si no recibe una cadena valida levanta ValueError\n Parametros:\n name (string) Nombre del archivo sin extension\"\"\"\n if self.tiempos.esta_vacia():\n return\n self.tiempos.volver_al_inicio()\n with open(name + \".plp\",\"w\") as f:\n f.write(\"C,\"+str(self.cant_tracks())+\"\\n\")\n for track in self.tracks:\n f.write(\"S,{}|{}|{}\\n\".format(track.obtener_tipo(),track.obtener_frecuencia(),track.obtener_volumen()))\n anterior = None\n MarcaDeTiempo = self.tiempos.actual()\n while True:\n try:\n if not MarcaDeTiempo.obtener_duracion() == anterior:\n f.write(\"T,\"+str(MarcaDeTiempo.obtener_duracion())+\"\\n\")\n anterior = MarcaDeTiempo.obtener_duracion()\n cadena = \"\"\n for posicion in range(self.cant_tracks()):\n if posicion in MarcaDeTiempo.obtener_habilitados():\n cadena += \"#\"\n else:\n cadena += \"·\"\n f.write(\"N,\"+cadena+\"\\n\")\n MarcaDeTiempo = self.tiempos.siguiente()\n except StopIteration:\n break\n\n def step(self):\n \"\"\"Avanza a la siguiente marca de tiempo si la hay. Si no, no hace nada.\"\"\"\n try:\n self.tiempos.siguiente()\n except StopIteration:\n return\n \n def stepm(self,numero):\n \"\"\"Avanza N marcas de tiempo hacia adelante o las que pueda.\n Parametros:\n numero (int) Numero de marcas a avanzar\"\"\"\n try:\n for x in range(numero):\n self.tiempos.siguiente()\n except StopIteration:\n return\n \n def back(self):\n \"\"\"Retrocede a la anterior marca de tiempo si puede.\"\"\"\n try:\n self.tiempos.anterior()\n except StopIteration:\n return\n\n def backm(self,numero):\n \"\"\"Retrocede N marcas de tiempo hacia atras o las que pueda.\n Parametros:\n numero (int) Numero de marcas a retroceder\"\"\"\n try:\n for x in range(numero):\n self.tiempos.anterior()\n except StopIteration:\n return \n\n def track_add(self,funcion,frecuencia,volumen):\n \"\"\"Agrega un track con el sonido indicado.\n Parametros:\n funcion (string) nombre de la funcion\n frecuencia (int) frecuencia de onda\n volumen (float) volumen del sonido comprendido entre 0 y 1\"\"\"\n if funcion.lower() not in self.FUNCIONES_DISPONIBLES:\n raise ValueError('El sonido introducido no existe')\n self.tracks.append(Track(funcion,int(frecuencia),float(volumen)))\n\n def track_del(self,posicion):\n \"\"\"Elimina un track por numero. Levanta un IndexError si no esta habilitado.\n Parametros:\n posicion (int) Posicion a quitar\"\"\"\n self.tracks.pop(posicion)\n\n def mark_add(self,duracion):\n \"\"\"Agrega una marca de tiempo de la duracion indicada. Originalmente\n todos los tracks estan deshabilitados\n Parametros:\n duracion (float) duracion de la marca de tiempo\"\"\"\n mark = MarcaDeTiempo(duracion)\n self.tiempos.insert(self.tiempos.posicion_actual(),mark)\n self.tiempos.actualizar()\n\n def mark_add_next(self,duracion):\n \"\"\"Igual que MARKADD pero la inserta luego de la marca en la cual esta\n actualmente el cursor\n Parametros:\n duracion (float) duracion de la marca de tiempo\"\"\"\n mark = MarcaDeTiempo(duracion)\n self.tiempos.insert(self.tiempos.posicion_actual()+1,mark)\n self.tiempos.actualizar()\n\n def mark_add_prev(self,duracion):\n \"\"\"Igual que MARKADD pero la inserta antes de la marca en la cual esta\n actualmente el cursor\n Parametros:\n duracion (float) duracion de la marca de tiempo\"\"\"\n if not self.tiempos.posicion_actual():\n self.mark_add(duracion) # Si se encuentra en la posicion inicial no hay marca previa\n return\n mark = MarcaDeTiempo(duracion)\n self.tiempos.insert(self.tiempos.posicion_actual()-1, mark)\n self.tiempos.actualizar()\n\n def track_on(self,numero):\n \"\"\"Habilita al track durante la marca de tiempo en la cual esta parada el\n cursor. Si el track no existe lanza IndexError. Si no hay marca levanta AttributeError.\n Parametros:\n numero (int) Numero de track (o posicion)\"\"\"\n track = self.tracks[numero] #Para levantar una excepcion si no existe el track\n if not numero in self.tiempos.actual().obtener_habilitados():\n self.tiempos.actual().habilitar_track(numero)\n \n def track_off(self,numero):\n \"\"\"Deshabilita al track durante la marca de tiempo en la cual esta parada el\n cursor. Si el track no estaba habilitado, no hace nada. Si no hay marca levanta AttributeError.\n Parametros:\n numero (int) Numero de track (o posicion)\"\"\"\n if numero in self.tiempos.actual().obtener_habilitados():\n self.tiempos.actual().deshabilitar_track(numero)\n \n def play(self):\n \"\"\"Reproduce la marca en la que se encuentra el cursor actualmente. Si no hay marca no hace nada.\"\"\"\n if not self.tiempos.esta_vacia():\n self._reproducir(self.tiempos.actual())\n\n def play_all(self):\n \"\"\"Reproduce la cancion completa desde el inicio. Y vuelve a la posicion actual. Si no hay marca no hace nada.\"\"\"\n posicion_actual = self.tiempos.posicion_actual()\n self.tiempos.volver_al_inicio()\n while True:\n try:\n if not self.tiempos.esta_vacia():\n self._reproducir(self.tiempos.actual())\n self.tiempos.siguiente()\n except StopIteration:\n self.tiempos.volver_al_inicio()\n self.tiempos.actualizar(posicion_actual)\n return\n\n def play_marks(self,numero):\n \"\"\"Reproduce las proximas n marcas desde la posicion actual del cursor. Y vuelve a la posicion actual. Si no hay marca no hace nada.\n Parametros:\n numero (int) Numero de marcas a reproducir\"\"\"\n posicion_actual = self.tiempos.posicion_actual()\n try:\n for i in range(numero):\n if not self.tiempos.esta_vacia():\n self._reproducir(self.tiempos.actual())\n self.tiempos.siguiente()\n except StopIteration:\n pass\n self.tiempos.volver_al_inicio()\n self.tiempos.actualizar(posicion_actual) \n\n def play_seconds(self,segundos):\n \"\"\"Reproduce los proximos segundos la posicion actual del cursor. Y vuelve a la posicion actual. Si no hay marca no hace nada.\n Parametros:\n segundos (int) Segundos de marcas a reproducir\"\"\"\n suma_duracion = 0\n posicion_actual = self.tiempos.posicion_actual()\n while True:\n try:\n if not self.tiempos.esta_vacia():\n self._reproducir(self.tiempos.actual())\n suma_duracion += self.tiempos.actual().obtener_duracion()\n if suma_duracion >= segundos:\n break\n self.tiempos.siguiente()\n except StopIteration:\n break\n self.tiempos.volver_al_inicio()\n self.tiempos.actualizar(posicion_actual)\n \n def cant_tracks(self):\n \"\"\"Obtiene la cantidad de tracks cargados\"\"\"\n return len(self.tracks)\n \n def _reproducir(self,mark):\n \"\"\"Reproduce una marca de tiempo\"\"\"\n sp = pysounds.SoundPlayer(self.cant_tracks())\n duracion = mark.obtener_duracion()\n sonidos_a_reproducir = []\n for track_numero in mark.obtener_habilitados():\n track = self.tracks[track_numero]\n tipo = track.obtener_tipo()\n freq = track.obtener_frecuencia()\n vol = track.obtener_volumen()\n if tipo == \"sine\":\n sonidos_a_reproducir.append(pysounds.SoundFactory.get_sine_sound(freq,vol))\n if tipo == \"triangular\":\n sonidos_a_reproducir.append(pysounds.SoundFactory.get_triangular_sound(freq,vol))\n if tipo == \"square\":\n sonidos_a_reproducir.append(pysounds.SoundFactory.get_square_sound(freq,vol))\n sp.play_sounds(sonidos_a_reproducir, duracion)\n" }, { "alpha_fraction": 0.5852820873260498, "alphanum_fraction": 0.5865903496742249, "avg_line_length": 38.96731948852539, "blob_id": "4112d152b046a807a5aa9c0326578d160cc16c5f", "content_id": "ca4851eec1d282e3669999f80609c468e99b6e34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6117, "license_type": "no_license", "max_line_length": 126, "num_lines": 153, "path": "/Shell.py", "repo_name": "AlejandroKler/Sounds-of-Cyber-City", "src_encoding": "UTF-8", "text": "from Cancion import Cancion\nfrom ListaEnlazada import ListaEnlazada,_IteradorListaEnlazada\nimport cmd\n\nclass Shell(cmd.Cmd):\n intro = \"Bienvenido a Sounds of Cyber City.\\n Ingrese help o ? para listar los comandos.\\n\"\n prompt = \"Sounds of Cyber City: \"\n cancion = Cancion()\n def do_LOAD(self,file):\n \"\"\"Carga la cancion desde el archivo. Reemplaza la cancion en edicion\n actual si es que la hay.\"\"\"\n print(load_cancion(file,self))\n def do_STORE(self,name):\n \"\"\"Guarda la cancion\"\"\"\n if not name:\n print(\"Debe indicar el nombre\")\n return\n self.cancion.store(name)\n def do_STEP(self,params=None):\n \"\"\"Avanza a la siguiente marca de tiempo si la hay. Si no, no hace nada.\"\"\"\n self.cancion.step()\n def do_STEPM(self,n):\n \"\"\"Avanza N marcas de tiempo hacia adelante o las que pueda.\"\"\"\n if not is_numeric(n):\n return\n self.cancion.stepm(int(n))\n def do_BACK(self,params=None):\n \"\"\"Retrocede a la anterior marca de tiempo si puede.\"\"\"\n self.cancion.back()\n def do_BACKM(self,n):\n \"\"\"Retrocede N marcas de tiempo hacia atras o las que pueda.\"\"\"\n if not is_numeric(n):\n return\n self.cancion.backm(int(n))\n def do_TRACKADD(self,params):\n \"\"\"Agrega un track indicandole la funcion, la frecuencia y el volumen (separados por espacios).\"\"\"\n lista_parametros = params.split()\n if not len(lista_parametros) == 3:\n print(\"No ingreso los 3 parametros correctamente\")\n return\n funcion,frecuencia,volumen = lista_parametros\n if not is_numeric(frecuencia) or not is_numeric(volumen):\n return\n if float(volumen) < 0 or 1 < float(volumen):\n print(\"El volumen debe estar comprendido entre 0 y 1\")\n return\n try:\n self.cancion.track_add(funcion,int(frecuencia),float(volumen))\n except ValueError as e:\n print(e)\n def do_TRACKDEL(self,n):\n \"\"\"Elimina un track por numero\"\"\"\n if not is_numeric(n):\n return\n try:\n self.cancion.track_del(int(n))\n except IndexError:\n print('Este track no se encuentra en la canción')\n def do_MARKADD(self,duracion):\n \"\"\"Agrega una marca de tiempo de la duracion indicada.\"\"\"\n if not is_numeric(duracion):\n return\n self.cancion.mark_add(float(duracion))\n def do_MARKADDNEXT(self,duracion):\n \"\"\"Agrega una marca de tiempo de la duracion indicada en la posicion siguente\"\"\"\n if not is_numeric(duracion):\n return\n self.cancion.mark_add_next(float(duracion))\n def do_MARKADDPREV(self,duracion):\n \"\"\"Agrega una marca de tiempo de la duracion indicada en la posicion anterior\"\"\"\n if not is_numeric(duracion):\n return\n self.cancion.mark_add_prev(float(duracion))\n def do_TRACKON(self,n):\n \"\"\"Habilita al track durante la marca de tiempo actual\"\"\"\n if not is_numeric(n):\n return\n try:\n self.cancion.track_on(int(n))\n except IndexError:\n print('No existe tal track en la canción')\n except AttributeError:\n print(\"No hay marca\")\n def do_TRACKOFF(self,n):\n \"\"\"Desabilita al track durante la marca de tiempo actual\"\"\"\n if not is_numeric(n):\n return\n try:\n self.cancion.track_off(int(n))\n except AttributeError:\n print(\"No hay marca\")\n def do_PLAY(self,params=None):\n \"\"\"Reproduce la marca actual.\"\"\"\n self.cancion.play()\n def do_PLAYALL(self,params=None):\n \"\"\"Reproduce la cancion completa desde el inicio.\"\"\"\n self.cancion.play_all()\n def do_PLAYMARKS(self,n):\n \"\"\"Reproduce las proximas n marcas desde la posicion actual.\"\"\"\n if not is_numeric(n):\n return\n self.cancion.play_marks(int(n))\n def do_PLAYSECONDS(self,n):\n \"\"\"Reproduce los proximos segundos desde la posicion actual.\"\"\"\n if not is_numeric(n):\n return\n self.cancion.play_seconds(int(n))\n def actualizar_cancion(self,cancion):\n \"\"\"Actualiza la cancion de la Shell\"\"\"\n self.cancion = cancion\n\ndef is_numeric(cadena):\n \"\"\" Devuelve True si recibe una cadena numerica, False en otro caso. Imprime un mensaje de error si no recibe un numero\"\"\"\n if not cadena.replace('.','').isdigit():\n print(\"Ha ingresado un parametro incorrectamente\")\n return False\n return True\n\ndef load_cancion(file,shell=None):\n \"\"\"Carga la cancion desde el archivo. Reemplaza la cancion en edicion\n actual si es que la hay.\n Parametros:\n file (string) Debe tener el nombre del archivo junto con su extencion (.plp)\n shell (object) Objeto de la clase Shell para actualizar la cancion\"\"\"\n cancion = Cancion()\n primer_marca = True\n try:\n with open(file,\"r\") as f:\n for linea in f:\n campo,valor = linea.rstrip(\"\\n\").split(\",\")\n if campo == \"S\":\n funcion,frecuencia,volumen = valor.split(\"|\")\n cancion.track_add(funcion,int(frecuencia),float(volumen))\n elif campo == \"T\":\n duracion = float(valor)\n elif campo == \"N\":\n #Siempre hay un tipo 'T' antes, donde se define duracion\n if primer_marca:\n cancion.mark_add(duracion)\n else:\n cancion.mark_add_next(duracion)\n primer_marca = False\n cancion.step()\n for posicion,caracter in enumerate(valor):\n if caracter == \"#\":\n cancion.track_on(posicion)\n except IOError as e:\n return \"I/O error({0}): {1}\".format(e.errno, e.strerror)\n if shell:\n shell.actualizar_cancion(cancion) # Actualizamos el atributo del objeto shell\n return \"Cancion cargada con exito\"\n\nShell().cmdloop()\n" }, { "alpha_fraction": 0.5844594836235046, "alphanum_fraction": 0.5884340405464172, "avg_line_length": 36.55223846435547, "blob_id": "988baeef6692551ae3cde4cd649c3ac5a36892d7", "content_id": "f2cdb0eb52c198b8135445e51ac1d1d1c7b78511", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5042, "license_type": "no_license", "max_line_length": 174, "num_lines": 134, "path": "/ListaEnlazada.py", "repo_name": "AlejandroKler/Sounds-of-Cyber-City", "src_encoding": "UTF-8", "text": "from Pila import Pila\n\nclass _IteradorListaEnlazada():\n \"\"\"Itera una instancia de la clase ListaEnlazada\"\"\"\n def __init__(self, prim):\n self.actual = prim\n self.pila_auxiliar = Pila()\n self.posicion = 0\n def next(self):\n \"\"\"Avanza una posicion y devuelve el dato. Si no hay posicion siguiente lanza una excepcion StopIteration. Si no hay elemento lanza una excepcion AttributeError.\"\"\"\n if not self.actual.prox:\n raise StopIteration('No hay más elementos en la lista')\n nodo = self.actual\n self.pila_auxiliar.apilar(nodo)\n self.actual = self.actual.prox\n self.posicion += 1\n return self.actual.dato\n def prev(self):\n \"\"\"Retrocede una posicion y devuelve el dato. Si no hay posicion anterior lanza una excepcion StopIteration. Si no hay elemento lanza una excepcion AttributeError.\"\"\"\n if self.pila_auxiliar.esta_vacia():\n raise StopIteration('No hay elemento previo')\n nodo = self.pila_auxiliar.desapilar()\n self.actual = nodo\n self.posicion -= 1\n return self.actual.dato\n \nclass ListaEnlazada():\n def __init__(self):\n \"\"\"Crea una lista enlazada vacía.\"\"\"\n self.prim = None\n self.len = 0\n self.iterador = self.obtener_iterador()\n \n def pop(self, posicion = None):\n \"\"\" Elimina el nodo y devuelve el dato contenido.\n Si está fuera de rango, se lanza una excepcion IndexError.\n Si no se recibe la posición, devuelve el último elemento.\"\"\"\n if not posicion:\n posicion = self.len - 1\n if posicion < 0 or posicion >= self.len:\n raise IndexError('Indice fuera de rango')\n if posicion == 0:\n dato = self.prim.dato\n self.prim = self.prim.prox\n else:\n n_ant = self.prim\n n_act = n_ant.prox\n for pos in range (1, posicion):\n n_ant = n_act\n n_act = n_ant.prox\n dato = n_act.dato\n n_ant.prox = n_act.prox\n self.len -= 1\n return dato\n \n def append(self,dato):\n \"\"\"Agrega un elemento al final de la lista enlazada\"\"\"\n nuevo = _Nodo(dato)\n if self.len == 0:\n self.prim = nuevo\n elif self.len == 1:\n self.prim.prox = nuevo\n else:\n n_act = self.prim\n for pos in range(1,self.len):\n n_act = n_act.prox\n n_act.prox = nuevo\n self.len += 1\n \n def insert(self, posicion, dato):\n \"\"\"Inserta el dato en la posición indicada.\n Si la posición es inválida, lanza una excepcion IndexError\"\"\"\n if posicion < 0 or posicion > self.len:\n raise IndexError(\"Posición inválida\")\n nuevo = _Nodo(dato)\n if posicion == 0:\n nuevo.prox = self.prim\n self.prim = nuevo\n else:\n n_ant = self.prim\n for pos in range(1, posicion):\n n_ant = n_ant.prox\n nuevo.prox = n_ant.prox\n n_ant.prox = nuevo\n self.len += 1\n\n def esta_vacia(self):\n \"\"\"Devuelve true si la lista no tiene ningun elemento\"\"\"\n return (self.len == 0)\n\n def obtener_iterador(self):\n \"\"\" Devuelve el iterador de la lista. \"\"\"\n return _IteradorListaEnlazada(self.prim)\n\n def siguiente(self):\n \"\"\"Avanza al siguiente elemento y lo devuelve. Si no hay marca o es la ultima, lanza una excepcion StopIteration\"\"\"\n try:\n return self.iterador.next()\n except AttributeError:\n raise StopIteration \n \n def anterior(self):\n \"\"\"Retrocede al anterior elemento y lo devuelve. Si no hay marca o es la primera, lanza una excepcion StopIteration\"\"\"\n try:\n return self.iterador.prev()\n except AttributeError:\n raise StopIteration \n\n def actual(self):\n \"\"\"Devuelve el dato en la posicion actual del iterador. Si hay elemento, lanza una excepcion AttributeError.\"\"\"\n return self.iterador.actual.dato\n\n def volver_al_inicio(self):\n \"\"\"Vuelve el iterador a la posicion inicial\"\"\"\n self.iterador = self.obtener_iterador()\n\n def actualizar(self,desplazamiento=0):\n \"\"\" Reinicia el iterador y mueve el cursor a la posicion anterior (por defecto) o a la posicion indicada por parametro.\n Recibe un parametro desplazamiento que indica el desplazamiento con repecto a la posicion anterior\"\"\"\n posicion = self.iterador.posicion\n self.iterador = self.obtener_iterador()\n for i in range(posicion + desplazamiento):\n if i < (self.len - 1):\n self.iterador.next()\n\n def posicion_actual(self):\n \"\"\"Devuelve la posicion actual del iterador\"\"\"\n return self.iterador.posicion\n\nclass _Nodo():\n \"\"\"Un nodo contiene un dato y una referencia al proximo\"\"\"\n def __init__(self, dato, prox = None):\n self.dato = dato\n self.prox = prox\n" } ]
9
wen-liao/leetcode
https://github.com/wen-liao/leetcode
cf5230edfdb44a3a324c1dcd488a01c631a2f538
af5bb2106105ac8990fff9e426bde4b05113d38d
233deb4e573b97f4e9cd8503245953c755cd7e19
refs/heads/master
2020-04-18T07:40:39.499411
2019-02-14T12:55:51
2019-02-14T12:55:51
167,368,325
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.45627376437187195, "alphanum_fraction": 0.46768060326576233, "avg_line_length": 28.33333396911621, "blob_id": "ddfd0e1b8546dc2afce35c4b463ee3feb76e0040", "content_id": "0346fdbfa88fcd88663dcf84169c05d51755b5a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 263, "license_type": "no_license", "max_line_length": 71, "num_lines": 9, "path": "/初级算法/字符串/反转字符串.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution:\n def reverseString(self, s):\n \"\"\"\n :type s: List[str]\n :rtype: void Do not return anything, modify s in-place instead.\n \"\"\"\n n = len(s)//2\n for i in range(n):\n s[i],s[-(i+1)] = s[-(i+1)],s[i]" }, { "alpha_fraction": 0.33786407113075256, "alphanum_fraction": 0.3621359169483185, "avg_line_length": 24.774999618530273, "blob_id": "e889cbd23086934498b40d749d2d33949d941351", "content_id": "4a7351ba67b9eb7fd59f5c5bfa8b160037206f3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 55, "num_lines": 40, "path": "/初级算法/字符串/字符串转换函数(atoi).py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution:\n def myAtoi(self, string):\n \"\"\"\n :type str: str\n :rtype: int\n \"\"\"\n INT_MAX = (1<<31) - 1\n INT_MIN = -(1<<31)\n string = string.strip()\n N = len(string)\n if N == 0:\n return 0\n sign = 1\n value = 0\n i = 0\n if string[0] == '-':\n if len(string) > 1 and string[1].isdigit():\n sign = -1\n i += 1\n else:\n return 0\n elif string [i] == '+':\n if len(string) > 1 and string[1].isdigit():\n i += 1\n else:\n return 0\n while i < N:\n if string[i].isdigit():\n value = value*10 + int(string[i])\n i += 1\n if value > INT_MAX:\n break\n else:\n break\n value *= sign\n if value < INT_MIN:\n return INT_MIN\n if value > INT_MAX:\n return INT_MAX\n return value" }, { "alpha_fraction": 0.5247376561164856, "alphanum_fraction": 0.5292353630065918, "avg_line_length": 25.719999313354492, "blob_id": "9f017c593d09d9dc3dad38500164f332e94d74d1", "content_id": "ee4fe2c402c0e2ef4c7aac74963ab702815f072f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "no_license", "max_line_length": 42, "num_lines": 25, "path": "/初级算法/树/二叉树的层次遍历.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def traversal(self,depth,root):\n if root == None:\n return\n if len(self.ret) <= depth:\n self.ret.append([])\n self.ret[depth].append(root.val)\n self.traversal(depth+1, root.left)\n self.traversal(depth+1,root.right)\n \n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n self.ret = []\n self.traversal(0,root)\n return self.ret" }, { "alpha_fraction": 0.28913044929504395, "alphanum_fraction": 0.321739137172699, "avg_line_length": 23.263158798217773, "blob_id": "5248996b681c3141222da6c7cca773d0d4e7ceee", "content_id": "140ce83b93c11f46a50a8bfd53d353b37612d14d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "no_license", "max_line_length": 38, "num_lines": 19, "path": "/初级算法/数学/计数质数.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution(object):\n def countPrimes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n == 0 or n == 1 or n == 2:\n return 0\n rec = [1]*n\n rec[0],rec[1] = 0,0\n count = 0\n for i in range(2,n):\n if rec[i] == 1:\n count += 1\n j = 2*i\n while j < n:\n rec[j] = 0\n j += i\n return count" }, { "alpha_fraction": 0.4351464509963989, "alphanum_fraction": 0.4476987421512604, "avg_line_length": 23, "blob_id": "6d564402bf35632b2410548a6bf788bdf09006f9", "content_id": "5bd09c99e16f70b4b82d93399790dfec8fec8d80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 48, "num_lines": 10, "path": "/初级算法/其他/缺失数字.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution:\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n sum_ = 0\n for val in nums:\n sum_ += val\n return len(nums)*(len(nums)+1)//2 - sum_" }, { "alpha_fraction": 0.41403865814208984, "alphanum_fraction": 0.43743643164634705, "avg_line_length": 25.594594955444336, "blob_id": "98e74d7cefa9e034ea58bb81860e9e25e219f47a", "content_id": "64034f32e9ef3edcd57ae4572ccc4b206c03ac51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 983, "license_type": "no_license", "max_line_length": 57, "num_lines": 37, "path": "/初级算法/链表/回文链表.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n if head == None or head.next == None:\n return True\n l1 = head\n N = 0\n while l1 != None:\n l1 = l1.next\n N += 1\n l1 = head\n for i in range(int((N+1)/2)):\n l1 = l1.next\n l2,head = head,l1\n \n #now @head is the head of the list to be reversed\n if int(N/2) > 1:\n p,q = head,head.next\n p.next,q.next,p,q = None,p,q,q.next\n while q != None:\n q.next,p,q = p,q,q.next\n l1 = p\n \n for i in range(int(N/2)):\n if not l1.val == l2.val:\n return False\n l1,l2 = l1.next,l2.next\n return True" }, { "alpha_fraction": 0.3641488254070282, "alphanum_fraction": 0.36978578567504883, "avg_line_length": 27.645160675048828, "blob_id": "7bd04a7fb2cb9340a89e3612023389fe71ded7f9", "content_id": "a6d69b20db8cdcabbd18257fa40e8475547faa9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 74, "num_lines": 31, "path": "/初级算法/数组/旋转数组.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution:\n def rotate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n if (len(nums) == 0) or (k == 0):\n return\n #gcd(len(nums),k)\n gcd,temp = len(nums),k\n while (gcd != 0) and (temp != 0):\n if gcd > temp:\n gcd %= temp\n else:\n temp %= gcd\n if gcd == 0:\n gcd = temp\n \n def switch(ix,k,nums):\n temp = nums[ix]\n N = len(nums)\n nums[ix] = nums[(ix + N - k)%N]\n j = (ix + N - k)%N\n while j != ix:\n nums[j] = nums[(j + N - k)%N]\n j = (j + N - k)%N\n nums[(ix + k)%N] = temp\n \n for i in range(gcd):\n switch(i,k,nums)" }, { "alpha_fraction": 0.4174528419971466, "alphanum_fraction": 0.4599056541919708, "avg_line_length": 24, "blob_id": "999eada12711c3acd482fc7c9a7e73866004881c", "content_id": "7e20fb2367c15b27d196b9fb1b416e0cfefd94c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "no_license", "max_line_length": 44, "num_lines": 17, "path": "/初级算法/链表/合并两个有序链表.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution(object):\n def mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n if l1 == None:\n return l2\n if l2 == None:\n return l1\n if l1.val <= l2.val:\n ret,l1 = l1,l1.next\n else:\n ret,l2 = l2,l2.next\n ret.next = self.mergeTwoLists(l1,l2)\n return ret" }, { "alpha_fraction": 0.5285524725914001, "alphanum_fraction": 0.5471447706222534, "avg_line_length": 29.15999984741211, "blob_id": "582252fabe179d9b576baca35701e5922c2fe9ab", "content_id": "dfd5b6decd256386d4a9023765f42962fe1cf49c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 753, "license_type": "no_license", "max_line_length": 90, "num_lines": 25, "path": "/初级算法/树/对称二叉树.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def compare(self,root1, root2):\n if root1 == None and root2 == None:\n return True\n if (root1 == None and root2 != None) or (root1 != None and root2 == None):\n return False\n if root1.val != root2.val:\n return False\n if self.compare(root1.left,root2.right) and self.compare(root1.right, root2.left):\n return True\n return False\n \n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n return self.compare(root,root)" }, { "alpha_fraction": 0.4890219569206238, "alphanum_fraction": 0.4980039894580841, "avg_line_length": 29.393939971923828, "blob_id": "6a39ef213617ff997d4cfb296d797255d3042038", "content_id": "7a85a964c0d4b17997745d174dce7844da82e529", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 60, "num_lines": 33, "path": "/初级算法/树/将有序数组转换为二叉搜索树.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def build(self, nums, index, root):\n if index > 0:\n l_index = index // 2\n root.left = TreeNode(nums[l_index])\n self.build(nums[:index],l_index,root.left)\n else:\n root.left = None\n if index < len(nums) - 1:\n r_index = (len(nums) - 1 - index) // 2\n root.right = TreeNode(nums[r_index + index + 1])\n self.build(nums[index+1:],r_index,root.right)\n else:\n root.right = None\n \n def sortedArrayToBST(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n if len(nums) == 0:\n return None\n index = len(nums) // 2\n self.ret = TreeNode(nums[index])\n self.build(nums, index, self.ret)\n return self.ret" }, { "alpha_fraction": 0.3276231288909912, "alphanum_fraction": 0.35331904888153076, "avg_line_length": 22.399999618530273, "blob_id": "f9d6ba86e7f96403ffb86e850721b6d8a1718b33", "content_id": "ab0d6637eb082a18d81a2525044080f6b96f27f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 467, "license_type": "no_license", "max_line_length": 35, "num_lines": 20, "path": "/初级算法/数组/加一.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution:\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n #x[N-1-i]\n r = 1\n N = len(digits)\n for i in range(N):\n digits[N-1-i] += r\n r = 0\n if digits[N-1-i] > 9:\n digits[N-1-i] -= 10\n r = 1\n else:\n break\n if r == 1:\n digits = [1] + digits\n return digits" }, { "alpha_fraction": 0.45628416538238525, "alphanum_fraction": 0.46721312403678894, "avg_line_length": 25.214284896850586, "blob_id": "bbd8d11a54e7fd30aa6a4c857e37683eacccbaac", "content_id": "b598a800dd0d7f61367a7830d6cf7558ae1586ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "no_license", "max_line_length": 44, "num_lines": 14, "path": "/初级算法/动态规划/买卖股票的最佳时机.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if len(prices) == 0:\n return 0\n least = prices[0]\n ret = 0\n for i in range(len(prices)):\n least = min(least,prices[i])\n ret = max(ret,prices[i] - least)\n return ret" }, { "alpha_fraction": 0.4984709620475769, "alphanum_fraction": 0.5076452493667603, "avg_line_length": 28.81818199157715, "blob_id": "408ae20a16f5d3f260f834f42361679de689f75b", "content_id": "08890d3eac950bf77f61c6bcc7e80d48f8032ace", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "no_license", "max_line_length": 71, "num_lines": 11, "path": "/初级算法/动态规划/打家劫舍.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution(object):\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n ret,steal,not_steal = 0,0,0\n for i in range(len(nums)):\n steal,not_steal = not_steal + nums[i], max(steal,not_steal)\n ret = max(ret,steal,not_steal)\n return ret" }, { "alpha_fraction": 0.548828125, "alphanum_fraction": 0.5546875, "avg_line_length": 24.649999618530273, "blob_id": "a495df9c736d7edf682ad7e3ac8829874469cdbc", "content_id": "330a7811399d4983e0a07c333ddd0e574a496064", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "no_license", "max_line_length": 50, "num_lines": 20, "path": "/初级算法/排序和搜索/第一个错误的版本.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "# The isBadVersion API is already defined for you.\n# @param version, an integer\n# @return a bool\n# def isBadVersion(version):\n\nclass Solution(object):\n def find(self,begin,end):\n if begin == end:\n return begin\n mid = (begin+end)//2\n if isBadVersion(mid):\n return self.find(begin,mid)\n else:\n return self.find(mid+1,end)\n def firstBadVersion(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return self.find(1,n)" }, { "alpha_fraction": 0.37748345732688904, "alphanum_fraction": 0.39403972029685974, "avg_line_length": 27.809524536132812, "blob_id": "27c897cf49c40ce8fd48770c05f381404c813aac", "content_id": "9c80f7bf3b4a77077d7341a1ac63c178c28114b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 48, "num_lines": 21, "path": "/初级算法/字符串/最长公共前缀.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if len(strs) == 0:\n return \"\"\n if len(strs) == 1:\n return strs[0]\n max_len = len(strs[0])\n for i in range(1, len(strs)):\n max_len = min(max_len, len(strs[i]))\n if max_len == 0:\n return \"\"\n for j in range(max_len):\n if strs[i-1][j] != strs[i][j]:\n j -= 1\n break\n max_len = j + 1\n return strs[0][:max_len]" }, { "alpha_fraction": 0.3426573574542999, "alphanum_fraction": 0.36713287234306335, "avg_line_length": 21.076923370361328, "blob_id": "b42ef75e226017e58c9dea749e519a689ebc7a30", "content_id": "87d8f5dc6c30633875245a92da284c9e606900d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 286, "license_type": "no_license", "max_line_length": 36, "num_lines": 13, "path": "/初级算法/其他/Hamilton距离.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution(object):\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n ret = 0\n while x > 0 or y > 0:\n ret += int(x%2 != y%2)\n x //= 2\n y //= 2\n return ret" }, { "alpha_fraction": 0.4880174398422241, "alphanum_fraction": 0.5119825601577759, "avg_line_length": 40.818180084228516, "blob_id": "86cfc479d92cdd071173e78c90d2afaecd788998", "content_id": "40b5f1c859b508fe27e84c7ed88c577ff63921e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 169, "num_lines": 11, "path": "/初级算法/数组/旋转图像.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution:\n def rotate(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: void Do not return anything, modify matrix in-place instead.\n \"\"\"\n N = len(matrix)\n n = N//2\n for i in range(n):\n for j in range(N-1-2*i):\n matrix[i][i+j],matrix[i+j][N-1-i],matrix[N-1-i][N-1-j-i],matrix[N-1-j-i][i] = matrix[N-1-j-i][i],matrix[i][i+j],matrix[i+j][N-1-i],matrix[N-1-i][N-1-j-i]" }, { "alpha_fraction": 0.34328359365463257, "alphanum_fraction": 0.3987206816673279, "avg_line_length": 30.33333396911621, "blob_id": "1dab31fdf0cdb3febe2b0ea513522a1ddc9e70e8", "content_id": "0ea74a349bbcd9efe76220200866353f8148e18a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 469, "license_type": "no_license", "max_line_length": 68, "num_lines": 15, "path": "/初级算法/数学/罗马数字转整数.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution(object):\n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n priority = {\"I\":0,\"V\":1,\"X\":2,\"L\":3,\"C\":4,\"D\":5,\"M\":6}\n value = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000}\n ret = 0\n for i in range(len(s)):\n if i < len(s)-1 and priority[s[i]]<priority[s[i+1]]:\n ret -= value[s[i]]\n else:\n ret += value[s[i]]\n return ret" }, { "alpha_fraction": 0.26980727910995483, "alphanum_fraction": 0.31477516889572144, "avg_line_length": 19.34782600402832, "blob_id": "88f6eaa8bc22a210d9fe7e64e1232746f2e5aa97", "content_id": "21701f1eae0d73d13e941152850ec508e903e55a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 467, "license_type": "no_license", "max_line_length": 31, "num_lines": 23, "path": "/初级算法/字符串/整数反转.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n MIN = -(1<<31)\n MAX = (1<<31)-1\n sign = 1\n if x == 0:\n return 0\n if x < 0:\n sign = -1\n x = -x\n ret = 0\n while x > 0:\n ret = ret*10 + x%10\n x //= 10\n ret *= sign\n if MIN <= ret <= MAX:\n return ret\n else:\n return 0" }, { "alpha_fraction": 0.37617555260658264, "alphanum_fraction": 0.4106582999229431, "avg_line_length": 25.625, "blob_id": "67210deacab662f5bd6941d857e03a2e9325e138", "content_id": "b5b46ea233f8b790d21856e5a4c805ddadd45a22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 638, "license_type": "no_license", "max_line_length": 53, "num_lines": 24, "path": "/初级算法/数组/两个数组的交集 II.py", "repo_name": "wen-liao/leetcode", "src_encoding": "UTF-8", "text": "class Solution:\n def intersect(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n dict1 = {}\n dict2 = {}\n for num in nums1:\n if num in dict1:\n dict1[num] += 1\n else:\n dict1[num] = 1\n for num in nums2:\n if num in dict2:\n dict2[num] += 1\n else:\n dict2[num] = 1\n common = dict1.keys() & dict2.keys()\n ret = []\n for val in common:\n ret += [val] * min(dict1[val],dict2[val])\n return ret" } ]
20
liampingu/project-euler-starters
https://github.com/liampingu/project-euler-starters
ea2a7679863accf65c7836eb6ea75abed2452f3d
bd14b9338711cbdd85f7a5cb0dcd19d7a9b08d33
8fbe915b3e43a1c8d89412be66bfe5ad6b325821
refs/heads/master
2020-09-30T07:42:50.952584
2019-12-19T06:31:04
2019-12-19T06:31:04
227,242,782
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5597484111785889, "alphanum_fraction": 0.5807127952575684, "avg_line_length": 17.346153259277344, "blob_id": "de8130e9d572e6b7cc1603eb5997fbf44030e74c", "content_id": "0127246acc5f3de9d22b1881ed3ba7c257f832dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 477, "license_type": "no_license", "max_line_length": 76, "num_lines": 26, "path": "/problem007.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# prints 6th prime number\n\n# is this efficient? have you heard of the sieve of erathosthenes method for\n# finding lots of primes?\n\ndef is_prime(x):\n if x < 2:\n return False\n for factor in range(2, x):\n if x % factor == 0:\n return False\n return True\n\nnumber = 2\nprime_count = 0\n\nwhile True:\n if is_prime(number):\n prime_count += 1\n if prime_count == 6:\n break\n number += 1\n \nprint(number)\n" }, { "alpha_fraction": 0.5853658318519592, "alphanum_fraction": 0.6219512224197388, "avg_line_length": 17.16666603088379, "blob_id": "f2d009464d9ef428523c7055231e00166845694f", "content_id": "6ba159a6604c6901f8c19ff859dd7869c27b166c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "no_license", "max_line_length": 48, "num_lines": 18, "path": "/problem002.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# prints sum of even fibonacci numbers under 100\n\nprevious_num = 1\ncurrent_num = 2\ntotal = 0\n\nwhile current_num <= 100:\n\n if current_num % 2 == 0:\n total += current_num\n \n next_num = previous_num + current_num\n previous_num = current_num\n current_num = next_num\n \nprint(total)\n\n" }, { "alpha_fraction": 0.6294766068458557, "alphanum_fraction": 0.6570248007774353, "avg_line_length": 22.419355392456055, "blob_id": "3ef6f947126968420f884c655bc55782db43506d", "content_id": "b0b32027d3eef0e1d4c28e5061e367534fc226a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 726, "license_type": "no_license", "max_line_length": 86, "num_lines": 31, "path": "/stopwatch.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# to time how long it takes your code to run, enter the problem number here\n# and then run this file\n\nproblem_num = 1\n\n\n\n\nimport time, sys, os\n\nif len(sys.argv) == 2:\n problem_num = int(sys.argv[1])\n \nmodule_name = \"problem{:03}\".format(problem_num)\nfile_name = module_name + '.py'\nif not os.path.isfile(file_name):\n print(\"[!] file '{}' doesn't exist!\".format(file_name))\n exit()\n\nprint(\"[*] running {}...\".format(module_name))\nstart_time = time.time()\n__import__(module_name)\nend_time = time.time()\nprint(\"[*] code finished!\")\n\nelapsed_time = end_time - start_time\nmilliseconds = int(elapsed_time*1000)\n\nprint(\"[*] time taken: {}s {:03}ms\".format(int(milliseconds/1000), milliseconds%1000))\n" }, { "alpha_fraction": 0.35091742873191833, "alphanum_fraction": 0.39449542760849, "avg_line_length": 11.79411792755127, "blob_id": "4940ee26506978fdcf4fac6e040db3db20213a74", "content_id": "be631c8bef1b7b7ff5c955690121dfe0e8800f62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 25, "num_lines": 34, "path": "/problem045.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\nimport math\n\ndef tri(n):\n return n*n + n\n \ndef pent(n):\n return 3*n*n - n\n \ndef hexa(n):\n return 4*n*n - 2*n\n \nt = 285 + 1\np = 165\nh = 143\n\nT = tri(t)\nP = 0\nH = 0\n\nwhile True:\n if P < T:\n p += 1\n P = pent(p)\n if H < T:\n h += 1\n H = hexa(h)\n while T < P or T < H:\n t += 1\n T = tri(t)\n if T == P and T == H:\n print(int(T))\n break\n\n" }, { "alpha_fraction": 0.4043583571910858, "alphanum_fraction": 0.4527845084667206, "avg_line_length": 19.649999618530273, "blob_id": "acf2b8868eda80a6e8243e4d9c3f38ee2847168f", "content_id": "87ccbc0539c8d7918d7256fbe3fb237fb8d49f77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "no_license", "max_line_length": 51, "num_lines": 20, "path": "/problem039.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\nimport math\n\nmax_count = 0\nmax_p = 120\n\nfor p in range(121, 1001):\n count = 0\n for a in range(1, math.ceil(p/3)):\n for b in range(a, math.ceil(p/2)):\n c = p - a - b\n if a**2 + b**2 == c**2:\n count += 1\n if count > max_count:\n print('p={} ==> count={}'.format(p, count))\n max_count = count\n max_p = p\n \nprint(p)\n" }, { "alpha_fraction": 0.6595744490623474, "alphanum_fraction": 0.7872340679168701, "avg_line_length": 10.75, "blob_id": "b75f04ad6b28e2bef9a115dc239a88269ca6142f", "content_id": "7fd4bb03830f2f9ba16620a12b1b7bdfb69c73c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 47, "license_type": "no_license", "max_line_length": 26, "num_lines": 4, "path": "/problem247/run.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "import problem247\n\n\nprint(problem247.result())\n" }, { "alpha_fraction": 0.5545454621315002, "alphanum_fraction": 0.6090909242630005, "avg_line_length": 19, "blob_id": "62bf4a4de582d84ce625889c1b35fd5797bee4f8", "content_id": "7009386638cebcf611dbfea67805b1bd442e49a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "no_license", "max_line_length": 72, "num_lines": 11, "path": "/problem001.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# prints sum of number numbers less than 10 that are multiples of 3 or 5\n\ntotal = 0\n\nfor number in range(10):\n if number % 3 == 0 or number % 5 == 0:\n total += number\n \nprint(total)\n" }, { "alpha_fraction": 0.5969529151916504, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 30.30434799194336, "blob_id": "7de1664962cbbc3ac2550545105ccc409bb9269c", "content_id": "6e915815c34003e20efea6094cf303aaf07cc102", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 722, "license_type": "no_license", "max_line_length": 94, "num_lines": 23, "path": "/problem240.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "import math\nmax_perms = math.factorial(20)\n\n# run = number of previous rolls of the same value\n# div = factor by which to reduce dice permutations to avoid double counting\ndef f(num_dice, num_summed, max_value, value_sum, div=1, run=0):\n\n if num_dice == 0:\n return round(max_perms / div)\n \n total = 0\n it = range(1, max_value+1)\n if num_summed > 0:\n it = range(math.ceil(value_sum/num_summed), min(value_sum-num_summed+2,max_value+1))\n for val in it: \n if val == max_value:\n total += f(num_dice-1, num_summed-1, val, value_sum-val, div = div*(run+1), run = run+1)\n else:\n total += f(num_dice-1, num_summed-1, val, value_sum-val, div = div)\n \n return total\n\nprint(f(20, 10, 12, 70))\n\n\n" }, { "alpha_fraction": 0.5806451439857483, "alphanum_fraction": 0.6254480481147766, "avg_line_length": 21.31999969482422, "blob_id": "eb1e52bb063dd3a3620620d0696cd91dfe59e40b", "content_id": "760506e9fb46fd5928e0dd50aff3313195f87082", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "no_license", "max_line_length": 78, "num_lines": 25, "path": "/problem012.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# prints first triangle number to have over 5 divisors\n\n# is it efficient? to find all the divisors of 100, do you really need to test\n# 51, 52, 53 ... 100? Do you really need to test anything over 10?\n\ndef number_of_divisors(x):\n count = 0\n for divisor in range(1, x+1):\n if x % divisor == 0:\n count += 1\n return count\n \nnumber = 1\ntriangle_number = 1\n\nwhile True:\n if number_of_divisors(triangle_number) > 5:\n break\n \n number += 1\n triangle_number += number\n \nprint(triangle_number)\n" }, { "alpha_fraction": 0.40606653690338135, "alphanum_fraction": 0.42270058393478394, "avg_line_length": 21.399999618530273, "blob_id": "e126a5fc28d6c0734f2af979fdf8410af07de977", "content_id": "799d389f2303ec2963351e514cdaccc87df84ae6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1022, "license_type": "no_license", "max_line_length": 65, "num_lines": 45, "path": "/problem044.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\nimport math\n\n# nth pentagonal number\ndef P(n):\n return (3*n*n-n)/2\n\n# inverse function\ndef N(p):\n n = math.floor((1 + math.sqrt(1 + 24*p))/6)\n if P(n) == p:\n return n\n return None\n\n# main\nn_diff = 1400\nwhile True:\n print('trying n_diff = {}'.format(n_diff))\n p_diff = P(n_diff)\n \n n_small = 1\n while True:\n p_small = P(n_small)\n \n p_big = p_small + p_diff\n if p_big < P(n_small+1):\n break\n n_big = N(p_big)\n if n_big == None:\n n_small += 1\n continue\n \n p_sum = p_big + p_small\n n_sum = N(p_sum)\n if n_sum != None:\n print('diff: P({}) ==> {}'.format(n_diff, p_diff))\n print('small: P({}) ==> {}'.format(n_small, p_small))\n print('big: P({}) ==> {}'.format(n_big, p_big))\n print('sum: P({}) ==> {}'.format(n_sum, p_sum))\n exit()\n \n n_small += 1\n \n n_diff += 1\n \n \n" }, { "alpha_fraction": 0.5816733241081238, "alphanum_fraction": 0.6155378222465515, "avg_line_length": 19.91666603088379, "blob_id": "ce9c2f82255a02ef36925f363f04207a67f816ba", "content_id": "896e8f4301f0dc0084fd07be6d3d74754c4fe55d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 502, "license_type": "no_license", "max_line_length": 81, "num_lines": 24, "path": "/problem003.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# prints largest prime factor of 13195\n\n# is this efficient? there seems to be a lot of unnecessary divisibility testing,\n# both in the is_prime() function and the main code.\n\nnum = 13195\n\ndef is_prime(x):\n if x < 2:\n return False\n for factor in range(2, x):\n if x % factor == 0:\n return False\n return True\n\nlargest_factor = 1\n\nfor i in range(1, num):\n if num % i == 0 and is_prime(i):\n largest_factor = i\n \nprint(largest_factor)\n" }, { "alpha_fraction": 0.42020201683044434, "alphanum_fraction": 0.5191919207572937, "avg_line_length": 26.5, "blob_id": "8ee9110a033efc194adc4c80738b14a4bde47c92", "content_id": "4473265f6d423d05c90440934ed3a3b9a18e3cd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 495, "license_type": "no_license", "max_line_length": 67, "num_lines": 18, "path": "/problem009.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# prints product of pythagorean triplets whose elements sum to 1000\n\n# is this efficient? it seems to check the 3-4-5 triplet 6 times!\n# (3-4-5, 3-5-4, 4-3-5, 4-5-3, 5-3-4, 5-4-3)\n\ndef get_answer():\n for a in range(1, 1000):\n for b in range(1, 1000):\n for c in range(1, 1000):\n if a + b + c == 1000:\n if a**2 + b**2 == c**2:\n return a*b*c\n return None\n \nanswer = get_answer()\nprint(answer)\n" }, { "alpha_fraction": 0.48236513137817383, "alphanum_fraction": 0.5466805100440979, "avg_line_length": 25.75, "blob_id": "f93761c3fd9b81112e97a89d38c8c4fa99158264", "content_id": "50507e4d729c47143092186e3599522e9183dabc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 964, "license_type": "no_license", "max_line_length": 78, "num_lines": 36, "path": "/problem247/problem247.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "\nimport math\n\n# largest square to fit under x0,y0 curve: y+y0 = 1/(x+x0)\ndef square(x0, y0):\n b = x0 + y0\n c = x0*y0 - 1.0\n return (-b + math.sqrt(b**2 - 4.0*c)) / 2.0\n\n# follow 'RUU' style string to get size of square found by going right then up\ndef get_size(directions, x0, y0):\n s = square(x0, y0)\n if len(directions) == 0:\n return s\n if directions.pop(0) == 'U':\n return get_size(directions, x0, y0+s)\n return get_size(directions, x0+s, y0)\n \n# num of squares smaller than s0 that fit under x0,y0 curve\ndef count_squares(s0, x0, y0):\n s = square(x0, y0)\n total = 0\n while s > s0:\n above = count_squares(s0, x0, y0+s)\n if above == 0:\n break\n total += 1 + above\n x0 += s\n s = square(x0, y0)\n while s > s0:\n total += 1\n x0 += s\n s = square(x0, y0)\n return total\n\ns0 = get_size(list('RRRUUU'), 1.0, 0.0)\nprint(1 + count_squares(s0, 1.0, 0.0))\n" }, { "alpha_fraction": 0.5877862572669983, "alphanum_fraction": 0.6297709941864014, "avg_line_length": 23.619047164916992, "blob_id": "42648b19fe271b9004777328eaf22b38a1d98437", "content_id": "0b7e4ba2a60caa811f3994be8f243bc3d77384f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 524, "license_type": "no_license", "max_line_length": 72, "num_lines": 21, "path": "/problem004.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# prints largest palindromic multiple of two 2 digit numbers\n\n# is this efficient? it seems to test things twice (12 * 34 and 34 * 12)\n\ndef is_palindromic(number):\n string_forwards = str(number)\n string_backwards = string_forwards[::-1]\n if string_forwards == string_backwards:\n return True\n return False\n\nlargest = 0\n\nfor x in range(10, 100):\n for y in range(10, 100):\n if is_palindromic(x*y) and x*y > largest:\n largest = x*y\n \nprint(largest) \n" }, { "alpha_fraction": 0.5409836173057556, "alphanum_fraction": 0.5737704634666443, "avg_line_length": 20.217391967773438, "blob_id": "fee5b823efac7f26ef3cc25dafdcb14cc44d1100", "content_id": "511c1091e1149cb644d658599c6627a90f83bd00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 488, "license_type": "no_license", "max_line_length": 46, "num_lines": 23, "path": "/problem042.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\nimport math\n\ndef is_triangle_number(value):\n value *= 2\n root = int(math.sqrt(value))\n if root * (root + 1) == value:\n return True\n return False\n\nwith open('problem042-words.txt', 'r') as f:\n words = [x for x in f.read().split('\",\"')]\nwords[0] = words[0][1:]\nwords[-1] = words[-1][:-1]\n\ncount = 0\nfor word in words:\n value = sum([ord(x)-64 for x in word])\n if is_triangle_number(value):\n print(word)\n count += 1\nprint(count)\n" }, { "alpha_fraction": 0.5758293867111206, "alphanum_fraction": 0.5971564054489136, "avg_line_length": 18.18181800842285, "blob_id": "47ac7f7298fe2a39a3dca2dc2307b684bbb4716f", "content_id": "67f3217fe49544063f598db791432ca6f8b01402", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 422, "license_type": "no_license", "max_line_length": 76, "num_lines": 22, "path": "/problem010.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# prints sum of primes below 10\n\n# is this efficient? have you heard of the sieve of erathosthenes method for\n# finding lots of primes?\n\ndef is_prime(x):\n if x < 2:\n return False\n for factor in range(2, x):\n if x % factor == 0:\n return False\n return True\n \ntotal = 0\n\nfor number in range(10):\n if is_prime(number):\n total += number\n \nprint(total)\n" }, { "alpha_fraction": 0.5505464673042297, "alphanum_fraction": 0.5696721076965332, "avg_line_length": 23.399999618530273, "blob_id": "39b4f6322d4cf474e11387ffb406d8db0392ac27", "content_id": "7de42b63178165d73e8e205a6ca1b704ee5cb4d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 732, "license_type": "no_license", "max_line_length": 55, "num_lines": 30, "path": "/problem041.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\nimport math\n\ndef is_prime(num):\n for i in range(2, math.floor(math.sqrt(num))):\n if num % i == 0:\n return False\n return True\n\ndef test(selected):\n num = int(''.join([str(x) for x in selected]))\n if is_prime(num):\n print(num)\n exit()\n\ndef iterate(selected, remaining):\n if len(remaining) == 0:\n test(selected)\n else:\n for i in range(len(remaining)):\n selected_copy = selected.copy()\n remaining_copy = remaining.copy()\n selected_copy.append(remaining_copy.pop(i))\n iterate(selected_copy, remaining_copy)\n\nremaining = [9, 8, 7, 6, 5, 4, 3, 2, 1]\nwhile True:\n iterate([], remaining)\n remaining.pop(0)\n" }, { "alpha_fraction": 0.44470587372779846, "alphanum_fraction": 0.48941177129745483, "avg_line_length": 17.478260040283203, "blob_id": "eb03a7d18375987afabac131f7b300dad02eb829", "content_id": "fa4b1ee0e2650313bebde6b5b3ef6b7322900d7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 425, "license_type": "no_license", "max_line_length": 64, "num_lines": 23, "path": "/problem040.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\ndef digit(n):\n if n < 10:\n return n\n n -= 10\n \n width = 2\n amount = 90\n start_value = 10\n while True:\n if n < width*amount:\n return int(str(start_value + int(n/width))[n%width])\n n -= width*amount\n \n width += 1\n amount *= 10\n start_value *= 10\n \nproduct = 1\nfor i in range(7):\n product *= digit(10**i)\nprint(product)\n" }, { "alpha_fraction": 0.5115384459495544, "alphanum_fraction": 0.5807692408561707, "avg_line_length": 27.851852416992188, "blob_id": "db9b21adc1533dba4e905bcb8cf501e9baf287e2", "content_id": "3ce895e3c70418d9427668451c950f646c195308", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 780, "license_type": "no_license", "max_line_length": 82, "num_lines": 27, "path": "/problem247.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "\nimport math\n\n# size of largest square that fits under y+y0 = 1/(x+x0)\ndef square(x0, y0):\n b = x0 + y0\n c = x0*y0 - 1.0\n return (-b + math.sqrt(b**2 - 4.0*c)) / 2.0\n\n# follow 'RUU' style string to get size of square found by going right, up then up\ndef get_size(directions, x0, y0):\n s = square(x0, y0)\n if len(directions) == 0:\n return s\n if directions.pop(0) == 'U':\n return get_size(directions, x0, y0+s)\n return get_size(directions, x0+s, y0)\n\n# count num squares smaller than s0 that fit under y+y0 = 1/(x+x0)\ndef count(s0, x0, y0):\n s = square(x0, y0)\n if s < s0:\n return 0\n return 1 + count(s0, x0, y0+s) + count(s0, x0+s, y0)\n \ndef result():\n s0 = get_size(list('RRRUUU'), 1.0, 0.0)\n return count(s0, 1.0, 0.0)\n" }, { "alpha_fraction": 0.46265560388565063, "alphanum_fraction": 0.5020747184753418, "avg_line_length": 27.352941513061523, "blob_id": "11ff61bf73503118b87dab9468d9fdfa9b881325", "content_id": "a8772fee20dce5ced4f314953dd406e35a3da162", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 964, "license_type": "no_license", "max_line_length": 62, "num_lines": 34, "path": "/problem043.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\ntotal = 0\n\ndef substr_int(x, offset):\n return int(''.join(x[offset:offset+3]))\n\ndef test(x):\n if substr_int(x,1) % 2 == 0 and \\\n substr_int(x,2) % 3 == 0 and \\\n substr_int(x,3) % 5 == 0 and \\\n substr_int(x,4) % 7 == 0 and \\\n substr_int(x,5) % 11 == 0 and \\\n substr_int(x,6) % 13 == 0 and \\\n substr_int(x,7) % 17 == 0:\n return True\n return False\n \ndef iterate(selected, remaining):\n if len(remaining) == 0:\n if test(selected):\n global total\n total += int(''.join(selected))\n else:\n for i in range(len(remaining)):\n selected_copy = selected.copy()\n remaining_copy = remaining.copy()\n selected_copy.append(remaining_copy.pop(i))\n iterate(selected_copy, remaining_copy)\n \n \nremaining = ['9', '8', '7', '6', '5', '4', '3', '2', '1', '0']\niterate([], remaining)\nprint(total)\n" }, { "alpha_fraction": 0.6450839042663574, "alphanum_fraction": 0.6810551285743713, "avg_line_length": 23.52941131591797, "blob_id": "6c2377c07c711b5e1830a2ac43d924d97c5a1d53", "content_id": "836c235e23a53f14b260f2768de324f7bb3b45c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 417, "license_type": "no_license", "max_line_length": 81, "num_lines": 17, "path": "/problem006.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# prints the difference between the square of the sum, and the sum of the square,\n# of the first 10 natural numbers\n\n# is this efficient? it seems to do the same loop twice\n\nsum_of_squares = 0\nfor num in range(1, 10+1):\n sum_of_squares += num**2\n \nsquare_of_sum = 0\nfor num in range(1, 10+1):\n square_of_sum += num\nsquare_of_sum = square_of_sum**2\n\nprint(square_of_sum - sum_of_squares)\n" }, { "alpha_fraction": 0.6064257025718689, "alphanum_fraction": 0.6285140514373779, "avg_line_length": 21.636363983154297, "blob_id": "3a6667b219b0c26dc1cfac202dae074fcb00045d", "content_id": "8b6d1a476f0a38eed0d957b00179ecfc720c5107", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 498, "license_type": "no_license", "max_line_length": 75, "num_lines": 22, "path": "/problem005.py", "repo_name": "liampingu/project-euler-starters", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n\n# prints smallest number divisible by all integers from 1 to 10 inclusive\n\n# is this efficient? it seems there could be a better way to go about this.\n# also, it seems to keep testing for divisibility after one test fails.\n\nnumber = 1\n\nwhile True:\n\n divisible_by_all = True\n for factor in range(1, 10+1):\n if number % factor != 0:\n divisible_by_all = False\n \n if divisible_by_all:\n break\n \n number += 1\n \nprint(number)\n" } ]
22
synapse-rpc/astraea
https://github.com/synapse-rpc/astraea
c83f9f0e7a8c958a081bc315856cc67b07b0c51c
c2571aaf6287f3c58b3b696fd96b95f71f3b1e50
8b441423d83dd1617971fda8186421fac7505117
refs/heads/master
2020-12-30T14:34:58.002459
2018-03-16T01:23:03
2018-03-16T01:23:03
91,074,475
1
1
null
2017-05-12T09:24:03
2017-05-14T01:26:11
2017-05-14T01:25:14
Python
[ { "alpha_fraction": 0.5871597528457642, "alphanum_fraction": 0.5927695631980896, "avg_line_length": 36.31007766723633, "blob_id": "ea736d42580d8101d65a425d765093806495e293", "content_id": "2620eba9b3d1d8d2f790896f6531663114a5cb2e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4813, "license_type": "permissive", "max_line_length": 116, "num_lines": 129, "path": "/rpc/synapse/astraea/synapse.py", "repo_name": "synapse-rpc/astraea", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport time\nimport pika\nimport threading\nfrom random import Random\nfrom rpc.synapse.astraea.event_server import EventServer\nfrom rpc.synapse.astraea.event_client import EventClient\nfrom rpc.synapse.astraea.rpc_server import RpcServer\nfrom rpc.synapse.astraea.rpc_client import RpcClient\n\n\nclass Synapse:\n debug = False\n disable_rpc_client = False\n disable_event_client = False\n sys_name = ''\n app_name = ''\n app_id = ''\n mq_host = ''\n mq_port = 5672\n mq_user = ''\n mq_pass = ''\n mq_vhost = '/'\n event_process_num = 20\n rpc_process_num = 20\n rpc_timeout = 3\n event_callback = {}\n rpc_callback = {}\n\n LogInfo = \"Info\"\n LogWarn = \"Warn\"\n LogDebug = \"Debug\"\n LogError = \"Error\"\n\n _rpc_client = None\n _event_client = None\n\n def serve(self):\n if self.app_name == \"\" or self.sys_name == \"\":\n self.log(\"Must Set app_name and sys_name , system exit .\", self.LogError)\n exit(1)\n else:\n self.log(\"System Name: %s\" % self.sys_name)\n self.log(\"App Name: %s\" % self.app_name)\n if self.app_id == \"\":\n self.app_id = self.random_string()\n self.log(\"App Id: %s\" % self.app_id)\n if self.debug:\n self.log(\"App Run Mode: Debug\", self.LogWarn)\n else:\n self.log(\"App Run Mode: Production\")\n self._check_and_create_exchange()\n if self.event_callback == {}:\n self.log(\"Event Server Disabled: event_callback not set\", self.LogWarn)\n else:\n threading.Thread(target=EventServer(self).run).start()\n for k in self.event_callback:\n self.log(\"*EVT: %s -> %s\" % (k, self.event_callback[k].__name__))\n if self.rpc_callback == {}:\n self.log(\"Rpc Server Disabled: rpc_callback not set\", self.LogWarn)\n else:\n threading.Thread(target=RpcServer(self).run).start()\n for k in self.rpc_callback:\n self.log(\"*RPC: %s -> %s\" % (k, self.rpc_callback[k].__name__))\n if self.disable_event_client:\n self.log(\"Event Client Disabled: disable_event_client set True\", self.LogWarn)\n else:\n self._event_client = EventClient(self)\n if self.disable_rpc_client:\n self.log(\"Rpc Client Disabled: disable_rpc_client set True\", self.LogWarn)\n else:\n self._rpc_client = RpcClient(self)\n threading.Thread(target=self._rpc_client.run).start()\n\n def send_event(self, event, params):\n if self.disable_event_client:\n self.log(\"Event Client Disabled!\", self.LogError)\n self._event_client.send(event, params)\n\n def send_rpc(self, app, method, params):\n if self.disable_rpc_client:\n self.log(\"Rpc Client Disabled!\", self.LogError)\n res = {\"rpc_error\": \"rpc client disabled\"}\n else:\n res = self._rpc_client.send(app, method, params)\n return res\n\n def _create_connection(self, desc='unknow'):\n config = pika.ConnectionParameters(\n host=self.mq_host,\n port=self.mq_port,\n virtual_host=self.mq_vhost,\n credentials=pika.PlainCredentials(self.mq_user, self.mq_pass),\n client_properties={\"connection_name\": \"%s_%s_%s_%s\" % (self.sys_name, self.app_name, self.app_id, desc)}\n )\n conn = pika.BlockingConnection(parameters=config)\n self.log(\"%s Connection Created\" % desc)\n return conn\n\n def create_channel(self, process_num=0, desc=\"unknow\", connection=False):\n if not connection:\n connection = self._create_connection(desc=desc)\n channel = connection.channel()\n self.log(\"%s Channel Created\" % desc)\n if process_num > 0:\n channel.basic_qos(prefetch_size=0, prefetch_count=process_num)\n self.log(\"%s MaxProcessNum: %d\" % (desc, process_num))\n return channel\n\n def _check_and_create_exchange(self):\n connection = self._create_connection(desc=\"Exchange\")\n channel = self.create_channel(desc=\"Exchange\", connection=connection)\n channel.exchange_declare(self.sys_name, 'topic', durable=True, auto_delete=True)\n self.log(\"Register Exchange Successed.\")\n connection.close()\n self.log(\"Exchange Channel Closed\")\n self.log(\"Exchange Connection Closed\")\n\n def random_string(self, lens=20):\n str = ''\n chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n length = len(chars) - 1\n random = Random()\n for i in range(lens):\n str += chars[random.randint(0, length)]\n return str\n\n def log(self, desc, level=LogInfo):\n print(\"[%s][Synapse %s] %s\" % (time.strftime(\"%Y-%m-%d %H:%M:%S\"), level, desc))\n" }, { "alpha_fraction": 0.6104369163513184, "alphanum_fraction": 0.6104369163513184, "avg_line_length": 36.45454406738281, "blob_id": "870516cfe81d60c98af11b9812854a029cebb20b", "content_id": "b63464e9343d521516bc8c91246daaa167480b41", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 824, "license_type": "permissive", "max_line_length": 120, "num_lines": 22, "path": "/rpc/synapse/astraea/event_client.py", "repo_name": "synapse-rpc/astraea", "src_encoding": "UTF-8", "text": "import json\nimport pika\n\n\nclass EventClient:\n def __init__(self, synapse):\n self._synapse = synapse\n self.ch = synapse.create_channel(desc=\"EventClient\")\n synapse.log(\"Event Client Ready\")\n\n def send(self, event, params):\n props = pika.BasicProperties(\n app_id=self._synapse.app_id,\n message_id=self._synapse.random_string(),\n reply_to=self._synapse.app_name,\n type=event\n )\n router = \"event.%s.%s\" % (self._synapse.app_name, event)\n body = json.dumps(params)\n self.ch.basic_publish(exchange=self._synapse.sys_name, routing_key=router, properties=props, body=body)\n if self._synapse.debug:\n self._synapse.log(\"Event Publish: %s@%s %s\" % (event, self._synapse.app_name, body), self._synapse.LogDebug)\n" }, { "alpha_fraction": 0.5806878209114075, "alphanum_fraction": 0.5806878209114075, "avg_line_length": 40.23636245727539, "blob_id": "b3d8bf799619e08c7e140a15a62abc6772f1333c", "content_id": "ace8dff0f69b520799e49558c026a29d36e41087", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2268, "license_type": "permissive", "max_line_length": 117, "num_lines": 55, "path": "/rpc/synapse/astraea/rpc_client.py", "repo_name": "synapse-rpc/astraea", "src_encoding": "UTF-8", "text": "import json\nimport pika\nimport time\n\n\nclass RpcClient:\n _response_cache = {}\n\n def __init__(self, synapse):\n self._synapse = synapse\n self._channel = synapse.create_channel(desc=\"RpcClient\")\n self._queue_name = \"%s_%s_client_%s\" % (synapse.sys_name, synapse.app_name, synapse.app_id)\n self._router = \"client.%s.%s\" % (synapse.app_name, synapse.app_id)\n synapse.log(\"Rpc Client Ready\")\n\n def _check_and_create_queue(self):\n self._channel.queue_declare(queue=self._queue_name, durable=True, auto_delete=True)\n self._channel.queue_bind(queue=self._queue_name, exchange=self._synapse.sys_name, routing_key=self._router)\n\n def run(self):\n self._check_and_create_queue()\n\n def handler(ch, deliver, props, body):\n if self._synapse.debug:\n self._synapse.log(\"Rpc Response: (%s)%s@%s->%s %s\" % (\n props.correlation_id, props.type, props.reply_to, self._synapse.app_name, str(body)),\n self._synapse.LogDebug)\n self._response_cache[props.correlation_id] = json.loads(body)\n\n self._channel.basic_consume(consumer_callback=handler, queue=self._queue_name, no_ack=True)\n self._channel.start_consuming()\n\n def send(self, app, method, params):\n props = pika.BasicProperties(\n app_id=self._synapse.app_id,\n message_id=self._synapse.random_string(),\n reply_to=self._synapse.app_name,\n type=method\n )\n router = \"server.%s\" % app\n body = json.dumps(params)\n self._channel.basic_publish(exchange=self._synapse.sys_name, routing_key=router, properties=props, body=body)\n if self._synapse.debug:\n self._synapse.log(\n \"Rpc Request: (%s)%s->%s@%s %s\" % (props.message_id, self._synapse.app_name, method, app, body),\n self._synapse.LogDebug)\n ts = int(time.time())\n while True:\n if int(time.time()) - ts > self._synapse.rpc_timeout:\n res = {\"rpc_error\": \"timeout\"}\n break\n if props.message_id in self._response_cache:\n res = self._response_cache[props.message_id]\n break\n return res\n" }, { "alpha_fraction": 0.5832531452178955, "alphanum_fraction": 0.5832531452178955, "avg_line_length": 47.32558059692383, "blob_id": "b39e23baf0d659c69031875ce6d91c9970d0b67f", "content_id": "d836e26745e61396ffb9b405d227dd4e978eb29e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2078, "license_type": "permissive", "max_line_length": 120, "num_lines": 43, "path": "/rpc/synapse/astraea/rpc_server.py", "repo_name": "synapse-rpc/astraea", "src_encoding": "UTF-8", "text": "import json\nimport pika\n\n\nclass RpcServer:\n def __init__(self, synapse):\n self._synapse = synapse\n self._channel = synapse.create_channel(process_num=synapse.rpc_process_num, desc=\"RpcServer\")\n self._queue_name = \"%s_%s_server\" % (self._synapse.sys_name, self._synapse.app_name)\n self._router = \"server.%s\" % self._synapse.app_name\n\n def _check_and_create_queue(self):\n self._channel.queue_declare(queue=self._queue_name, durable=True, auto_delete=True)\n self._channel.queue_bind(queue=self._queue_name, exchange=self._synapse.sys_name, routing_key=self._router)\n\n def run(self):\n self._check_and_create_queue()\n\n def handler(ch, deliver, props, body):\n if self._synapse.debug:\n self._synapse.log(\"Rpc Receive: (%s)%s->%s@%s %s\" % (\n props.message_id, props.reply_to, props.type, self._synapse.app_name, str(body)),\n self._synapse.LogDebug)\n if props.type in self._synapse.rpc_callback:\n res = self._synapse.rpc_callback[props.type](json.loads(body), props)\n else:\n res = {\"rpc_error\": \"method not found\"}\n body = json.dumps(res)\n reply = \"client.%s.%s\" % (props.reply_to, props.app_id)\n ret_props = pika.BasicProperties(\n app_id=self._synapse.app_id,\n correlation_id=props.message_id,\n message_id=self._synapse.random_string(),\n reply_to=self._synapse.app_name,\n type=props.type\n )\n ch.basic_publish(exchange=self._synapse.sys_name, routing_key=reply, properties=ret_props, body=body)\n if self._synapse.debug:\n self._synapse.log(\"Rpc Return: (%s)%s@%s->%s %s\" % (\n props.message_id, props.type, self._synapse.app_name, props.reply_to, body), self._synapse.LogDebug)\n\n self._channel.basic_consume(consumer_callback=handler, queue=self._queue_name, no_ack=True)\n self._channel.start_consuming()\n" }, { "alpha_fraction": 0.734721302986145, "alphanum_fraction": 0.7374076843261719, "avg_line_length": 18.350648880004883, "blob_id": "87ecb8f89868a4b5ca1ef588be9c68c1893305bf", "content_id": "f02f0c1eb1103025c6c9b5dd2b5d3dd96c314cff", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2241, "license_type": "permissive", "max_line_length": 70, "num_lines": 77, "path": "/README.md", "repo_name": "synapse-rpc/astraea", "src_encoding": "UTF-8", "text": "## 西纳普斯 - synapse (Python Version)\n\n### 此为系统核心交互组件,包含了事件和RPC系统\n包地址\n> https://pypi.python.org/pypi/rpc.synpase.astraea\n\ngit:\n> git clone https://github.com/synapse-rpc/astraea.git\n\n或者使用PIP安装:\n> pip install rpc.synpase.astraea\n\n初始化方法:\n\n```python\n#使用pip安装\nfrom synapse import Synapse\n#创建一个新的对象(这里有疑问,是不是应该加括号)\nserver = Synapse()\n#定义事件回调\nserver.event_callback = {\n \"icarus.test\": callback,\n \"pytest.test\": callback\n}\n#定义RPC服务方法\nserver.rpc_callback = {\n \"pyt.get\": pyt,\n}\n#设置系统名称(相同的系统中的APP才能相互调用)\nserver.sys_name = \"\"\n#设置应用名称(RPC调用和事件的标识)\nserver.app_name = \"\"\n#RabbitMQ 服务器地址\nserver.mq_host = \"\"\n#RabbitMQ 服务器端口\nserver.mq_port = 5672\n#RabbitMQ 服务器用户\nserver.mq_user = \"\"\n#RabbitMQ 服务器密码\nserver.mq_pass =\"\"\n#调试模式开关 (打开后可以看到很多LOG)\nserver.debug = True\n#是否禁用RPC客户端功能 (默认可以进行RPC请求)\nserver.disable_rpc_client = True\n#是否禁用发送事件的机能 (默认允许发送事件)\nserver.disable_event_client = True\n#开始服务\nserver.serve()\n```\n事件处理方法类型:\n```python\ncallback(params, props) \n#params 为字典,客户端请求数据\n#props 为AMQP Properties\n#需要返回 True表示处理完成,返回False表示处理失败\n```\nRPC服务方法类型:\n```python\npyt(params, props) \n#params 为字典,客户端请求数据\n#props 为AMQP Properties\n#需要返回 一个key为string的字典\n```\n发送RPC请求:\n```python\n#第一个参数为要调用组件的名称\n#第二个参数为要调用组件的方法\n#第三个参数为一个key为string的字典 要发送的数据\nserver.send_rpc(\"icarus\",\"echo\",{\"ceshi\":\"我是中文\",\"test\":\"from python\"})\n```\n发送事件请求:\n```python\n#第一个参数为要触发的事件名称 \n#第二个参数为 事件的相关数据 一个key为string的字典\nserver.send_event(\"test\",{\"ceshi\":\"我是中文\",\"test\":\"from python\"})\n```\n上面发送了一个名为 app_name.test 的事件, 只需要在监听器中注册 app_name.test 即可在产生事件时被通知" }, { "alpha_fraction": 0.523809552192688, "alphanum_fraction": 0.523809552192688, "avg_line_length": 20, "blob_id": "6fc40e7dcb37a978d2b1ebbeb20f0ee25aeed56b", "content_id": "f668c09af0b700f93ba13704e704c3099a0748a7", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21, "license_type": "permissive", "max_line_length": 20, "num_lines": 1, "path": "/__init__.py", "repo_name": "synapse-rpc/astraea", "src_encoding": "UTF-8", "text": "__author__ = 'xRain'\n" }, { "alpha_fraction": 0.5754545331001282, "alphanum_fraction": 0.5918181538581848, "avg_line_length": 27.947368621826172, "blob_id": "f1184e4ad1f6719cc4a75fe61792ff3c24f0ac54", "content_id": "027c8b3689d286a09fcc4b498b4587d6d4e644cf", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1100, "license_type": "permissive", "max_line_length": 59, "num_lines": 38, "path": "/setup.py", "repo_name": "synapse-rpc/astraea", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding=utf-8\n\nfrom setuptools import setup, find_packages\n\nsetup(\n name='rpc.synpase.astraea',\n version='1.4.4',\n description=(\n 'A rpc framework base RabbitMQ'\n ),\n long_description=open('README.md').read(),\n author='xRain',\n author_email='[email protected]',\n maintainer='xrain0610',\n maintainer_email='[email protected]',\n license='BSD License',\n packages=find_packages(),\n platforms=[\"all\"],\n url='https://github.com/synapse-rpc',\n classifiers=[\n 'Operating System :: OS Independent',\n 'License :: OSI Approved :: BSD License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: Implementation',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Software Development :: Libraries'\n ],\n install_requires=[\n 'kombu'\n ],\n\n)\n" }, { "alpha_fraction": 0.592149019241333, "alphanum_fraction": 0.592149019241333, "avg_line_length": 44.54545593261719, "blob_id": "d90de1510a70dd3dde1dfdf23dc26f5c70139335", "content_id": "3c2aaac50c47a925093ca9371b3eb6cb8084d172", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1503, "license_type": "permissive", "max_line_length": 125, "num_lines": 33, "path": "/rpc/synapse/astraea/event_server.py", "repo_name": "synapse-rpc/astraea", "src_encoding": "UTF-8", "text": "import json\n\n\nclass EventServer:\n def __init__(self, synapse):\n self._synapse = synapse\n self._channel = synapse.create_channel(process_num=synapse.event_process_num, desc=\"EventServer\")\n self._queue_name = \"%s_%s_event\" % (self._synapse.sys_name, self._synapse.app_name)\n\n def _check_and_create_queue(self):\n self._channel.queue_declare(queue=self._queue_name, durable=True, auto_delete=True)\n for k in self._synapse.event_callback.keys():\n self._channel.queue_bind(queue=self._queue_name, exchange=self._synapse.sys_name,\n routing_key=\"event.%s\" % k)\n\n def run(self):\n self._check_and_create_queue()\n\n def handler(ch, deliver, props, body):\n if self._synapse.debug:\n self._synapse.log(\"Event Receive: %s@%s %s\" % (props.type, props.reply_to, str(body)),self._synapse.LogDebug)\n key = \"%s.%s\" % (props.reply_to, props.type)\n if key in self._synapse.event_callback:\n res = self._synapse.event_callback[key](json.loads(body), props)\n if res:\n self._channel.basic_ack(deliver.delivery_tag)\n else:\n self._channel.basic_nack(deliver.delivery_tag)\n else:\n self._channel.basic_nack(deliver.delivery_tag, requeue=False)\n\n self._channel.basic_consume(consumer_callback=handler, queue=self._queue_name)\n self._channel.start_consuming()\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 24, "blob_id": "fe107d03324c684f78a1c3a4a7488256366bbe29", "content_id": "04669a40ba6511cd79baa505381de6b491c6dc9b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 50, "license_type": "permissive", "max_line_length": 28, "num_lines": 2, "path": "/rpc/synapse/astraea/__init__.py", "repo_name": "synapse-rpc/astraea", "src_encoding": "UTF-8", "text": "__author__ = \"xRain\"\nfrom .synapse import Synapse\n" } ]
9
thoratvinod/Music_On_Mood_BE_Project
https://github.com/thoratvinod/Music_On_Mood_BE_Project
e00566cab52379b5bdccf4140c9566eff48568da
e83a367c25aabfcdea5bf8859c45f741bdf679d5
4d341679be4da3aa10d3b97039741ee092bc449d
refs/heads/master
2021-04-11T01:18:29.690011
2020-03-22T02:12:19
2020-03-22T02:12:19
248,981,457
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6382330656051636, "alphanum_fraction": 0.6656512022018433, "avg_line_length": 33.55263137817383, "blob_id": "de89e2e840e6f74ae5af6315456944eaf48b4f7d", "content_id": "7de02b0db86c460e5a7c033785a89b3a4f2374b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1313, "license_type": "no_license", "max_line_length": 88, "num_lines": 38, "path": "/migrations/versions/e9709bd9ecb7_adding_table_again.py", "repo_name": "thoratvinod/Music_On_Mood_BE_Project", "src_encoding": "UTF-8", "text": "\"\"\"adding table again\n\nRevision ID: e9709bd9ecb7\nRevises: bb56c8e3484d\nCreate Date: 2020-03-20 20:07:06.281453\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e9709bd9ecb7'\ndown_revision = 'bb56c8e3484d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('track_group', sa.Column('pl_id', sa.Integer(), nullable=False))\n op.add_column('track_group', sa.Column('tg_id', sa.Integer(), nullable=False))\n op.add_column('track_group', sa.Column('track_id', sa.Integer(), nullable=False))\n op.drop_column('track_group', 'Playlist_id')\n op.drop_column('track_group', 'id')\n op.drop_column('track_group', 'Track_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('track_group', sa.Column('Track_id', sa.INTEGER(), nullable=False))\n op.add_column('track_group', sa.Column('id', sa.INTEGER(), nullable=False))\n op.add_column('track_group', sa.Column('Playlist_id', sa.INTEGER(), nullable=False))\n op.drop_column('track_group', 'track_id')\n op.drop_column('track_group', 'tg_id')\n op.drop_column('track_group', 'pl_id')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6382660865783691, "alphanum_fraction": 0.6621823906898499, "avg_line_length": 29.409090042114258, "blob_id": "8b19cd8723c5c48b972105a91728290c2a801342", "content_id": "7ceaabdc46512f4ddd37983df0f464981f5bea33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1338, "license_type": "no_license", "max_line_length": 79, "num_lines": 44, "path": "/migrations/versions/37b9c401cfa2_adding_playlist.py", "repo_name": "thoratvinod/Music_On_Mood_BE_Project", "src_encoding": "UTF-8", "text": "\"\"\"Adding Playlist\n\nRevision ID: 37b9c401cfa2\nRevises: 14e456fcf9ea\nCreate Date: 2020-03-20 17:38:10.237210\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '37b9c401cfa2'\ndown_revision = '14e456fcf9ea'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('playlist',\n sa.Column('playlist_id', sa.Integer(), nullable=False),\n sa.Column('playlist_title', sa.String(length=200), nullable=False),\n sa.Column('date_created', sa.DateTime(), nullable=True),\n sa.Column('created_by', sa.Integer(), nullable=False),\n sa.Column('emotion', sa.String(length=10), nullable=True),\n sa.PrimaryKeyConstraint('playlist_id')\n )\n op.create_table('track_group',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('Playlist_id', sa.Integer(), nullable=False),\n sa.Column('Track_id', sa.Integer(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.add_column('track', sa.Column('playlist', sa.Integer(), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('track', 'playlist')\n op.drop_table('track_group')\n op.drop_table('playlist')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5407261848449707, "alphanum_fraction": 0.5736015439033508, "avg_line_length": 36.05454635620117, "blob_id": "92bcd589f02a1ff2db041592307ec1e375df21bb", "content_id": "b79f028d45bc8d1b181f65826892bc3731d1b9b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2038, "license_type": "no_license", "max_line_length": 103, "num_lines": 55, "path": "/emotion.py", "repo_name": "thoratvinod/Music_On_Mood_BE_Project", "src_encoding": "UTF-8", "text": "# Importing ML libs\nimport tensorflow as tf\nfrom tensorflow.python.keras.backend import set_session\nfrom tensorflow.python.keras.models import load_model\nfrom time import sleep\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing import image\nimport cv2\nimport numpy as np\n\n# ML Initializations\nsess = tf.Session()\ngraph = tf.get_default_graph()\nset_session(sess)\nface_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\nclassifier =load_model('Emotion_little_vgg.h5')\nclass_labels = ['Angry','Happy','Neutral','Sad','Surprise']\n\n# Emotion Detection Function\ndef get_emotion():\n label='404'\n cap = cv2.VideoCapture(0)\n while label=='404':\n global sess\n global graph\n with graph.as_default():\n ret, frame = cap.read()\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n faces = face_classifier.detectMultiScale(gray,1.3,5)\n\n # if faces:\n for (x,y,w,h) in faces:\n # cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\n roi_gray = gray[y:y+h,x:x+w]\n roi_gray = cv2.resize(roi_gray,(48,48),interpolation=cv2.INTER_AREA)\n if np.sum([roi_gray])!=0:\n roi = roi_gray.astype('float')/255.0\n roi = img_to_array(roi)\n roi = np.expand_dims(roi,axis=0)\n set_session(sess)\n preds = classifier.predict(roi)[0]\n label=class_labels[preds.argmax()]\n # label_position = (x,y)\n # cv2.putText(frame,label,label_position,cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)\n # cap.release()\n # return label\n else:\n # cv2.putText(frame,'No Face Found',(20,60),cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)\n label = '404'\n # cv2.imshow('Emotion Detector',frame)\n \n # time.sleep(15)\n cap.release() \n # cv2.waitKey(1) \n return label\n" }, { "alpha_fraction": 0.6373737454414368, "alphanum_fraction": 0.6828283071517944, "avg_line_length": 27.285715103149414, "blob_id": "cdb7900de8bde9c09e187825420460b8a2fb1e2e", "content_id": "714bb19b8ce2dcb9967d44c7f9fe1029e33fe626", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 990, "license_type": "no_license", "max_line_length": 71, "num_lines": 35, "path": "/migrations/versions/71a797de0ca6_updating_table_playlist.py", "repo_name": "thoratvinod/Music_On_Mood_BE_Project", "src_encoding": "UTF-8", "text": "\"\"\"Updating Table Playlist\n\nRevision ID: 71a797de0ca6\nRevises: 45173b81873d\nCreate Date: 2020-03-20 23:07:36.077820\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '71a797de0ca6'\ndown_revision = '45173b81873d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('playlist',\n sa.Column('playlist_id', sa.Integer(), nullable=False),\n sa.Column('playlist_title', sa.String(length=200), nullable=False),\n sa.Column('date_created', sa.DateTime(), nullable=False),\n sa.Column('created_by', sa.String(length=15), nullable=False),\n sa.Column('emotion', sa.String(length=10), nullable=True),\n sa.PrimaryKeyConstraint('playlist_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('playlist')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6226415038108826, "alphanum_fraction": 0.6578616499900818, "avg_line_length": 23.090909957885742, "blob_id": "01645257662f057fbdc009a199f458fbc47eb12a", "content_id": "0e5ae1fccbdef24398459d5fbe6b15b8edf8e0e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 795, "license_type": "no_license", "max_line_length": 65, "num_lines": 33, "path": "/migrations/versions/7f05bf2657d9_adding_table_again.py", "repo_name": "thoratvinod/Music_On_Mood_BE_Project", "src_encoding": "UTF-8", "text": "\"\"\"adding table again\n\nRevision ID: 7f05bf2657d9\nRevises: e9709bd9ecb7\nCreate Date: 2020-03-20 20:07:55.677173\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '7f05bf2657d9'\ndown_revision = 'e9709bd9ecb7'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('track_group')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('track_group',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.Column('Playlist_id', sa.INTEGER(), nullable=False),\n sa.Column('Track_id', sa.INTEGER(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6290143728256226, "alphanum_fraction": 0.6611295938491821, "avg_line_length": 24.799999237060547, "blob_id": "fc04e0f615f7a6dbbbbbae773a20c1b9c733e329", "content_id": "3d52e388ba5698165e33e0b3116ed2dcbb60a3f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 903, "license_type": "no_license", "max_line_length": 65, "num_lines": 35, "path": "/migrations/versions/14e456fcf9ea_initial_migration.py", "repo_name": "thoratvinod/Music_On_Mood_BE_Project", "src_encoding": "UTF-8", "text": "\"\"\"Initial migration.\n\nRevision ID: 14e456fcf9ea\nRevises: \nCreate Date: 2020-03-20 07:17:37.209190\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '14e456fcf9ea'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('track',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=200), nullable=False),\n sa.Column('duration', sa.String(length=5), nullable=False),\n sa.Column('file', sa.String(length=200), nullable=False),\n sa.Column('emotion', sa.String(length=10), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('track')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6158196926116943, "alphanum_fraction": 0.6269603371620178, "avg_line_length": 33.122806549072266, "blob_id": "48168a0dd5ac5729b15d8915c25e13b9d872c296", "content_id": "e9c781eaa97e30d4e0802b66b4b7f6d8d15a0024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11669, "license_type": "no_license", "max_line_length": 223, "num_lines": 342, "path": "/app.py", "repo_name": "thoratvinod/Music_On_Mood_BE_Project", "src_encoding": "UTF-8", "text": "# Importing flask libs\nfrom flask import Flask, render_template, redirect, url_for, request\nfrom flask_bootstrap import Bootstrap\nfrom flask_wtf import FlaskForm \nfrom wtforms import StringField, PasswordField, BooleanField\nfrom wtforms.validators import InputRequired, Email, Length\nfrom flask_sqlalchemy import SQLAlchemy\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user\nfrom flask_migrate import Migrate\nimport json\nfrom datetime import datetime\nfrom emotion import get_emotion\n\n\n\n# instantiate the app\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'Thisissupposedtobesecret!'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mom.db'\nbootstrap = Bootstrap(app)\ndb = SQLAlchemy(app)\ndb.init_app(app)\nmigrate = Migrate(app, db)\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = 'login'\n\n\nclass Track(db.Model):\n track_id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(200), nullable=False)\n duration = db.Column(db.String(5), nullable=False)\n file = db.Column(db.String(1000), nullable=False)\n emotion = db.Column(db.String(10), nullable=False)\n\n def __repr__(self):\n return '<Track%r'% self.track_id\n\n def asdict(self):\n res = {\n 'id' : self.track_id,\n 'name' : self.name,\n 'file' : self.file,\n 'duration' : self.duration,\n 'emotion' : self.emotion\n }\n return res\n\nclass Playlist(db.Model):\n playlist_id = db.Column(db.Integer, primary_key=True)\n playlist_title = db.Column(db.String(200), nullable=False)\n date_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)\n created_by = db.Column(db.String(15), nullable=False)\n emotion = db.Column(db.String(10), default='404')\n\n def __repr__(self):\n return '<playlist%r'% self.playlist_id\n\nclass TrackGroup(db.Model):\n tg_id = db.Column(db.Integer, primary_key=True)\n playlist_id = db.Column(db.Integer, nullable=False, default=0)\n track_id = db.Column(db.Integer, nullable=False, default=0)\n \nclass User(UserMixin, db.Model):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(15), unique=True)\n email = db.Column(db.String(50), unique=True)\n password = db.Column(db.String(80))\n \n\n# Here will be my models\nclass LoginForm(FlaskForm):\n username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])\n password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])\n remember = BooleanField('remember me')\n\nclass RegisterForm(FlaskForm):\n email = StringField('email', validators=[InputRequired(), Email(message='Invalid email'), Length(max=50)])\n username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])\n password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(int(user_id))\n\[email protected]('/')\ndef index():\n trackTemp = []\n tracks = Track.query.all()\n for track in tracks:\n trackTemp.append(track.asdict())\n return render_template('index.html', current_user=current_user, tracks=trackTemp)\n\n\[email protected]('/default_add_track', methods=['POST','GET'])\ndef default_add_track():\n track_to_delete = Track.query.delete()\n db.session.commit()\n track1 = Track(\n name= \"All This Is - Joe L.'s Studio\",\n duration = \"2:46\",\n file=\"https://raw.githubusercontent.com/muhammederdem/mini-player/master/mp3/1.mp3\",\n emotion = \"Angry\"\n \n )\n track2 = Track(\n name= \"The Forsaken - Broadwing Studio (Final Mix)\",\n duration = \"2:46\",\n file=\"https://raw.githubusercontent.com/muhammederdem/mini-player/master/mp3/2.mp3\",\n emotion = \"Sad\"\n )\n track3 = Track(\n name= \"All The King's Men - Broadwing Studio (Final Mix)\",\n duration = \"2:46\",\n file=\"https://raw.githubusercontent.com/muhammederdem/mini-player/master/mp3/3.mp3\",\n emotion = \"Surprise\"\n )\n track4 = Track(\n name= \"The Forsaken - Broadwing Studio (First Mix)\",\n duration = \"2:46\",\n file=\"https://raw.githubusercontent.com/muhammederdem/mini-player/master/mp3/4.mp3\",\n emotion = \"Sad\"\n )\n track5 = Track(\n name= \"All The King's Men - Broadwing Studio (First Mix)\",\n duration = \"2:46\",\n file=\"https://raw.githubusercontent.com/muhammederdem/mini-player/master/mp3/5.mp3\",\n emotion = \"Happy\"\n )\n track6 = Track(\n name= \"All This Is - Alternate Cuts\",\n duration = \"2:46\",\n file=\"https://raw.githubusercontent.com/muhammederdem/mini-player/master/mp3/6.mp3\",\n emotion = \"Happy\"\n )\n track7 = Track(\n name= \"All The King's Men (Take 1) - Alternate Cuts\",\n duration = \"2:46\",\n file=\"https://raw.githubusercontent.com/muhammederdem/mini-player/master/mp3/7.mp3\",\n emotion = \"Happy\"\n )\n track8 = Track(\n name= \"All The King's Men (Take 2) - Alternate Cuts\",\n duration = \"2:46\",\n file=\"https://raw.githubusercontent.com/muhammederdem/mini-player/master/mp3/8.mp3\",\n emotion = \"Angry\"\n )\n track9 = Track(\n name= \"Magus - Alternate Cuts\",\n duration = \"2:46\",\n file=\"https://raw.githubusercontent.com/muhammederdem/mini-player/master/mp3/9.mp3\",\n emotion = \"Happy\"\n )\n db.session.add(track1)\n db.session.add(track2)\n db.session.add(track3)\n db.session.add(track4)\n db.session.add(track5)\n db.session.add(track6)\n db.session.add(track7)\n db.session.add(track8)\n db.session.add(track9)\n db.session.commit()\n return \"Done...\"\n # if request.method == 'POST':\n # name = request.form['name']\n # duration = request.form['duration']\n # file = request.form['file']\n # emotion = request.form['emotion']\n # new_track = Track(\n # name=name,\n # duration=duration,\n # file=file,\n # emotion=emotion\n # )\n # # try:\n # db.session.add(new_track)\n # db.session.commit()\n # return redirect('/')\n # # except:\n # # return 'There was problem when adding track to database'\n\n # else:\n # return render_template('add_track.html')\n\[email protected]('/add_track', methods=['POST','GET'])\ndef add_track():\n if request.method == 'POST':\n name = request.form['name']\n duration = request.form['duration']\n file = request.form['file']\n emotion = request.form['emotion']\n new_track = Track(\n name=name,\n duration=duration,\n file=file,\n emotion=emotion\n )\n # try:\n db.session.add(new_track)\n db.session.commit()\n return redirect('/')\n # except:\n # return 'There was problem when adding track to database'\n\n else:\n return render_template('add_track.html')\n\[email protected]('/add_playlist', methods=['POST','GET'])\ndef add_playlist():\n if request.method == 'POST':\n name = request.form['name']\n emotion = request.form['emotion']\n new_playlist = Playlist(\n playlist_title=name,\n emotion=emotion,\n created_by=current_user.username\n )\n # try:\n db.session.add(new_playlist)\n db.session.commit()\n id = new_playlist.playlist_id\n return redirect('/add_tracks_to_playlist?playlist_id={}'.format(id))\n # except:\n # return 'There was problem when adding track to database'\n\n else:\n return render_template('add_playlist.html')\n\[email protected]('/add_tracks_to_playlist', methods=['POST','GET'])\ndef add_tracks_to_playlist():\n if request.method == 'POST':\n playlist_id = request.args.get('playlist_id')\n inputs = request.form.to_dict()\n for track_id in inputs:\n trackGroup = TrackGroup(\n track_id = int(track_id),\n playlist_id = playlist_id\n )\n db.session.add(trackGroup)\n \n db.session.commit()\n return redirect('/')\n else:\n tracks = Track.query.all()\n return render_template('add_tracks_to_playlist.html', tracks=tracks)\n\n\n\[email protected]('/show_playlists', methods=['POST','GET'])\ndef show_playlists():\n playlists = Playlist.query.all()\n return render_template('show_playlists.html', playlists=playlists)\n\ndef convert_into_dict(track):\n res = {\n 'id' : track.track_id,\n 'name' : track.name,\n 'file' : track.file,\n 'duration' : track.duration,\n 'emotion' : track.emotion\n }\n return res\n\[email protected]('/play_playlist/<int:playlist_id>', methods=['POST','GET'])\ndef play_playlist(playlist_id):\n sql = 'select * from track where track.track_id in (select track_group.track_id from playlist inner join track_group on playlist.playlist_id=track_group.playlist_id where track_group.playlist_id={})'.format(playlist_id)\n print(sql)\n tracks = db.engine.execute(sql)\n trackTemp = []\n for track in tracks:\n trackTemp.append(convert_into_dict(track))\n return render_template('play_playlist.html', tracks = trackTemp)\n\[email protected]('/delete_playlist/<int:playlist_id>')\ndef delete_playlist(playlist_id):\n playlist = Playlist.query.get_or_404(playlist_id)\n db.session.delete(playlist)\n db.session.commit()\n trackGroup = TrackGroup.query.filter_by(playlist_id=playlist_id).delete()\n db.session.commit()\n return redirect('/show_playlists')\n\[email protected]('/musicplayer', methods=['POST','GET'])\ndef musicplayer():\n mood = request.args.get('mood')\n if mood is None:\n print('mood is none')\n return render_template('index.html')\n filename = 'img/{}.png'.format(mood)\n print(mood)\n trackTemp = []\n tracks = Track.query.all()\n for track in tracks:\n trackTemp.append(track.asdict())\n return render_template('index.html', filename=filename, current_user=current_user, tracks=trackTemp)\n\n\[email protected]('/login', methods=['POST','GET'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.username.data).first()\n if user:\n if check_password_hash(user.password, form.password.data):\n login_user(user, remember=form.remember.data)\n return redirect(url_for('index'))\n\n return '<h1>Invalid username or password</h1>'\n #return '<h1>' + form.username.data + ' ' + form.password.data + '</h1>'\n return render_template('login.html', form=form) \n\[email protected]('/register', methods=['GET', 'POST'])\ndef register():\n form = RegisterForm()\n\n if form.validate_on_submit():\n hashed_password = generate_password_hash(form.password.data, method='sha256')\n new_user = User(username=form.username.data, email=form.email.data, password=hashed_password)\n db.session.add(new_user)\n db.session.commit()\n\n return '<h1>New user has been created!</h1>'\n #return '<h1>' + form.username.data + ' ' + form.email.data + ' ' + form.password.data + '</h1>'\n\n return render_template('register.html', form=form)\n\[email protected]('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n\[email protected]('/predict')\ndef predict():\n label = get_emotion() \n return redirect('/musicplayer?mood='+label)\n\nif __name__== \"__main__\":\n app.run(debug=True)" }, { "alpha_fraction": 0.6432880759239197, "alphanum_fraction": 0.6689291000366211, "avg_line_length": 33.894737243652344, "blob_id": "ceb86d86d3832267697af4708e8e34793f304186", "content_id": "08794abc89067b4c2a0232ca4dde12937c7be7da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1326, "license_type": "no_license", "max_line_length": 88, "num_lines": 38, "path": "/migrations/versions/bb56c8e3484d_adding_table_again.py", "repo_name": "thoratvinod/Music_On_Mood_BE_Project", "src_encoding": "UTF-8", "text": "\"\"\"adding table again\n\nRevision ID: bb56c8e3484d\nRevises: ae92e4d18a37\nCreate Date: 2020-03-20 20:06:11.721218\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'bb56c8e3484d'\ndown_revision = 'ae92e4d18a37'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('track_group', sa.Column('playlist_id', sa.Integer(), nullable=False))\n op.add_column('track_group', sa.Column('tg_id', sa.Integer(), nullable=False))\n op.add_column('track_group', sa.Column('track_id', sa.Integer(), nullable=False))\n op.drop_column('track_group', 'id')\n op.drop_column('track_group', 'Playlist_id')\n op.drop_column('track_group', 'Track_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('track_group', sa.Column('Track_id', sa.INTEGER(), nullable=False))\n op.add_column('track_group', sa.Column('Playlist_id', sa.INTEGER(), nullable=False))\n op.add_column('track_group', sa.Column('id', sa.INTEGER(), nullable=False))\n op.drop_column('track_group', 'track_id')\n op.drop_column('track_group', 'tg_id')\n op.drop_column('track_group', 'playlist_id')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6414653062820435, "alphanum_fraction": 0.6652377247810364, "avg_line_length": 37.878787994384766, "blob_id": "fbe258d28929c02311b011d807bbdeada105b64f", "content_id": "304e125cbaf4f737806a42d5733adb81b3a72991", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2566, "license_type": "no_license", "max_line_length": 88, "num_lines": 66, "path": "/migrations/versions/9036040d046e_adding_table_again.py", "repo_name": "thoratvinod/Music_On_Mood_BE_Project", "src_encoding": "UTF-8", "text": "\"\"\"adding table again\n\nRevision ID: 9036040d046e\nRevises: 37b9c401cfa2\nCreate Date: 2020-03-20 20:02:55.778267\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9036040d046e'\ndown_revision = '37b9c401cfa2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('playlist',\n sa.Column('playlist_id', sa.Integer(), nullable=False),\n sa.Column('playlist_title', sa.String(length=200), nullable=False),\n sa.Column('date_created', sa.DateTime(), nullable=False),\n sa.Column('created_by', sa.Integer(), nullable=False),\n sa.Column('emotion', sa.String(length=10), nullable=True),\n sa.PrimaryKeyConstraint('playlist_id')\n )\n op.create_table('track',\n sa.Column('track_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=200), nullable=False),\n sa.Column('duration', sa.String(length=5), nullable=False),\n sa.Column('file', sa.String(length=1000), nullable=False),\n sa.Column('emotion', sa.String(length=10), nullable=False),\n sa.PrimaryKeyConstraint('track_id')\n )\n op.create_table('user',\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=15), nullable=True),\n sa.Column('email', sa.String(length=50), nullable=True),\n sa.Column('password', sa.String(length=80), nullable=True),\n sa.PrimaryKeyConstraint('user_id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('username')\n )\n op.add_column('track_group', sa.Column('playlist_id', sa.Integer(), nullable=False))\n op.add_column('track_group', sa.Column('tg_id', sa.Integer(), nullable=False))\n op.add_column('track_group', sa.Column('track_id', sa.Integer(), nullable=False))\n op.drop_column('track_group', 'id')\n op.drop_column('track_group', 'Playlist_id')\n op.drop_column('track_group', 'Track_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('track_group', sa.Column('Track_id', sa.INTEGER(), nullable=False))\n op.add_column('track_group', sa.Column('Playlist_id', sa.INTEGER(), nullable=False))\n op.add_column('track_group', sa.Column('id', sa.INTEGER(), nullable=False))\n op.drop_column('track_group', 'track_id')\n op.drop_column('track_group', 'tg_id')\n op.drop_column('track_group', 'playlist_id')\n op.drop_table('user')\n op.drop_table('track')\n op.drop_table('playlist')\n # ### end Alembic commands ###\n" } ]
9
hmltnbrn/massm-project
https://github.com/hmltnbrn/massm-project
79ab0a2ee6ad978a7d4446e3c2a25b331bab6115
0e780d4ef9319ed3f90c9fc15ecfbd860f730a64
00d055abe5bf51e590ad070c8667ccf97f78ae33
refs/heads/master
2023-03-18T18:19:33.333551
2020-05-10T17:16:57
2020-05-10T17:16:57
262,340,433
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5109022259712219, "alphanum_fraction": 0.5317668914794922, "avg_line_length": 25.73366928100586, "blob_id": "d15a0c331caa41226a2819e8725cc7adec5ce2a5", "content_id": "9d7b135ddc02b36d400a54c1257e0fdc213f9260", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5320, "license_type": "no_license", "max_line_length": 110, "num_lines": 199, "path": "/static/scripts/states.js", "repo_name": "hmltnbrn/massm-project", "src_encoding": "UTF-8", "text": "(function() {\n const toolDiv = d3.select(\"body\")\n .append(\"div\")\n .attr(\"class\", \"state-tooltip\")\n .style(\"opacity\", 0);\n\n const margin = { top: 10, right: 20, bottom: 30, left: 30 };\n\n const width = 960 - margin.left - margin.right;\n const height = 600 - margin.top - margin.bottom;\n\n const svg = d3.select('#state-map')\n .append('svg')\n .attr('width', width + margin.left + margin.right)\n .attr('height', height + margin.top + margin.bottom)\n .call(responsive);\n\n const riskMap = d3.map();\n const stabilityMap = d3.map();\n const stateNames = d3.map();\n\n const path = d3.geoPath();\n\n const color = d3.scaleSequential()\n .interpolator(d3.interpolateOranges)\n .domain([0, 100]);\n\n const x = d3.scaleLinear()\n .domain([0, 100])\n .range([0, width/2]);\n\n const g = svg.append(\"g\")\n .attr(\"class\", \"key\")\n .attr(\"transform\", `translate(${width/2}, 10)`);\n\n g.selectAll(\"rect\")\n .data(Array.from(Array(100).keys()))\n .enter().append(\"rect\")\n .attr(\"x\", d => Math.floor(x(d)))\n .attr(\"y\", 0)\n .attr(\"height\", 10)\n .attr(\"width\", d => {\n if (d == 100) {\n return 6;\n }\n return Math.floor(x(d+1)) - Math.floor(x(d)) + 1;\n })\n .attr(\"fill\", d => color(d));\n\n g.append(\"text\")\n .attr(\"class\", \"caption\")\n .attr(\"x\", width/4)\n .attr(\"y\", 0)\n .attr(\"fill\", \"#000000\")\n .text(\"Number of At-Risk Individuals\");\n\n g.call(d3.axisBottom(x)\n .tickSize(15)\n .tickFormat(d => { return d === 0 ? 'Lowest' : 'Highest'; })\n .tickValues(color.domain()))\n .select(\".domain\").remove();\n\n const states = svg.append(\"g\")\n .attr(\"class\", \"state-container\");\n\n const borders = svg.append(\"g\")\n .attr(\"class\", \"border-container\");\n\n const dc = svg.append(\"g\")\n .attr(\"transform\", `translate(${width - 40}, ${height - 150})`)\n .attr(\"class\", \"dc-group\");\n\n dc.append(\"text\")\n .attr(\"class\",\"dc-text\")\n .attr(\"x\", 24)\n .attr(\"y\", 9)\n .attr(\"dy\", \".35em\")\n .text(\"DC\");\n\n const promises = [\n d3.json(\"https://d3js.org/us-10m.v1.json\"),\n d3.tsv(\"./static/data/state-names.tsv\", d => {\n stateNames.set(d.id, { code: d.code, name: d.name });\n }),\n d3.json(\"/api/state/total\").then(d => {\n d.data.forEach(d => {\n riskMap.set(d.state, { total: d.total, percentage: d.percentage });\n });\n }),\n d3.json(\"/api/state/stability\").then(d => {\n d.data.forEach(d => {\n stabilityMap.set(d.state, { total: d.total, percentage: d.percentage });\n });\n })\n ];\n\n Promise.all(promises).then(createAll);\n\n function createAll([us]) {\n d3.selectAll(\"input[name='state-view']\").on(\"change\", function() {\n if(this.value === \"risk\") {\n createMap(us, riskMap, 'Individuals', 'Number of Individuals');\n }\n else if(this.value === \"stability\") {\n createMap(us, stabilityMap, 'Economic Stability', 'Average Economic Stability (1-30) of Individuals');\n }\n });\n createMap(us, riskMap, 'Individuals', 'Number of Individuals');\n }\n\n function createMap(us, map, title, caption) {\n const paths = states.selectAll('path')\n .data(topojson.feature(us, us.objects.states).features);\n\n paths.exit().remove();\n\n paths.enter().append(\"path\")\n .merge(paths)\n .attr(\"fill\", d => {\n let state = stateNames.get(+d.id);\n d.percentage = map.get(state.code)[\"percentage\"] || 0;\n d.total = map.get(state.code)[\"total\"] || 0;\n let col = color(d.percentage);\n if (col) {\n return col;\n }\n else {\n return '#ffffff';\n }\n })\n .attr(\"d\", path)\n .on(\"mouseover\", handleMouseOver)\n .on(\"mouseout\", handleMouseOut);\n\n const state_paths = borders.selectAll('path')\n .data([topojson.mesh(us, us.objects.states, (a, b) => { return a !== b; })]);\n\n state_paths.exit().remove();\n\n state_paths.enter().append(\"path\")\n .attr(\"class\", \"states\")\n .merge(state_paths)\n .attr(\"d\", path);\n \n const dc_data = dc.selectAll(\"rect\")\n .data([map.get(\"DC\")]);\n\n dc_data.exit().remove();\n\n dc_data.enter().append(\"rect\")\n .attr(\"class\", \"dc-rect\")\n .attr(\"width\", 18)\n .attr(\"height\", 18)\n .merge(dc_data)\n .attr(\"fill\", d => {\n d.id = 11;\n let col = color(d.percentage); \n if (col) {\n return col;\n }\n else {\n return '#ffffff';\n }\n })\n .on(\"mouseover\", handleMouseOver)\n .on(\"mouseout\", handleMouseOut);\n \n d3.select('.caption')\n .text(caption);\n\n d3.select(\".key\").selectAll('rect')\n .attr(\"fill\", d => {\n if(title === 'Economic Stability') {\n return color(99 - d);\n }\n return color(d);\n });\n \n function handleMouseOver(d) {\n toolDiv.transition()\n .duration(200)\n .style(\"opacity\", .9);\n toolDiv.html(`\n <h2>${stateNames.get(+d.id).name || \"District of Columbia\"}</h2>\n <h3>${title}</h3>\n <p>${d.total.toLocaleString()}</p>\n `)\n .style(\"left\", (d3.event.pageX) + \"px\")\n .style(\"top\", (d3.event.pageY - 28) + \"px\");\n }\n\n function handleMouseOut() {\n toolDiv.transition()\n .duration(500)\n .style(\"opacity\", 0);\n }\n }\n\n})();\n" }, { "alpha_fraction": 0.6208605170249939, "alphanum_fraction": 0.6258148550987244, "avg_line_length": 35.52381134033203, "blob_id": "893e151fd93f343c034480f4b9d55057e7b528cc", "content_id": "b37ccef4e1d2f9e3453702a78dbf366d21c81e00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3835, "license_type": "no_license", "max_line_length": 199, "num_lines": 105, "path": "/start.py", "repo_name": "hmltnbrn/massm-project", "src_encoding": "UTF-8", "text": "import sys\nimport os\nimport sqlite3\n\nimport pandas as pd\n\nfrom flask import Flask, jsonify\nfrom flask import render_template\n\napp = Flask(__name__)\n\nDATABASE = os.path.join(app.root_path, \"recruit.db\")\n\ndef df_fetch(cursor):\n df = pd.DataFrame(cursor.fetchall())\n if not df.empty:\n df.columns = [col[0] for col in cursor.description]\n return df\n\ndef query_db(query):\n\n result_dict = {}\n\n try:\n connection = sqlite3.connect(DATABASE)\n\n cursor = connection.cursor()\n cursor.execute(query)\n result_dict = df_fetch(cursor)\n\n except sqlite3.OperationalError as e:\n print(\"Db operation error\", e)\n result_dict[\"error\"] = str(e)\n except:\n e = sys.exc_info()[0]\n print(\"An error occurred with the database\", e)\n result_dict[\"error\"] = str(e)\n else:\n cursor.close()\n connection.close()\n\n return result_dict\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/api/state/total', methods=['GET'])\ndef get_state_risk():\n\n result_df = query_db('''WITH at_risk AS (SELECT state, COUNT(id) AS total FROM customer GROUP BY state),\n risk_aggs AS (SELECT MAX(total) AS max_num, MIN(total) AS min_num FROM at_risk)\n SELECT ar.state, ar.total, (((ar.total-ra.min_num)*1.0/(ra.max_num-ra.min_num)*1.0)*100) AS percentage FROM at_risk ar, risk_aggs ra;''')\n result_dict = result_df.to_dict('records')\n\n return jsonify({'data': result_dict})\n\[email protected]('/api/state/stability', methods=['GET'])\ndef get_state_stability():\n\n result_df = query_db('''WITH at_risk AS (SELECT state, AVG(economic_stability) AS total FROM customer GROUP BY state),\n risk_aggs AS (SELECT MAX(total) AS max_num, MIN(total) AS min_num FROM at_risk)\n SELECT ar.state, ar.total, (((ar.total-ra.min_num)*1.0/(ra.max_num-ra.min_num)*1.0)*100) AS percentage FROM at_risk ar, risk_aggs ra;''')\n result_dict = result_df.to_dict('records')\n\n return jsonify({'data': result_dict})\n\[email protected]('/api/demo/race', methods=['GET'])\ndef get_demo_race():\n\n result_df = query_db('''SELECT r.value AS race, c.gender, COUNT(c.id) AS total FROM customer c, race r WHERE c.race_code = r.code GROUP BY r.value, c.gender;''')\n result_dict = result_df.to_dict('records')\n\n return jsonify({'data': result_dict})\n\[email protected]('/api/demo/education', methods=['GET'])\ndef get_demo_education():\n\n result_df = query_db('''SELECT coalesce(e.value, 'None') AS education_type, c.gender, COUNT(c.id) AS total FROM customer c, education e WHERE c.education_id = e.id GROUP BY e.value, c.gender;''')\n result_dict = result_df.to_dict('records')\n\n return jsonify({'data': result_dict})\n\[email protected]('/api/demo/ownership', methods=['GET'])\ndef get_demo_home():\n\n result_df = query_db('''SELECT home_owner, gender, COUNT(id) AS total FROM customer WHERE home_owner != ' ' GROUP BY home_owner, gender\n UNION ALL\n SELECT 'N' AS home_owner, gender, COUNT(id) AS total FROM customer WHERE home_owner = ' ' GROUP BY home_owner, gender''')\n result_dict = result_df.to_dict('records')\n\n return jsonify({'data': result_dict})\n\[email protected]('/api/social/total', methods=['GET'])\ndef get_social_risk():\n\n result_df = query_db('''SELECT 'youtube' AS platform, youtube_user_rank AS social_rank, COUNT(id) AS total FROM customer GROUP BY youtube_user_rank\n UNION ALL\n SELECT 'facebook' AS platform, facebook_user_rank AS social_rank, COUNT(id) AS total FROM customer GROUP BY facebook_user_rank;''')\n result_dict = result_df.to_dict('records')\n\n return jsonify({'data': result_dict})\n\nif __name__ == '__main__':\n app.run()\n" }, { "alpha_fraction": 0.39024388790130615, "alphanum_fraction": 0.6585366129875183, "avg_line_length": 13, "blob_id": "eea3d9e8fbdd677d9eeec6fdb196ed9e2b3aeaa7", "content_id": "def88ef19ee786cf583e660150f4ae83d02a840e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 41, "license_type": "no_license", "max_line_length": 14, "num_lines": 3, "path": "/requirements.txt", "repo_name": "hmltnbrn/massm-project", "src_encoding": "UTF-8", "text": "Flask==1.1.2\nJinja2==2.11.1\npandas==1.0.3" } ]
3
mariswethz/smtp
https://github.com/mariswethz/smtp
2a354dd808535a6fdeb0bd20ee348ee2c8bed4c5
9c3a84000ffd880ab7a47ad3580199b26561120b
e55d330e2bba9689c356d48f7cea36a3ed90e9b7
refs/heads/master
2020-03-31T21:17:24.717589
2018-10-11T10:38:47
2018-10-11T10:38:47
152,574,753
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7113401889801025, "alphanum_fraction": 0.7113401889801025, "avg_line_length": 23.375, "blob_id": "ff65866fb4e5d9ca52a6cecd29a42bd9139078cd", "content_id": "d28ecb6ec9762057c8d1070ed0e066f078a2ec14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 194, "license_type": "no_license", "max_line_length": 40, "num_lines": 8, "path": "/smtp.py", "repo_name": "mariswethz/smtp", "src_encoding": "UTF-8", "text": "import smtplib\nserver=smtplib.SMTP('smtp.gmail.com')\nserver.starttls()\nserver.login(\"[email protected]\",\"melumaria\")\nmsg = \"Hello!\"\nserver.sendmail(\"[email protected]\",\"[email protected]\",msg)\nprint('msg sent')\nserver.quit()" } ]
1
ermakvv/DjangoBlog
https://github.com/ermakvv/DjangoBlog
7fea6cfa053aa52ac6cd9ec8c27a41aad4f85dee
aee7b2c75e5a3e1573c13834a0b3d2beea4f121b
c7837c37ef532a78f10108941d1b687de183aa4b
refs/heads/master
2020-04-11T22:31:58.405697
2019-01-04T18:30:47
2019-01-04T18:30:47
162,139,265
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6569459438323975, "alphanum_fraction": 0.6601272821426392, "avg_line_length": 33.29090881347656, "blob_id": "05e992ed95d73d088f50aa9f1a543a5fa6ead1d9", "content_id": "7c07d224b2a78e34d9b6f26822567377a4a4d655", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2214, "license_type": "no_license", "max_line_length": 68, "num_lines": 55, "path": "/blogs/views.py", "repo_name": "ermakvv/DjangoBlog", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.urls import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom .models import BlogPost\nfrom .forms import BlogForm\n\n# Create your views here.\ndef index(request):\n \"\"\"\n Домашняя страница приложения Blogs.\n Выводит список всех постов в хронологическом порядке\n \"\"\"\n blogs = BlogPost.objects.order_by('-date_added')\n context = {'blogs': blogs}\n return render(request, 'blogs/index.html', context)\n\n@login_required\ndef new_post(request):\n \"\"\"Определяет новый пост в блогах.\"\"\"\n if request.method != 'POST':\n # Данные не отправлялись; создается пустая форма.\n form = BlogForm()\n else:\n # Отправлены данные POST; обработать данные.\n form = BlogForm(request.POST)\n if form.is_valid():\n new_post = form.save(commit = False)\n new_post.owner = request.user\n form.save()\n return HttpResponseRedirect(reverse('blogs:index'))\n \n context = {'form': form}\n return render(request, 'blogs/new_post.html', context)\n\n@login_required\ndef edit_post(request, post_id):\n \"\"\"Редактирует существующую запись.\"\"\"\n post = BlogPost.objects.get(id=post_id)\n \"\"\"Проверка поста на пренадлежность текущему пользователю.\"\"\"\n if post.owner != request.user:\n raise Http404\n \n if request.method != 'POST':\n # Исходный запрос; форма заполняется данными текущей записи.\n form = BlogForm(instance=post)\n else:\n # Отправка данных POST; обработать данные.\n form = BlogForm(instance=post, data=request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('blogs:index'))\n \n context = {'post': post, 'form': form}\n return render(request, 'blogs/edit_post.html', context)\n" }, { "alpha_fraction": 0.6454293727874756, "alphanum_fraction": 0.6454293727874756, "avg_line_length": 29.16666603088379, "blob_id": "01ef9329594520aca9ffd1aecae5cd0f165e59da", "content_id": "392f2addd75e7825dda9baf90c3f51025dfb70bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 439, "license_type": "no_license", "max_line_length": 77, "num_lines": 12, "path": "/blogs/urls.py", "repo_name": "ermakvv/DjangoBlog", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n # Домашняя страница.\n url(r'^$', views.index, name='index'),\n # Страница для добавления нового поста.\n url(r'^new_post/$', views.new_post, name='new_post'),\n # Страница для редактирования поста.\n url(r'^edit_post/(?P<post_id>\\d+)/$', views.edit_post, name='edit_post'),\n]" } ]
2
apbraga/Courses
https://github.com/apbraga/Courses
63b9b95ec6a4ab9e02850865caa51aba0d5089c4
f35f9f3a1404f60eb0cb8855b84ddf1888bc593c
9aa8653601b4775fc6d8d768f989fc4e69c4f257
refs/heads/master
2023-04-01T06:35:45.921733
2020-03-31T12:43:13
2020-03-31T12:43:13
223,588,784
0
1
null
2019-11-23T12:58:07
2020-06-16T22:12:49
2023-03-24T23:49:56
C++
[ { "alpha_fraction": 0.6239103078842163, "alphanum_fraction": 0.6508094668388367, "avg_line_length": 32.74789810180664, "blob_id": "8e5ba64819ccff6a5c40303671f4ed636b325251", "content_id": "96394f100c3ca66e544033c6669f456d918eff01", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4015, "license_type": "permissive", "max_line_length": 106, "num_lines": 119, "path": "/Udacity Autonomous Vehicle Engineer Nanodegree/04 Behavioural Cloning/model.py", "repo_name": "apbraga/Courses", "src_encoding": "UTF-8", "text": "#Dependencies are imported\nimport csv\nimport numpy as np\nimport os\nimport cv2\nimport math\nimport pandas as pd\nimport time\nimport argparse\nimport json\nimport sys\nimport json\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras.layers import Dense, Dropout, Flatten, Lambda, Activation, ELU, Conv2D, Cropping2D\nfrom keras.optimizers import Adam\nimport matplotlib.image as mpimg\nfrom sklearn.model_selection import train_test_split\n\n#Load data from csv file to pandas dataframe\ndef load_dataset():\n data_df = pd.read_csv(os.path.join('data', 'driving_log.csv'))\n #drop 90% of data with steering = 0 to balance the dataset\n data_df = data_df[data_df['steering'] != 0].append(data_df[data_df['steering'] == 0].sample(frac=0.1))\n #separated the dataframe data into input and output \n X = data_df[['center', 'left', 'right']].values\n y = data_df['steering'].values\n return X, y\n\n#Mirror image for augmentation\ndef flip(image, measurement):\n #apply flip image\n image = np.fliplr(image)\n #reverse steering actuation\n measurement = -measurement\n return image, measurement\n\n#increase dataset with augmentation\ndef augment_data(X,y):\n #initialize array\n X_aug=[]\n y_aug=[]\n #add right, center and left data into a single array, adjust right and left angles by 0.2 \n for i in range(len(y)):\n X_aug.append(X[i][0])\n X_aug.append(X[i][1])\n X_aug.append(X[i][2])\n y_aug.append(y[i] + 0.0) \n y_aug.append(y[i] + 0.2) \n y_aug.append(y[i] - 0.2)\n # initialize array\n x_out = []\n y_out = []\n #shuffle image index before loading\n idx = np.arange(len(y_aug))\n idx = np.random.shuffle(idx)\n for i in range(len(y_aug)):\n #get each image file path\n file_path = str('/home/workspace/CarND-Behavioral-Cloning-P3/data/'+X_aug[i].strip())\n #read image as rgb\n x_i= cv2.cvtColor(cv2.imread(file_path),cv2.COLOR_BGR2RGB)\n # add image and respective steering anlge to an array\n x_out.append(x_i)\n y_out.append(y_aug[i])\n #flip each image and add to an array\n X_i_flip, y_i_flip = flip(x_i, y_aug[i])\n x_out.append(X_i_flip)\n y_out.append(y_i_flip)\n return np.array(x_out), np.array(y_out)\n\n#Create network architecture\ndef model_build():\n #Model Definition based on Project 3 network\n model = keras.Sequential()\n model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160,320,3)))\n model.add(Cropping2D(cropping=((60,25),(0,0)))) \n model.add(Conv2D(16, (5, 5), strides=(2,2), activation=\"relu\"))\n model.add(Dropout(0.2))\n model.add(Conv2D(32, (5, 5), strides=(2, 2), activation=\"relu\"))\n model.add(Dropout(0.2))\n model.add(Conv2D(64, (5, 5), strides=(2, 2), activation=\"relu\"))\n model.add(Dropout(0.2))\n model.add(Conv2D(128, (3, 3), activation=\"relu\"))\n model.add(Dropout(0.2))\n #model.add(keras.layers.MaxPooling2D(pool_size=(3,3),strides= 2))\n model.add(Conv2D(256, (3, 3), activation=\"relu\"))\n model.add(Flatten())\n #model.add(Dense(100))\n #model.add(Dense(50))\n #model.add(Dense(10))\n model.add(Dense(1))\n model.summary()\n exit()\n model.compile(loss='mse', optimizer='adam')\n return model \n\ndef train_model(model, n_epochs, batch_size, X_train, y_train ): \n \n #Fit model, (fit_generator was the first trial, but due to performance issues it was changed to fit)\n model.fit(X_train, y_train, batch_size=batch_size, epochs=n_epochs, validation_split=0.1)\n\n#project pipeline\ndef main():\n #Load image path and steering angles\n X, y = load_dataset()\n #Load images\n X_train, y_train = augment_data(X,y)\n #create neural net\n model = model_build()\n n_epochs = 3\n batch_size = 64\n #train model\n train_model(model, n_epochs, batch_size, X_train, y_train) \n #exported trained model\n model.save('model.h5') \n\nmain()" }, { "alpha_fraction": 0.59410160779953, "alphanum_fraction": 0.6346085667610168, "avg_line_length": 42.07143020629883, "blob_id": "de05d68a6ae3963d446f1fa4774525faa7bff79e", "content_id": "1cac0e31ef888d35f5315a55dafa345de7d0ba46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16886, "license_type": "no_license", "max_line_length": 203, "num_lines": 392, "path": "/Udacity Autonomous Vehicle Engineer Nanodegree/02 Advanced Finding Lanes/Project2_Advanced_Line_Detection.py", "repo_name": "apbraga/Courses", "src_encoding": "UTF-8", "text": "\n\nimport numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\nimport pickle\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\n\ndef calibrate ():\n # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\n objp = np.zeros((6*9,3), np.float32)\n objp[:,:2] = np.mgrid[0:9, 0:6].T.reshape(-1,2)\n\n # Arrays to store object points and image points from all the images.\n objpoints = [] # 3d points in real world space\n imgpoints = [] # 2d points in image plane.\n\n # Make a list of calibration images\n images = glob.glob('camera_cal/calibration*.jpg')\n\n # Step through the list and search for chessboard corners\n for idx, fname in enumerate(images):\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (9,6), None)\n\n # If found, add object points, image points\n if ret == True:\n objpoints.append(objp)\n imgpoints.append(corners)\n\n # Test undistortion on an image\n img = cv2.imread('test_images/test4.jpg')\n img_size = (img.shape[1], img.shape[0])\n\n # Do camera calibration given object points and image points\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size,None,None)\n\n return mtx, dist\n\ndef tresholding(img, s_thresh, luv_tres, lab_tres ,sx_thresh):\n # Convert to HLS color space and separate the V channel\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n hls_l_channel = hls[:,:,1]\n s_channel = hls[:,:,2]\n\n luv = cv2.cvtColor(img, cv2.COLOR_RGB2Luv)\n l_channel = luv[:,:,0]\n lab = cv2.cvtColor(img, cv2.COLOR_RGB2Lab)\n b_channel = lab[:,:,2]\n\n # Sobel x\n sobelx = cv2.Sobel(hls_l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x\n abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal\n scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))\n\n # Threshold x gradient\n s1_binary = np.zeros_like(scaled_sobel)\n s1_binary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1\n\n # Threshold color channel\n s2_binary = np.zeros_like(scaled_sobel)\n s2_binary[(l_channel >= luv_tres[0]) & (l_channel <= luv_tres[1])] = 1\n\n # Threshold color channel\n s3_binary = np.zeros_like(scaled_sobel)\n s3_binary[(b_channel >= lab_tres[0]) & (b_channel <= lab_tres[1])] = 1\n\n # Threshold color channel\n s4_binary = np.zeros_like(s_channel)\n s4_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1\n\n # Stack each channel\n color_binary = np.dstack((s1_binary, s2_binary, s3_binary+s4_binary ))*255\n ret, binary = cv2.threshold(cv2.cvtColor(color_binary,cv2.COLOR_BGR2GRAY), 10, 255, cv2.THRESH_BINARY)\n\n\n return binary\n\ndef perspective(img):\n img_size = (img.shape[1],img.shape[0])\n src = np.float32([[715,466],[1006,654],[314,656],[575, 466]])\n dst = np.float32([[990,0],[990,720],[290,720],[290,0]])\n M = cv2.getPerspectiveTransform(src, dst)\n warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)\n return warped\n\ndef find_lane_pixels(binary_warped):\n\n histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)\n out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255\n midpoint = np.int(histogram.shape[0]//2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n # HYPERPARAMETERS\n # Choose the number of sliding windows\n nwindows = 9\n # Set the width of the windows +/- margin\n margin = 100\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.int(binary_warped.shape[0]//nwindows)\n # Identify the x and y positions of all nonzero (i.e. activated) pixels in the image\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\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 for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = binary_warped.shape[0] - (window+1)*window_height\n win_y_high = binary_warped.shape[0] - window*window_height\n ### TO-DO: Find the four below boundaries of the window ###\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\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),\n (win_xright_high,win_y_high),(0,255,0), 2)\n\n ### TO-DO: Identify the nonzero pixels in x and y within the window ###\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_xright_low) & (nonzerox < win_xright_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 mean position ###\n if len(good_left_inds) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n if len(good_right_inds) > minpix:\n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n\n # Concatenate the arrays of indices (previously was a list of lists of pixels)\n try:\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n except ValueError:\n # Avoids an error if the above is not implemented fully\n pass\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\n return leftx, lefty, rightx, righty, out_img\n\ndef search_around_poly(warped,left_fit, right_fit):\n # HYPERPARAMETER\n # Choose the width of the margin around the previous polynomial to search\n # The quiz grader expects 100 here, but feel free to tune on your own!\n margin = 50\n\n # Grab activated pixels\n nonzero = 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)) & (nonzerox < (left_fit[0]*(nonzeroy**2) +left_fit[1]*nonzeroy + left_fit[2] + margin)))\n\n right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy +right_fit[2] - margin)) & (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, right_fit = fit_poly(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((warped, warped, 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]] = [255, 0, 0]\n out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [255, 0, 0]\n\n return leftx, lefty, rightx, righty, out_img\n\ndef getPoly(warped, poly_left_old, poly_right_old):\n global a\n poly_left_new=np.array([ 0., 0., 0.])\n poly_right_new=np.array([ 0., 0., 0.])\n if a == 0:\n leftx, lefty, rightx, righty, out_img = find_lane_pixels(warped)\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n poly_left_new=left_fit\n poly_right_new=right_fit\n a=1\n else:\n\n try:\n leftx, lefty, rightx, righty, out_img = search_around_poly(warped,poly_left_old, poly_right_old)\n 1/len(rightx)\n 1/len(leftx)\n except:\n leftx, lefty, rightx, righty, out_img = find_lane_pixels(warped)\n\n\n try:\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n poly_left_new[0] = poly_left_old[0]*0.8 +left_fit[0]*0.2\n poly_left_new[1] = poly_left_old[1]*0.8 +left_fit[1]*0.2\n poly_left_new[2] = poly_left_old[2]*0.8 +left_fit[2]*0.2\n poly_right_new[0] = poly_right_old[0]*0.8 +right_fit[0]*0.2\n poly_right_new[1] = poly_right_old[1]*0.8 +right_fit[1]*0.2\n poly_right_new[2] = poly_right_old[2]*0.8 +right_fit[2]*0.2\n y_lenght = np.linspace(0, warped.shape[0]-1, warped.shape[0])\n left_fitx = poly_left_new[0]*y_lenght**2 + poly_left_new[1]*y_lenght + poly_left_new[2]\n right_fitx = poly_right_new[0]*y_lenght**2 + poly_right_new[1]*y_lenght + poly_right_new[2]\n imgpoints = (y_lenght.astype(int), left_fitx.astype(int),right_fitx.astype(int))\n mask = np.zeros((warped.shape[0],warped.shape[1],3), np.uint8)\n mask[ y_lenght.astype(int) , left_fitx.astype(int)] = [255,255,0]\n mask[ y_lenght.astype(int) , right_fitx.astype(int)] = [255,255,0]\n\n except:\n poly_left_new = poly_left_old\n poly_right_new = poly_right_old\n\n return poly_left_new, poly_right_new ,out_img\n\ndef lane_area_draw(img,left_fit, right_fit):\n #create lane area image\n img_size = (img.shape[1],img.shape[0])\n mask = np.zeros((img.shape[0],img.shape[1],3), np.uint8)\n y_lenght = np.linspace(0, img.shape[0]-1, img.shape[0])\n left_fitx = left_fit[0]*y_lenght**2 + left_fit[1]*y_lenght + left_fit[2]\n right_fitx = right_fit[0]*y_lenght**2 + right_fit[1]*y_lenght + right_fit[2]\n imgpoints = (y_lenght.astype(int), left_fitx.astype(int),right_fitx.astype(int))\n mask[ y_lenght.astype(int) , np.clip(left_fitx.astype(int),0,1279)] = [255,255,0]\n mask[ y_lenght.astype(int) , np.clip(right_fitx.astype(int),0,1279)] = [255,255,0]\n\n th, im_th = cv2.threshold(mask, 128,255, cv2.THRESH_BINARY)\n im_floodfill = im_th.copy()\n h, w = im_th.shape[:2]\n mask = np.zeros((h + 2, w + 2), np.uint8)\n cv2.floodFill(im_floodfill, mask, (int(img.shape[1]/2),int(img.shape[0]/2)), 255);\n fill_image = im_th | im_floodfill\n return fill_image\n\ndef unwarped(fill_image):\n #unwarp lane area images\n src = np.float32([[715,466],[1006,654],[314,656],[575, 466]])\n dst = np.float32([[990,0],[990,720],[290,720],[290,0]])\n\n M = cv2.getPerspectiveTransform(dst, src)\n unwarped = cv2.warpPerspective(fill_image, M, (fill_image.shape[1],fill_image.shape[0]), flags=cv2.INTER_LINEAR)\n\n return unwarped\n\ndef curvature(unwarped,left_fit, right_fit):\n y_lenght = np.linspace(0, unwarped.shape[0]-1, unwarped.shape[0])\n left_fitx = left_fit[0]*y_lenght**2 + left_fit[1]*y_lenght + left_fit[2]\n right_fitx = right_fit[0]*y_lenght**2 + right_fit[1]*y_lenght + right_fit[2]\n #Calculate curvature\n ym_per_pix = 14.4/720 # meters per pixel in y dimension\n xm_per_pix = 3.7/700 # meters per pixel in x dimension\n y_eval = 720\n left_fit_cr = np.polyfit(y_lenght*ym_per_pix, left_fitx*xm_per_pix, 2)\n right_fit_cr = np.polyfit(y_lenght*ym_per_pix, right_fitx*xm_per_pix, 2)\n\n left_curverad = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])\n right_curverad = ((1 + (2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])\n\n curve=(left_curverad+right_curverad)/2\n\n if curve > 20000.:\n curve_text = \"straight\"\n else:\n curve_text = str(int(right_curverad))+\" m\"\n\n out = cv2.putText(unwarped, \"Radius Curvature: \"+ curve_text , (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2, lineType=cv2.LINE_AA)\n\n #off center calculation\n off_center= ((left_fitx[-1]+right_fitx[-1])/2-unwarped.shape[1]/2)*xm_per_pix\n off_center_txt = \"Distance from center:\" + format(off_center, '.2f') + \" m \"\n out = cv2.putText(unwarped, off_center_txt, (100, 150), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2, lineType=cv2.LINE_AA)\n return unwarped\n\ndef process_image(img):\n #Apply distortion transformation for input image\n #img = cv2.imread('test_images/straight_lines1.jpg')\n #plt.imshow(img)\n global a\n global left_fit\n global right_fit\n global poly_left\n global poly_right\n\n undist = cv2.undistort(img, mtx, dist, None, mtx)\n binary = tresholding(undist,s_thresh=(150, 255), luv_tres=(225, 255), lab_tres=(155,200),sx_thresh=(50, 100))\n warped = perspective (binary)\n poly_left, poly_right, box = getPoly(warped, poly_left, poly_right)\n mask = lane_area_draw(warped,poly_left, poly_right)\n unwarp = unwarped(mask)\n curve = curvature(unwarp,poly_left, poly_right)\n out_img = cv2.addWeighted(undist, 1.0, curve, 0.5, 0.)\n return out_img\n\nmtx, dist = calibrate()\ncv2.imwrite('output_images/calibrated_chessboard.jpg',cv2.undistort(cv2.imread('camera_cal/calibration1.jpg'), mtx, dist, None, mtx))\n\ndef processVideo(file):\n global a\n global left_fit\n global right_fit\n global poly_left\n global poly_right\n a=0\n poly_left = np.array([ 0., 0., 0.])\n poly_right = np.array([ 0., 0., 0.])\n left_fit = np.array([ 0., 0., 0.])\n right_fit = np.array([ 0., 0., 0.])\n white_output = 'process_'+file+'.mp4'\n clip1 = VideoFileClip(file)\n white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\n %time white_clip.write_videofile(white_output, audio=False)\n\nprocessVideo('project_video.mp4')\n\ndef generate_examples(fname,idx):\n global a\n global left_fit\n global right_fit\n global poly_left\n global poly_right\n\n a=0\n poly_left = np.array([ 0., 0., 0.])\n poly_right = np.array([ 0., 0., 0.])\n left_fit = np.array([ 0., 0., 0.])\n right_fit = np.array([ 0., 0., 0.])\n img = cv2.imread(fname)\n\n undist = cv2.undistort(img, mtx, dist, None, mtx)\n binary = tresholding(undist,s_thresh=(150, 255), luv_tres=(225, 255), lab_tres=(155,200),sx_thresh=(50, 100))\n warped = perspective (binary)\n poly_left, poly_right, box_search = getPoly(warped, poly_left, poly_right)\n\n y_lenght = np.linspace(0, warped.shape[0]-1, warped.shape[0])\n left_fitx = poly_left[0]*y_lenght**2 + poly_left[1]*y_lenght + poly_left[2]\n right_fitx = poly_right[0]*y_lenght**2 + poly_right[1]*y_lenght + poly_right[2]\n lines = np.zeros((warped.shape[0],warped.shape[1],3), np.uint8)\n lines[ y_lenght.astype(int) , np.clip(left_fitx.astype(int),0,1279)] = [0,255,255]\n lines[ y_lenght.astype(int) , np.clip(right_fitx.astype(int),0,1279)] = [0,255,255]\n lines = cv2.addWeighted(lines, 1.0, box_search, 1, 0.)\n\n mask = lane_area_draw(warped,poly_left, poly_right)\n unwarp = unwarped(cv2.addWeighted(mask, 1.0, lines, 1, 0.))\n curve = curvature(unwarp,poly_left, poly_right)\n out_img = cv2.addWeighted(undist, 1.0, curve, 0.5, 0.)\n\n cv2.imwrite('output_images/'+str(idx+1)+'test.jpg',img)\n cv2.imwrite('output_images/'+str(idx+1)+'undist.jpg',undist)\n cv2.imwrite('output_images/'+str(idx+1)+'binary.jpg',binary)\n cv2.imwrite('output_images/'+str(idx+1)+'warped.jpg',warped)\n cv2.imwrite('output_images/'+str(idx+1)+'lines.jpg',lines)\n cv2.imwrite('output_images/'+str(idx+1)+'mask.jpg',mask)\n cv2.imwrite('output_images/'+str(idx+1)+'unwarp.jpg',unwarp)\n cv2.imwrite('output_images/'+str(idx+1)+'curve.jpg',curve)\n cv2.imwrite('output_images/'+str(idx+1)+'out_img.jpg',out_img)\n\nimages = sorted(glob.glob('test_images/test*.jpg'))\nfor idx, fname in enumerate(images):\n generate_examples(fname,idx)\n" }, { "alpha_fraction": 0.6370806097984314, "alphanum_fraction": 0.683464765548706, "avg_line_length": 51.3146858215332, "blob_id": "60355f6e9c2f18f8e6e041697a2b498aef09140f", "content_id": "f8668f771b7c4975206bb2ca5d12f3727fa82c12", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7481, "license_type": "permissive", "max_line_length": 351, "num_lines": 143, "path": "/Udacity Autonomous Vehicle Engineer Nanodegree/04 Behavioural Cloning/writeup_report.md", "repo_name": "apbraga/Courses", "src_encoding": "UTF-8", "text": "# **Behavioral Cloning** \n\n\n**Behavioral Cloning Project**\n\nThe goals / steps of this project are the following:\n* Use the simulator to collect data of good driving behavior\n* Build, a convolution neural network in Keras that predicts steering angles from images\n* Train and validate the model with a training and validation set\n* Test that the model successfully drives around track one without leaving the road\n* Summarize the results with a written report\n\n\n[//]: # (Image References)\n\n[image1]: ./examples/placeholder.png \"Model Visualization\"\n[image2]: ./examples/placeholder.png \"Grayscaling\"\n[image3]: ./examples/placeholder_small.png \"Recovery Image\"\n[image4]: ./examples/placeholder_small.png \"Recovery Image\"\n[image5]: ./examples/placeholder_small.png \"Recovery Image\"\n[image6]: ./examples/placeholder_small.png \"Normal Image\"\n[image7]: ./examples/placeholder_small.png \"Flipped Image\"\n\n## Rubric Points\n### Here I will consider the [rubric points](https://review.udacity.com/#!/rubrics/432/view) individually and describe how I addressed each point in my implementation. \n\n---\n### Files Submitted & Code Quality\n\n#### 1. Submission includes all required files and can be used to run the simulator in autonomous mode\n\nMy project includes the following files:\n* model.py containing the script to create and train the model\n* drive.py for driving the car in autonomous mode (Speed changed from 9 to 20)\n* model.h5 containing a trained convolution neural network \n* writeup_report.md or writeup_report.pdf summarizing the results\n\n#### 2. Submission includes functional code\nUsing the Udacity provided simulator and my drive.py file, the car can be driven autonomously around the track by executing \n```sh\npython drive.py model.h5\n```\n\n#### 3. Submission code is usable and readable\n\nThe model.py file contains the code for training and saving the convolution neural network. The file shows the pipeline I used for training and validating the model, and it contains comments to explain how the code works.\n\n### Model Architecture and Training Strategy\n\n#### 1. An appropriate model architecture has been employed\n\nMy model consists of a 5 layer convolution neural network with 5x5 and 3x3 filter sizes and depths between 32 and 256 (model.py lines 74) and a single neuron as output .\n\nThe model includes RELU layers to introduce nonlinearity (code line 74), and the data is normalized in the model using a Keras lambda layer (code line 77).\n\nInput is also cropped within the model to remove the unwanted top and bottom portion of the image( model.py line 78). \n\n| Layer \t\t| Output shape\t \t\t\t\t\t| Number of trainable parameter |\n|:---------------------:|:---------------------------------------------:|:--------------|\n| lambda_1 (Lambda) \t\t| (None, 160, 320, 3) \t\t\t\t\t\t\t| 0|\n| cropping2d_1 (Cropping2D) \t| (None, 36, 158, 16) \t| 0|\n| conv2d_1 (Conv2D) \t\t\t\t|\t(None, 36, 158, 16) \t\t\t\t\t\t\t\t\t\t\t| 1216|\n| dropout_1 (Dropout)) \t| (None, 36, 158, 16) \t\t\t\t| 0|\n| conv2d_2 (Conv2D) \t | (None, 16, 77, 32) \t\t\t\t\t\t| 12832|\n| dropout_1 (Dropout)\t| (None, 16, 77, 32) \t\t\t\t\t\t\t\t\t|0 |\n| conv2d_3 (Conv2D) \t\t\t| (None, 6, 37, 64) \t\t\t\t\t\t\t\t\t| 51264|\n|\tdropout_1 (Dropout)\t\t\t\t|\t(None, 6, 37, 64)\t\t\t\t\t\t\t\t\t\t\t| 0|\n|\tconv2d_4 (Conv2D) \t\t\t\t|\t\t(None, 4, 35, 128)\t\t\t\t\t\t\t\t\t\t| 73856|\n|\tdropout_4 (Dropout)\t\t\t\t|\t\t(None, 4, 35, 128)\t\t\t\t\t\t\t| 0|\n|\tconv2d_5 (Conv2D)\t\t\t\t|\t\t\t(None, 2, 33, 256)\t\t\t\t\t\t\t\t\t|295168 |\n|\tFlatten\t\t\t\t\t|\t\t\t\t(None, 16896)\t\t\t\t\t\t\t\t| 0|\n|\tSoftmax\t\t\t\t\t|\t\t\t(None, 1)\t\t\t\t\t\t\t\t\t| 16897|\n\nTotal params: 451,233\n\nTrainable params: 451,233\n\nNon-trainable params: 0\n\n#### 2. Attempts to reduce overfitting in the model\n\nThe model contains dropout layers in order to reduce overfitting (model.py lines 80, 82, 84, 86). \n\nThe model was trained and validated on different data sets to ensure that the model was not overfitting (code line 102). The model was tested by running it through the simulator and ensuring that the vehicle could stay on the track.\n\n#### 3. Model parameter tuning\n\nThe model used an adam optimizer, so the learning rate was not tuned manually (model.py line 96).\n\n#### 4. Appropriate training data\n\nThe dataset provided by udacity was used for the training. Data augmentation was used to scale up to 20k training samples.\n\nImages for the left and right camera were used combined with a drift on the steering angle, and each image was flipped in the horizontal axis and its steering angle inverted. \n\nFor details about how I created the training data, see the next section. \n\n### Model Architecture and Training Strategy\n\n#### 1. Solution Design Approach\n\nThe overall strategy for deriving a model architecture was to build a network general enough to handle parts of the track that had few samples in training, so a great effort to reduce overfitting was done, as result dropout layers gave the best performance, as well as removing the fully connected layer within the output and the convolutional layers.\n\nMy first step was to use a convolution neural network model similar to the Nvidia, but during training it would overfit rather quickly, leading to the collection of more data.\n\nThen i borrow the network developed in the last project for traffic sign recognition, and on trial and error it was decided to remove the max pooling layers, remove one conv layer and add more dropouts.\n\nThis resulted in a good generality after only 3 epochs.\n\nFor all the trials it was used Adam optimization and MSE as loss function.\nThe final step was to run the simulator to see how well the car was driving around track one. \n\nAt the end of the process, the vehicle is able to drive autonomously around the track without leaving the road.\n\n#### 2. Final Model Architecture\n\nThe final model architecture (model.py lines 74) consisted of a convolution neural network with the following layers and layer sizes:\n| Layer \t\t| Output shape\t \t\t\t\t\t| Number of trainable parameter |\n|:---------------------:|:---------------------------------------------:|:--------------|\n| lambda_1 (Lambda) \t\t| (None, 160, 320, 3) \t\t\t\t\t\t\t| 0|\n| cropping2d_1 (Cropping2D) \t| (None, 36, 158, 16) \t| 0|\n| conv2d_1 (Conv2D) \t\t\t\t|\t(None, 36, 158, 16) \t\t\t\t\t\t\t\t\t\t\t| 1216|\n| dropout_1 (Dropout)) \t| (None, 36, 158, 16) \t\t\t\t| 0|\n| conv2d_2 (Conv2D) \t | (None, 16, 77, 32) \t\t\t\t\t\t| 12832|\n| dropout_1 (Dropout)\t| (None, 16, 77, 32) \t\t\t\t\t\t\t\t\t|0 |\n| conv2d_3 (Conv2D) \t\t\t| (None, 6, 37, 64) \t\t\t\t\t\t\t\t\t| 51264|\n|\tdropout_1 (Dropout)\t\t\t\t|\t(None, 6, 37, 64)\t\t\t\t\t\t\t\t\t\t\t| 0|\n|\tconv2d_4 (Conv2D) \t\t\t\t|\t\t(None, 4, 35, 128)\t\t\t\t\t\t\t\t\t\t| 73856|\n|\tdropout_4 (Dropout)\t\t\t\t|\t\t(None, 4, 35, 128)\t\t\t\t\t\t\t| 0|\n|\tconv2d_5 (Conv2D)\t\t\t\t|\t\t\t(None, 2, 33, 256)\t\t\t\t\t\t\t\t\t|295168 |\n|\tFlatten\t\t\t\t\t|\t\t\t\t(None, 16896)\t\t\t\t\t\t\t\t| 0|\n|\tSoftmax\t\t\t\t\t|\t\t\t(None, 1)\t\t\t\t\t\t\t\t\t| 16897|\n\n#### 3. Creation of the Training Set & Training Process\n\nThe dataset provided by udacity was used for the training. Data augmentation was used to scale up to 20k training samples.\n\nImages for the left and right camera were used combined with a drift on the steering angle, and each image was flipped in the horizontal axis and its steering angle inverted. \n\n\nOne key point that gave a great leap on performance was to drop around 90% of the data points with steering angle =0, the dataset is very unbalanced so this helps the model to learn more about curve and not overfitting on straight condition.\n\nCheck out the result in this youtube link: https://youtu.be/FdVlMMWQjcw\n" }, { "alpha_fraction": 0.7380422949790955, "alphanum_fraction": 0.7491657137870789, "avg_line_length": 31.10714340209961, "blob_id": "618c8a8cb17b998f5db8c2a3c9be4c1607ee93a1", "content_id": "678843f09a9937b292ba57fa4f3120263a24c045", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1798, "license_type": "no_license", "max_line_length": 198, "num_lines": 56, "path": "/Udacity Autonomous Vehicle Engineer Nanodegree/01 Finding Lanes/writeup.md", "repo_name": "apbraga/Courses", "src_encoding": "UTF-8", "text": "# **Finding Lane Lines on the Road**\n\n## Writeup\n\nAlex Braga | [email protected]\n\n---\n\n**Finding Lane Lines on the Road**\n\nThe goals / steps of this project are the following:\n* Make a pipeline that finds lane lines on the road\n* Reflect on your work in a written report\n\n\n[//]: # (Image References)\n\n[image1]: ./examples/grayscale.jpg \"Grayscale\"\n\n---\n\n### Reflection\n\n### 1. Describe your pipeline. As part of the description, explain how you modified the draw_lines() function.\n\nMy pipeline consisted of 5 steps.\n\n* Step 1 : Select region of interest\n* Step 2 : Change to gray colorspace\n* Step 3 : Segment based on color intensity\n* Step 4 : Smooth image with filter\n* Step 5 : Get edges mask using Canny\n* Step 6 : Get lines using Hough\n* Step 7 : Draw line on start image\nRepeat for each frame\n\nIn order to draw a single line on the Step 7 the following steps were taken:\n\nLoop each line from Hough\n* Step 1 : calculate slope, bias and X for y = height*2/3\n* Step 2 : Decide if line consisted of left or right traffic lane based on the slope\n* Step 3 : Accumulate slope and X\nEnd Loop\n* Step 4 : Calculate average slope and X\n* Step 5 : Draw average lines\n\n### 2. Identify potential shortcomings with your current pipeline\n\nThe region of interest may be an issue depending on the data, basically it works for the data used in this activity, but is not generic enough to adapt for other video sources.\n\nSegmentation based on color intensity of grayscale image have huge impact on the final result, it does no adapt well enough to shadows or day time.\n\n\n### 3. Suggest possible improvements to your pipeline\n\nOne potential improvement would be to perform the Segmentation based on color instead of intensity, HSV colorspace could be used instead of BRG bringing better accuracy under conditions with shadow.\n" }, { "alpha_fraction": 0.5773400068283081, "alphanum_fraction": 0.6156894564628601, "avg_line_length": 36.79294967651367, "blob_id": "56aacb5591803937fe9a64921a3421afe9a4450c", "content_id": "b3f0714853c98279fe624b05ed050c3f309d719e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8579, "license_type": "no_license", "max_line_length": 247, "num_lines": 227, "path": "/Udacity Autonomous Vehicle Engineer Nanodegree/03 Traffic Sign Classifier/README.md", "repo_name": "apbraga/Courses", "src_encoding": "UTF-8", "text": "# **Traffic Sign Recognition**\nAlex Braga [email protected]\nAutonomous Vehicle Nanodegree | Udacity\n\nhttps://github.com/apbraga/Traffic-Sign-Classifier/blob/master/Traffic_Sign_Classifier.ipynb\n\n## Writeup\n---\n\n**Build a Traffic Sign Recognition Project**\n\nThe goals / steps of this project are the following:\n* Load the data set (see below for links to the project data set)\n* Explore, summarize and visualize the data set\n* Design, train and test a model architecture\n* Use the model to make predictions on new images\n* Analyze the softmax probabilities of the new images\n* Summarize the results with a written report\n\n\n[//]: # (Image References)\n\n[image1]: ./examples/1.png \"Visualization\"\n[image2]: ./examples/2.png \"Grayscaling\"\n[image3]: ./examples/3.png \"Random Noise\"\n[image4]: ./examples/4.png \"Traffic Sign 1\"\n[image5]: ./examples/5.jpeg \"Traffic Sign 2\"\n[image6]: ./examples/6.jpeg \"Traffic Sign 3\"\n[image7]: ./examples/7.jpeg \"Traffic Sign 4\"\n[image8]: ./examples/8.jpeg \"Traffic Sign 5\"\n[image9]: ./examples/9.jpeg \"Traffic Sign 5\"\n---\n\n\n### Data Set Summary & Exploration\n\n#### 1. Summary\n\nUsing numpy library the following information was gathered from the dataset.\n\n* Number of training examples = 34799\n* Number of testing examples = 4410\n* Number of testing examples = 34799\n* Image data shape = (32, 32, 3)\n* Number of classes = 43\n\n#### 2. Include an exploratory visualization of the dataset.\n\nHere is an exploratory visualization of the data set. It is a bar chart showing how the labels are distributed among the datasets for training, validation and testing.\n\n* Training Data Distribution\n\n![alt text][image1]\n\n* Validation Data Distribution\n\n![alt text][image2]\n\n* Test Data Distribution\n\n![alt text][image3]\n\nThe distribution is pretty much similar between the datasets, but not among the labels.\nIn this sense, we may find it difficult to get the Model to predict the traffic signs with small quantity of examples.\n\n### Design and Test a Model Architecture\n\n#### 1. Image Process Pipeline\n\nAs a first step, the image is converted to Grayscale to reduce the effect of color grading among images and the effect of different cameras representing color independently.\n\nThe second step is to Equalize each image according to its histogram to reduce the effect of light condition in each image.\n\nThe third step is to apply a smoothing filter to reduce the effect of noise in the performance of the Model. After testing several filters, the one that provided the best performance for the model was the Laplacian.\n\nAs sanity check we reshape the image to a 32x32x1 image, this will also become handy when we bring images from others sources to be tested.\n\nFinally the 0-255 Grayscale image is transformed into a 0.- 1. matrix.(This provided better model accuracy than using -1 - 1 scale)\n\n``` python\n def preprocess(img):\n out= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n out= cv2.equalizeHist(out)\n out= cv2.Laplacian(out, cv2.CV_64F)\n #out= cv2.bilateralFilter(out, 9, 75, 75)\n #out= cv2.medianBlur(out,5)\n out= out.reshape(32,32,1)\n out= out/255\n return\n```\n\n\n#### 2. Model Architecture\n\nMy final model consisted of the following layers:\n\n| Layer \t\t| Description\t \t\t\t\t\t|\n|:---------------------:|:---------------------------------------------:|\n| Input \t\t| 32x32x1 Image \t\t\t\t\t\t\t|\n| Convolution 1x1 \t| 1x1 stride, same padding, 64 Filters \t|\n| Convolution 5x5\t\t\t\t\t|\t1x1 stride, same padding, 128 Filters \t\t\t\t\t\t\t\t\t\t\t|\n| Max pooling\t3x3 \t| 2x2 stride \t\t\t\t|\n| Convolution 3x3\t | 1x1 stride, same padding, 256 Filters \t\t\t\t\t\t|\n| Max pooling 3x3\t\t| 2x2 stride \t\t\t\t\t\t\t\t\t|\n| Convolution 3x3\t\t\t\t| 1x1 stride, same padding, 512 Filters \t\t\t\t\t\t\t\t\t|\n|\tMax pooling\t\t\t\t\t|\t2x2 stride\t\t\t\t\t\t\t\t\t\t\t|\n|\tDropout\t\t\t\t\t|\t\tRate = 0.2\t\t\t\t\t\t\t\t\t\t|\n|\tFlatten\t\t\t\t\t|\t\t\t\t-\t\t\t\t\t\t\t\t|\n|\tSoftmax\t\t\t\t\t|\t\t\t43 Classes\t\t\t\t\t\t\t\t\t|\n\n#### 3. Training Parameters\n\nTo train the model, I used an the following parameters:\n\n* Loss function: Categorical Crossentropy\n* Optimizer: AdaDelta\n* Metrics: Categorical Accuracy and Top k=5 Categorical Accuracy\n* Batch size: 64\n* epochs: 5\n\n\n#### 4. Model Evaluation\n\nMy final model results were without data augmentation:\n* training set accuracy of 1.0\n* validation set accuracy of 0.9920\n* test set accuracy of 0.9739\n\nMy final model results were with data augmentation:\n* training set accuracy of 0.9995\n* validation set accuracy of 0.9920\n* test set accuracy of 0.9754\n\n\nI started with a Model based on MicronNet (https://arxiv.org/pdf/1804.00497v3.pdf), and from it the first improvements were related to the image processing, deciding the image filter to be applied, finally leading to the Laplacian.\n\nAfter Tweaking training epochs, the model was still achieving accuracy lower the 85%.\nFrom this moment on I started to modify the model architecture, the first big change was to drop the fully connected layers from MicronNet, In my case they were causing the model to underfit, after removing the FC layers the accuracy rose to 0.92.\n\nThe further improvements to reach the final performance level were the optimizer change from Adam to AdaDelta and the filter size on each conv layer, and finally the dropout layer to avoid overfitting.\n\n### Test a Model on New Images\n\n#### 1. External Source images\n\nHere are five German traffic signs that I found on the web:\n\n![alt text][image5] ![alt text][image6] ![alt text][image7]\n![alt text][image8] ![alt text][image9]\n\nReason per image:\n* Stop: High resolution and tilted Sign\n* Bumpy: Complex symbol and tilted sign\n* Priority: Color related sign, to check performance using grayscale\n* Caution: Common sign external shape (triangle) and busy background\n* Intersection Priority: Complex symbol\n\n#### 2. Prediction on external images\n\nHere are the results of the prediction:\n\n| Image\t\t\t | Prediction\t \t\t\t\t\t|\n|:---------------------:|:---------------------------------------------:|\n| Stop Sign \t\t| Stop sign \t\t\t\t\t\t\t\t\t|\n| Bumpy road \t\t\t| Bumpy road \t\t\t\t\t\t\t\t\t\t|\n| Priority road\t\t\t\t\t| Priority road\t\t\t\t\t\t\t\t\t\t\t|\n| General caution\t \t\t| General caution\t\t\t\t\t \t\t\t\t|\n| Right-of-way at the next intersection\t\t| Right-of-way at the next intersection \t\t\t\t\t\t\t|\n\n\nThe model was able to correctly guess 5 of the 5 traffic signs, which gives an accuracy of 80%. This compares favorably to the accuracy on the test set approximately 99%.\n\n#### 3. Top K prediction\n\nFor the first image, the model is relatively sure that this is a stop sign (probability of 0.6), and the image does contain a stop sign. The top five soft max probabilities were\n\n| Probability \t| Prediction\t \t\t\t\t\t|\n|:---------------------:|:---------------------------------------------:|\n| .55 \t\t\t| 14 Stop \t\t\t\t\t\t\t\t\t|\n| .07 \t\t\t\t| 2\tSpeed limit (50km/h)\t\t\t\t\t\t\t\t\t|\n| .06\t\t\t\t\t| 13\tYield\t\t\t\t\t\t\t\t\t\t|\n| .03\t \t\t\t| 8\tNo passing\t\t\t\t \t\t\t\t|\n| .02\t\t\t\t | 5 Speed limit (80km/h) \t\t\t\t\t\t\t|\n\n\nFor the second image ...\n\n| Probability \t| Prediction\t \t\t\t\t\t|\n|:---------------------:|:---------------------------------------------:|\n| .54 \t\t\t| 22 Bumpy road \t\t\t\t\t\t\t\t\t|\n| .13 \t\t\t\t| 25 Road work\t\t\t\t\t\t\t\t\t\t|\n| .13\t\t\t\t\t| 20 Dangerous curve to the right\t\t\t\t\t\t\t\t\t\t\t|\n| .06\t \t\t\t| 26 Traffic signals\t\t\t\t\t \t\t\t\t|\n| .03\t\t\t\t | 13 Yield \t\t\t\t\t\t\t|\n\n\nFor the third image ...\n\n| Probability \t| Prediction\t \t\t\t\t\t|\n|:---------------------:|:---------------------------------------------:|\n| .98 \t\t\t| 12 Priority road \t\t\t\t\t\t\t\t\t|\n| .009 \t\t\t\t| 32 End of all speed and passing limits\t\t\t\t\t\t\t\t\t\t|\n| .0009\t\t\t\t\t| 9\tNo passing\t\t\t\t\t\t\t\t\t\t|\n| .0003 \t\t\t| 15 No vehicles\t\t\t\t\t \t\t\t\t|\n| .0002\t\t\t | 22 Bumpy road \t\t\t\t\t\t\t|\n\n\nFor the fourth image ...\n\n| Probability \t| Prediction\t \t\t\t\t\t|\n|:---------------------:|:---------------------------------------------:|\n| .96 \t\t\t| 18 General caution \t\t\t\t\t\t\t\t\t|\n| .003 \t\t\t\t| 24 Road narrows on the right\t\t\t\t\t\t\t\t\t\t|\n| .00005\t\t\t\t\t| 40 Roundabout mandatory\t\t\t\t\t\t\t\t\t\t\t|\n| .00005\t \t\t\t| 11 Right-of-way at the next intersection\t\t\t\t\t \t\t\t\t|\n| .00004\t\t\t\t | 27 Pedestrians \t\t\t\t\t\t\t|\n\n\nFor the last image ...\n\n| Probability \t| Prediction\t \t\t\t\t\t|\n|:---------------------:|:---------------------------------------------:|\n| .99 \t\t\t| 11 Right-of-way at the next intersection \t\t\t\t\t\t\t\t\t|\n| .00008 \t\t\t\t| 27 \tPedestrians\t\t\t\t\t\t\t\t\t|\n| .00006\t\t\t\t\t| 30\tBeware of ice/snow\t\t\t\t\t\t\t\t\t\t|\n| .00001\t \t\t\t| 31\tWild animals crossing\t\t\t\t \t\t\t\t|\n| .000005\t\t\t\t | 24 Road narrows on the right \t\t\t\t\t\t\t|\n" }, { "alpha_fraction": 0.6595744490623474, "alphanum_fraction": 0.6595744490623474, "avg_line_length": 30, "blob_id": "2ebb9eba433f64d0fe9c47c03c54b39f00e5eb15", "content_id": "50fb9a0bf87ddb4a833d1b03b442fd70628ec49e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "permissive", "max_line_length": 35, "num_lines": 3, "path": "/Udacity Autonomous Vehicle Engineer Nanodegree/04 Behavioural Cloning/prepare_data.py", "repo_name": "apbraga/Courses", "src_encoding": "UTF-8", "text": "\n\n# save training data\nnp.save('X_train', np.array(x_out))\nnp.save('y_train', np.array(y_out))" }, { "alpha_fraction": 0.6448632478713989, "alphanum_fraction": 0.6531780958175659, "avg_line_length": 35.44444274902344, "blob_id": "ced4ffee92e142a03c1bbec0b192c346da8e18d4", "content_id": "fc9ac15d343134e04e89c2c7331648c8b8713390", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10824, "license_type": "permissive", "max_line_length": 171, "num_lines": 297, "path": "/Udacity Autonomous Vehicle Engineer Nanodegree/06 Kidnapped vehicle/src/particle_filter.cpp", "repo_name": "apbraga/Courses", "src_encoding": "UTF-8", "text": "/**\n * particle_filter.cpp\n *\n * Created on: Dec 12, 2016\n * Author: Tiffany Huang\n */\n\n#include \"particle_filter.h\"\n\n#include <math.h>\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <numeric>\n#include <random>\n#include <string>\n#include <vector>\n\n#include \"helper_functions.h\"\n\nusing std::string;\nusing std::vector;\n//adding std library namespace\nusing namespace std;\n\nvoid ParticleFilter::init(double x, double y, double theta, double std[]) {\n /**\n * TODO: Set the number of particles. Initialize all particles to\n * first position (based on estimates of x, y, theta and their uncertainties\n * from GPS) and all weights to 1.\n * TODO: Add random Gaussian noise to each particle.\n * NOTE: Consult particle_filter.h for more information about this method\n * (and others in this file).\n */\n //start random seed\n std:: default_random_engine gen;\n // set particle filter size to 100\n num_particles = 100; \n //create gaussian distributions\n normal_distribution<double> dist_x(x, std[0]);\n normal_distribution<double> dist_y(y, std[1]);\n normal_distribution<double> dist_theta(theta, std[2]);\n //iterate over particles size\n for(int i = 0 ; i < num_particles ; i++){\n //initiate values for each particle\n Particle particle;\n particle.id = i;\n particle.x = dist_x(gen);\n particle.y = dist_y(gen);\n particle.theta = dist_theta(gen);\n particle.weight = 1.0;\n particles.push_back(particle);\n }\n //change initalization flag\n is_initialized = true;\n}\n\nvoid ParticleFilter::prediction(double delta_t, double std_pos[],\n double velocity, double yaw_rate) {\n /**\n * TODO: Add measurements to each particle and add random Gaussian noise.\n * NOTE: When adding noise you may find std::normal_distribution\n * and std::default_random_engine useful.\n * http://en.cppreference.com/w/cpp/numeric/random/normal_distribution\n * http://www.cplusplus.com/reference/random/default_random_engine/\n */\n //start random seed\n std::default_random_engine gen;\n //create gaussian distributions\n normal_distribution<double> dist_x(0,std_pos[0]);\n normal_distribution<double> dist_y(0,std_pos[1]);\n normal_distribution<double> dist_theta(0,std_pos[2]);\n\n //avoid 0 division\n if( fabs( yaw_rate ) > 0.00001){\n // update each particle state using the bicycle model\n for(int i = 0; i < num_particles; i++){\n particles[i].x += (velocity/yaw_rate)*(sin(particles[i].theta + yaw_rate * delta_t) - sin(particles[i].theta)) + dist_x(gen);\n\n particles[i].y += (velocity/yaw_rate)*(cos(particles[i].theta)-cos(particles[i].theta + yaw_rate * delta_t)) + dist_y(gen);\n\n particles[i].theta += yaw_rate * delta_t + dist_theta(gen);\n\n }\n }\n else{\n // update each particle state using the bicycle model\n for(int i = 0; i < num_particles; i++){\n particles[i].x += velocity * delta_t * cos(particles[i].theta) + dist_x(gen);\n\n particles[i].y += velocity * delta_t * sin(particles[i].theta) + dist_x(gen);\n\n particles[i].theta += dist_theta(gen);\n\n }\n\n }\n}\n\nvoid ParticleFilter::dataAssociation(vector<LandmarkObs> predicted,\n vector<LandmarkObs>& observations) {\n /**\n * TODO: Find the predicted measurement that is closest to each\n * observed measurement and assign the observed measurement to this\n * particular landmark.\n * NOTE: this method will NOT be called by the grading code. But you will\n * probably find it useful to implement this method and use it as a helper\n * during the updateWeights phase.\n */\n // start random seed\n std::default_random_engine gen;\n //iterate over all observations\n for( int i = 0; i < observations.size(); i++){\n //set initial values for matching observation and prediction\n double min_dist = numeric_limits<double>::max();\n int map_index = -1;\n //iterate over all predictions\n for( int j = 0; j < predicted.size(); j++){\n // check the distance between observation and predictions\n double distance = dist(observations[i].x,observations[i].y,predicted[j].x,predicted[j].y);\n //pop up the nearest map landmark for each observation\n if(distance < min_dist){\n map_index = predicted[j].id;\n min_dist = distance;\n\n }\n }\n //update the observation id with the landmark value\n observations[i].id = map_index;\n }\n}\n\nvoid ParticleFilter::updateWeights(double sensor_range, double std_landmark[],\n const vector<LandmarkObs> &observations,\n const Map &map_landmarks) {\n /**\n * TODO: Update the weights of each particle using a mult-variate Gaussian\n * distribution. You can read more about this distribution here:\n * https://en.wikipedia.org/wiki/Multivariate_normal_distribution\n * NOTE: The observations are given in the VEHICLE'S coordinate system.\n * Your particles are located according to the MAP'S coordinate system.\n * You will need to transform between the two systems. Keep in mind that\n * this transformation requires both rotation AND translation (but no scaling).\n * The following is a good resource for the theory:\n * https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm\n * and the following is a good resource for the actual equation to implement\n * (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html\n */\n //start random seed\n std::default_random_engine gen;\n // for each particle\n for(int i = 0; i < num_particles; i++){\n\n // initalize vector to store transformed observation\n vector<LandmarkObs> obs_trans;\n //update each observation coordinate from vechicle to map coordinate system\n for(int j = 0; j < observations.size(); j++){\n\n LandmarkObs observed;\n observed.id = observations[j].id;\n observed.x = particles[i].x + (cos(particles[i].theta)*observations[j].x) - (sin(particles[i].theta) * observations[j].y);\n\n observed.y = particles[i].y + (sin(particles[i].theta)*observations[j].x) + (cos(particles[i].theta)* observations[j].y);\n\n obs_trans.push_back(observed);\n\n }\n\n //initialize potential map landmark list\n vector<LandmarkObs> predicted_landmarks;\n //get a list of landmarks within sensor range\n for(int j = 0; j < map_landmarks.landmark_list.size(); j++){\n double distance = dist(map_landmarks.landmark_list[j].x_f, map_landmarks.landmark_list[j].y_f, particles[i].x, particles[i].y);\n\n if(distance <= sensor_range){\n predicted_landmarks.push_back(LandmarkObs {map_landmarks.landmark_list[j].id_i, map_landmarks.landmark_list[j].x_f, map_landmarks.landmark_list[j].y_f});\n }\n }\n\n //link potential landmarks with obervation on map coordinate\n dataAssociation (predicted_landmarks, obs_trans );\n //clear particle weight\n particles[i].weight = 1.0;\n\n //initalize helper values\n double sigma_x_2 = 2*pow(std_landmark[0], 2);\n double sigma_y_2 = 2*pow(std_landmark[1], 2);\n double normalizer = (1.0/(2.0 * M_PI * std_landmark[0] * std_landmark[1]));\n\n //update each particle weights based on the distance between each landmark and observation\n for(int j = 0; j < obs_trans.size(); j++){\n bool found = false;\n int k =0;\n while(!found && k < predicted_landmarks.size()){\n if(predicted_landmarks[k].id == obs_trans[j].id){\n double weight = normalizer * exp( -( pow(obs_trans[j].x-predicted_landmarks[k].x,2)/(sigma_x_2) + (pow(obs_trans[j].y-predicted_landmarks[k].y,2)/(sigma_y_2))));\n if(weight == 0){\n particles[i].weight *= 0.0001;\n } else{\n particles[i].weight *= weight;\n }\n found = true;//break;\n }\n k++;\n }\n }\n //norm_weights += particles[i].weight;\n //add weight to list\n weights.push_back(particles[i].weight);\n }\n\n //for(int i =0; i < num_particles; i++){\n //particles[i].weight /= norm_weights;\n //weights.push_back(particles[i].weight);\n //}\n}\n\nvoid ParticleFilter::resample() {\n /**\n * TODO: Resample particles with replacement with probability proportional\n * to their weight.\n * NOTE: You may find std::discrete_distribution helpful here.\n * http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution\n */\n //std::default_random_engine gen;\n // initalize vector to store the new particles\n vector<Particle> resampled;\n //double mw = *std::max_element(weights.begin(),weights.end());\n //std::uniform_int_distribution<int> un_int_dist(0, num_particles-1);\n //std::uniform_real_distribution<double> un_real_dist(0.0, mw);\n //int index = un_int_dist(gen)%num_particles;\n //double beta =0.0;\n /*\n for(int i = 0; i < num_particles; i++){\n beta += 2.0 * un_real_dist(gen);\n while(beta > weights[index]){\n beta -= weights[index];\n index = (index + 1) % num_particles;\n }\n */\n //start random seed\n random_device rd;\n default_random_engine gen(rd());\n //select particles for next iteration based on the weight\n for(int i = 0; i < num_particles ; i++){\n discrete_distribution<int> index(weights.begin(), weights.end());\n resampled.push_back(particles[index(gen)%num_particles]);\n }\n \n //resampled.push_back(particles[index]);\n //}\n //replace particles\n particles = resampled;\n\n //clear helper variables from memory\n weights.clear();\n resampled.clear();\n}\n\nvoid ParticleFilter::SetAssociations(Particle& particle,\n const vector<int>& associations,\n const vector<double>& sense_x,\n const vector<double>& sense_y) {\n // particle: the particle to which assign each listed association,\n // and association's (x,y) world coordinates mapping\n // associations: The landmark id that goes along with each listed association\n // sense_x: the associations x mapping already converted to world coordinates\n // sense_y: the associations y mapping already converted to world coordinates\n particle.associations= associations;\n particle.sense_x = sense_x;\n particle.sense_y = sense_y;\n}\n\nstring ParticleFilter::getAssociations(Particle best) {\n vector<int> v = best.associations;\n std::stringstream ss;\n copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, \" \"));\n string s = ss.str();\n s = s.substr(0, s.length()-1); // get rid of the trailing space\n return s;\n}\n\nstring ParticleFilter::getSenseCoord(Particle best, string coord) {\n vector<double> v;\n\n if (coord == \"X\") {\n v = best.sense_x;\n } else {\n v = best.sense_y;\n }\n\n std::stringstream ss;\n copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, \" \"));\n string s = ss.str();\n s = s.substr(0, s.length()-1); // get rid of the trailing space\n return s;\n}\n" }, { "alpha_fraction": 0.6232643723487854, "alphanum_fraction": 0.6564841270446777, "avg_line_length": 39.008384704589844, "blob_id": "c58c75c9c974abe99f84eb3b57bec751fd038acd", "content_id": "72aa596eada3d4823c60e99e982b583a04ad19a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19085, "license_type": "no_license", "max_line_length": 240, "num_lines": 477, "path": "/Udacity Autonomous Vehicle Engineer Nanodegree/02 Advanced Finding Lanes/README.md", "repo_name": "apbraga/Courses", "src_encoding": "UTF-8", "text": " Course: Udacity Autonomous Car Engineer\n Project 2: Advanced line detection\n Alex Braga\n\n## Overview\nThis package refer to Project 2 - Advanced Line Detection for Udacity Autonomous Car Engineer Nanodegree.\n\nThe objective is to create a pipeline to detect and dress up a video clip with lane annotation in addition to curvature and off center line estimation.\n\n## Import packages\n\nThe following packages were used for this project and the implementation was done in Pyhton 3.\n\n```python\nimport numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\nimport pickle\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\n```\n\n## Camera Calibration\n\nOpenCV function to get camera calibration matrix were implemented used 20 calibration images of chessboard with a 6x9 grid.\n\n```python\ndef calibrate ():\n # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\n objp = np.zeros((6*9,3), np.float32)\n objp[:,:2] = np.mgrid[0:9, 0:6].T.reshape(-1,2)\n\n # Arrays to store object points and image points from all the images.\n objpoints = [] # 3d points in real world space\n imgpoints = [] # 2d points in image plane.\n\n # Make a list of calibration images\n images = glob.glob('camera_cal/calibration*.jpg')\n\n # Step through the list and search for chessboard corners\n for idx, fname in enumerate(images):\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (9,6), None)\n\n # If found, add object points, image points\n if ret == True:\n objpoints.append(objp)\n imgpoints.append(corners)\n\n # Test undistortion on an image\n img = cv2.imread('test_images/test4.jpg')\n img_size = (img.shape[1], img.shape[0])\n\n # Do camera calibration given object points and image points\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size,None,None)\n\n return mtx, dist\n\nmtx, dist = calibrate()\n\n```\n\n![alt-text-1](output_images/calibrated_chessboard.jpg \"chessboard\")\n\n![alt-text-1](/test_images/test7.jpg \"calibrated_image\")\n\n\n\n## Tresholding\nWith a calibrated image we apply color tresholding in the HLS space and gradients using sobel.\n\n```python\ndef tresholding(img, s_thresh, luv_tres, lab_tres ,sx_thresh):\n # Convert to HLS color space and separate the V channel\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n hls_l_channel = hls[:,:,1]\n s_channel = hls[:,:,2]\n\n luv = cv2.cvtColor(img, cv2.COLOR_RGB2Luv)\n l_channel = luv[:,:,0]\n lab = cv2.cvtColor(img, cv2.COLOR_RGB2Lab)\n b_channel = lab[:,:,2]\n\n # Sobel x\n sobelx = cv2.Sobel(hls_l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x\n abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal\n scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))\n\n # Threshold x gradient\n s1_binary = np.zeros_like(scaled_sobel)\n s1_binary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1\n\n # Threshold color channel\n s2_binary = np.zeros_like(scaled_sobel)\n s2_binary[(l_channel >= luv_tres[0]) & (l_channel <= luv_tres[1])] = 1\n\n # Threshold color channel\n s3_binary = np.zeros_like(scaled_sobel)\n s3_binary[(b_channel >= lab_tres[0]) & (b_channel <= lab_tres[1])] = 1 \n\n # Threshold color channel\n s4_binary = np.zeros_like(s_channel)\n s4_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1\n\n # Stack each channel\n color_binary = np.dstack((s1_binary, s2_binary, s3_binary+s4_binary ))*255\n ret, binary = cv2.threshold(cv2.cvtColor(color_binary,cv2.COLOR_BGR2GRAY), 10, 255, cv2.THRESH_BINARY)\n\n\n return binary\n\n```\n![alt-text-1](/output_images/7binary.jpg \"title-1\")\n\n## Perspective Transformation (Bird's eye view)\nUsing openCV cv2.warpPerspective function, the region of interest is extracted.\nValues are hard coded based on calibrated images and distribution on test images.\n\n```python\ndef perspective(img):\n img_size = (img.shape[1],img.shape[0])\n src = np.float32([[715,466],[1006,654],[314,656],[575, 466]])\n dst = np.float32([[990,0],[990,720],[290,720],[290,0]])\n M = cv2.getPerspectiveTransform(src, dst)\n warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)\n return warped\n\n```\n![alt-text-1](/output_images/7warped.jpg \"title-1\")\n\n## Lane identification\nThis stage is divided in 2 cases.\n\n1st case: First frame or Lost track\n Search box is applied by taken the half bottom image and detecting histogram peaks, from the peaks the search box algorithm start all the way up, appending the points related to the line and recentering at each step.\n\n2nd case: Default\n Based on the polynomial from the last frame, it search for lane pixels around the polynomial.\n\n if it fails, 1st is run.\n\nA polynomial is fit to the points found by case 1 or 2, in case of failure it uses the polynomial from the last frame.\n\n```python\ndef find_lane_pixels(binary_warped):\n\n histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)\n out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255\n midpoint = np.int(histogram.shape[0]//2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n # HYPERPARAMETERS\n # Choose the number of sliding windows\n nwindows = 9\n # Set the width of the windows +/- margin\n margin = 100\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.int(binary_warped.shape[0]//nwindows)\n # Identify the x and y positions of all nonzero (i.e. activated) pixels in the image\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\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 for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = binary_warped.shape[0] - (window+1)*window_height\n win_y_high = binary_warped.shape[0] - window*window_height\n ### TO-DO: Find the four below boundaries of the window ###\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\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),\n (win_xright_high,win_y_high),(0,255,0), 2)\n\n ### TO-DO: Identify the nonzero pixels in x and y within the window ###\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_xright_low) & (nonzerox < win_xright_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 mean position ###\n if len(good_left_inds) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n if len(good_right_inds) > minpix:\n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n\n # Concatenate the arrays of indices (previously was a list of lists of pixels)\n try:\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n except ValueError:\n # Avoids an error if the above is not implemented fully\n pass\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\n return leftx, lefty, rightx, righty, out_img\n\n```\n\n\n```python\ndef search_around_poly(warped,left_fit, right_fit):\n # HYPERPARAMETER\n # Choose the width of the margin around the previous polynomial to search\n # The quiz grader expects 100 here, but feel free to tune on your own!\n margin = 50\n\n # Grab activated pixels\n nonzero = 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)) & (nonzerox < (left_fit[0]*(nonzeroy**2) +left_fit[1]*nonzeroy + left_fit[2] + margin)))\n\n right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy +right_fit[2] - margin)) & (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, right_fit = fit_poly(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((warped, warped, 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]] = [255, 0, 0]\n out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [255, 0, 0]\n\n return leftx, lefty, rightx, righty, out_img\n\n```\n\n```python\ndef getPoly(warped, poly_left_old, poly_right_old):\n global a\n poly_left_new=np.array([ 0., 0., 0.])\n poly_right_new=np.array([ 0., 0., 0.])\n if a == 0:\n leftx, lefty, rightx, righty, out_img = find_lane_pixels(warped)\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n poly_left_new=left_fit\n poly_right_new=right_fit\n a=1\n else:\n\n try:\n leftx, lefty, rightx, righty, out_img = search_around_poly(warped,poly_left_old, poly_right_old)\n 1/len(rightx)\n 1/len(leftx)\n except:\n leftx, lefty, rightx, righty, out_img = find_lane_pixels(warped)\n\n\n try:\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n poly_left_new[0] = poly_left_old[0]*0.8 +left_fit[0]*0.2\n poly_left_new[1] = poly_left_old[1]*0.8 +left_fit[1]*0.2\n poly_left_new[2] = poly_left_old[2]*0.8 +left_fit[2]*0.2\n poly_right_new[0] = poly_right_old[0]*0.8 +right_fit[0]*0.2\n poly_right_new[1] = poly_right_old[1]*0.8 +right_fit[1]*0.2\n poly_right_new[2] = poly_right_old[2]*0.8 +right_fit[2]*0.2\n y_lenght = np.linspace(0, warped.shape[0]-1, warped.shape[0])\n left_fitx = poly_left_new[0]*y_lenght**2 + poly_left_new[1]*y_lenght + poly_left_new[2]\n right_fitx = poly_right_new[0]*y_lenght**2 + poly_right_new[1]*y_lenght + poly_right_new[2]\n imgpoints = (y_lenght.astype(int), left_fitx.astype(int),right_fitx.astype(int))\n mask = np.zeros((warped.shape[0],warped.shape[1],3), np.uint8)\n mask[ y_lenght.astype(int) , left_fitx.astype(int)] = [255,255,0]\n mask[ y_lenght.astype(int) , right_fitx.astype(int)] = [255,255,0]\n\n except:\n poly_left_new = poly_left_old\n poly_right_new = poly_right_old\n\n return poly_left_new, poly_right_new ,out_img\n\n```\n\n![alt-text-1](/output_images/7lines.jpg \"title-1\")\n\n## Perspective Transformation\nUsing openCV cv2.warpPerspective function, the reserve transformation is applied.\n\n```python\ndef unwarped(fill_image):\n #unwarp lane area images\n src = np.float32([[715,466],[1006,654],[314,656],[575, 466]])\n dst = np.float32([[990,0],[990,720],[290,720],[290,0]])\n\n M = cv2.getPerspectiveTransform(dst, src)\n unwarped = cv2.warpPerspective(fill_image, M, (fill_image.shape[1],fill_image.shape[0]), flags=cv2.INTER_LINEAR)\n\n return unwarped\n\n```\n![alt-text-1](/output_images/7mask.jpg \"title-1\")\n\n## Radius and curvature\nUsing real life x image reference the radius and off centre values are calculated and overlayed into the mask.\n\n```python\ndef curvature(unwarped,left_fit, right_fit):\n y_lenght = np.linspace(0, unwarped.shape[0]-1, unwarped.shape[0])\n left_fitx = left_fit[0]*y_lenght**2 + left_fit[1]*y_lenght + left_fit[2]\n right_fitx = right_fit[0]*y_lenght**2 + right_fit[1]*y_lenght + right_fit[2]\n #Calculate curvature\n ym_per_pix = 14.4/720 # meters per pixel in y dimension\n xm_per_pix = 3.7/700 # meters per pixel in x dimension\n y_eval = 720\n left_fit_cr = np.polyfit(y_lenght*ym_per_pix, left_fitx*xm_per_pix, 2)\n right_fit_cr = np.polyfit(y_lenght*ym_per_pix, right_fitx*xm_per_pix, 2)\n\n left_curverad = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])\n right_curverad = ((1 + (2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])\n\n curve=(left_curverad+right_curverad)/2\n\n if curve > 20000.:\n curve_text = \"straight\"\n else:\n curve_text = str(int(right_curverad))+\" m\"\n\n out = cv2.putText(unwarped, \"Radius Curvature: \"+ curve_text , (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2, lineType=cv2.LINE_AA)\n\n #off center calculation\n off_center= ((left_fitx[-1]+right_fitx[-1])/2-unwarped.shape[1]/2)*xm_per_pix\n off_center_txt = \"Distance from center:\" + format(off_center, '.2f') + \" m \"\n out = cv2.putText(unwarped, off_center_txt, (100, 150), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2, lineType=cv2.LINE_AA)\n return unwarped\n```\n![alt-text-1](/output_images/7curve.jpg \"title-1\")\n\n## Pipeline\nThe complete process is summarized into one function to apply to the video pipeline.\n```python\ndef process_image(img):\n #Apply distortion transformation for input image\n #img = cv2.imread('test_images/straight_lines1.jpg')\n #plt.imshow(img)\n global a\n global left_fit\n global right_fit\n global poly_left\n global poly_right\n\n undist = cv2.undistort(img, mtx, dist, None, mtx)\n binary = tresholding(undist, s_thresh=(150, 255), sx_thresh=(50, 100))\n warped = perspective (binary)\n poly_left, poly_right, box = getPoly(warped, poly_left, poly_right)\n mask = lane_area_draw(warped,poly_left, poly_right)\n unwarp = unwarped(mask)\n curve = curvature(unwarp,poly_left, poly_right)\n out_img = cv2.addWeighted(undist, 1.0, curve, 0.5, 0.)\n return out_img\n\n```\n![alt-text-1](/output_images/7out_img.jpg \"title-1\")\n## Test Images Pipeline\nGenerates single image evidence for the purpose of function check.\n\n```python\ndef generate_examples(fname,idx):\n global a\n global left_fit\n global right_fit\n global poly_left\n global poly_right\n\n a=0\n poly_left = np.array([ 0., 0., 0.])\n poly_right = np.array([ 0., 0., 0.])\n left_fit = np.array([ 0., 0., 0.])\n right_fit = np.array([ 0., 0., 0.])\n img = cv2.imread(fname)\n\n undist = cv2.undistort(img, mtx, dist, None, mtx)\n binary = tresholding(undist, s_thresh=(150, 255), sx_thresh=(50, 100))\n warped = perspective (binary)\n poly_left, poly_right, box_search = getPoly(warped, poly_left, poly_right)\n\n y_lenght = np.linspace(0, warped.shape[0]-1, warped.shape[0])\n left_fitx = poly_left[0]*y_lenght**2 + poly_left[1]*y_lenght + poly_left[2]\n right_fitx = poly_right[0]*y_lenght**2 + poly_right[1]*y_lenght + poly_right[2]\n lines = np.zeros((warped.shape[0],warped.shape[1],3), np.uint8)\n lines[ y_lenght.astype(int) , left_fitx.astype(int)] = [0,255,255]\n lines[ y_lenght.astype(int) , right_fitx.astype(int)] = [0,255,255]\n lines = cv2.addWeighted(lines, 1.0, box_search, 1, 0.)\n\n mask = lane_area_draw(warped,poly_left, poly_right)\n unwarp = unwarped(cv2.addWeighted(mask, 1.0, lines, 1, 0.))\n curve = curvature(unwarp,poly_left, poly_right)\n out_img = cv2.addWeighted(undist, 1.0, curve, 0.5, 0.)\n\n cv2.imwrite('output_images/'+str(idx+1)+'test.jpg',img)\n cv2.imwrite('output_images/'+str(idx+1)+'undist.jpg',undist)\n cv2.imwrite('output_images/'+str(idx+1)+'binary.jpg',binary)\n cv2.imwrite('output_images/'+str(idx+1)+'warped.jpg',warped)\n cv2.imwrite('output_images/'+str(idx+1)+'lines.jpg',lines)\n cv2.imwrite('output_images/'+str(idx+1)+'mask.jpg',mask)\n cv2.imwrite('output_images/'+str(idx+1)+'unwarp.jpg',unwarp)\n cv2.imwrite('output_images/'+str(idx+1)+'curve.jpg',curve)\n cv2.imwrite('output_images/'+str(idx+1)+'out_img.jpg',out_img)\n\nimages = sorted(glob.glob('test_images/test*.jpg'))\nfor idx, fname in enumerate(images):\n generate_examples(fname,idx)\n\n```\n![alt-text-1](/pipeline.jpeg \"title-1\")\n## Video Pipeline\nApply complete pipeline to a video clip and outputs a processed video.\n```python\ndef processVideo(file):\n global a\n global left_fit\n global right_fit\n global poly_left\n global poly_right\n a=0\n poly_left = np.array([ 0., 0., 0.])\n poly_right = np.array([ 0., 0., 0.])\n left_fit = np.array([ 0., 0., 0.])\n right_fit = np.array([ 0., 0., 0.])\n white_output = 'process_'+file+'.mp4'\n clip1 = VideoFileClip(file)\n white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\n %time white_clip.write_videofile(white_output, audio=False)\n\nprocessVideo('project_video.mp4')\n```\n[![](http://img.youtu.be/8h3EM0Q3zeQ.jpg)](http://www.youtu.be/8h3EM0Q3zeQ \"Processed Video\")\n\nhttps://www.youtube.com/watch?v=8h3EM0Q3zeQ\n\n## Discussion\nUnder shadows the line detection became unstable, additional tuning on tresholding is required to make it more suceptible to lighting variation.\n\nSometimes when lane is not visible on use side it would be good to adjust the impact of polynomial based on the side that has more pixels available for the estimation.\nIn the project video, the left side estimation provides much more reliable detection than the right, so under a given treshold of number of line pixels on the right side, we can use the left lane to update the polynomial of the right lines.\n" } ]
8
shivani-2001/Image-Video-Captioning
https://github.com/shivani-2001/Image-Video-Captioning
c8fcc2bfd513c6b6e9e21337fef963ad7f88c1ed
60fec1e261b287fc91492c77263c972c3d3b284d
eb2ba48d4316dedbb7b69366407306ec7f621b23
refs/heads/main
2023-06-09T16:12:16.384016
2021-06-23T18:38:47
2021-06-23T18:38:47
379,695,606
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6540425419807434, "alphanum_fraction": 0.6800000071525574, "avg_line_length": 31.600000381469727, "blob_id": "ae743251710f5a59b4b011b9287cf07169c77e8b", "content_id": "99ee34e5977f913e8850750dc7111a9bb1af345f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2350, "license_type": "no_license", "max_line_length": 79, "num_lines": 70, "path": "/Image_Video captioning/img_caption.py", "repo_name": "shivani-2001/Image-Video-Captioning", "src_encoding": "UTF-8", "text": "import ast\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom tensorflow.keras.models import Model\r\nfrom tensorflow.keras.preprocessing.image import img_to_array\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\r\nfrom tensorflow.keras.applications.inception_v3 import preprocess_input\r\nfrom tensorflow.keras.layers import Input, Dropout, Dense, Embedding, LSTM, add\r\n\r\nencode_model = InceptionV3(weights='imagenet')\r\nencode_model = Model(encode_model.input, encode_model.layers[-2].output)\r\nWIDTH = 299\r\nHEIGHT = 299\r\nOUTPUT_DIM = 2048\r\n\r\nmax_length = 34\r\nwith open('wordtoidx.txt') as f:\r\n data = f.read()\r\nwordtoidx = ast.literal_eval(data)\r\n\r\nwith open('idxtoword.txt') as f:\r\n data = f.read()\r\nidxtoword = ast.literal_eval(data)\r\n\r\nvocab_size = len(idxtoword) + 1\r\nembedding_dim = 200\r\n\r\ndef generateCaption(photo):\r\n in_text = 'startseq'\r\n for i in range(max_length):\r\n sequence = [wordtoidx[w] for w in in_text.split() if w in wordtoidx]\r\n sequence = pad_sequences([sequence], maxlen=max_length)\r\n yhat = caption_model.predict([photo,sequence], verbose=0)\r\n yhat = np.argmax(yhat)\r\n word = idxtoword[yhat]\r\n in_text += ' ' + word\r\n if word == 'endseq':\r\n break\r\n final = in_text.split()\r\n final = final[1:-1]\r\n final = ' '.join(final)\r\n return final\r\n\r\ndef extract_features(img):\r\n img = img.resize((WIDTH, HEIGHT), Image.ANTIALIAS)\r\n x = img_to_array(img)\r\n x = np.expand_dims(x, axis=0)\r\n x = preprocess_input(x)\r\n x = encode_model.predict(x)\r\n x = np.reshape(x, OUTPUT_DIM)\r\n return x\r\n\r\ninputs1 = Input(shape=(OUTPUT_DIM,))\r\nfe1 = Dropout(0.5)(inputs1)\r\nfe2 = Dense(256, activation='relu')(fe1)\r\ninputs2 = Input(shape=(max_length,))\r\nse1 = Embedding(vocab_size, embedding_dim, mask_zero=True)(inputs2)\r\nse2 = Dropout(0.5)(se1)\r\nse3 = LSTM(256)(se2)\r\ndecoder1 = add([fe2, se3])\r\ndecoder2 = Dense(256, activation='relu')(decoder1)\r\noutputs = Dense(vocab_size, activation='softmax')(decoder2)\r\ncaption_model = Model(inputs=[inputs1, inputs2], outputs=outputs)\r\n\r\ncaption_model.load_weights('caption-model.hdf5')\r\nimg_file = Image.open('Sample_Image2.jpg')\r\nimg = extract_features(img_file).reshape((1,OUTPUT_DIM))\r\n\r\nprint(\"Caption:\",generateCaption(img))" }, { "alpha_fraction": 0.8064516186714172, "alphanum_fraction": 0.8225806355476379, "avg_line_length": 30, "blob_id": "768850a1e6a1c224597bebc59d4081d181080b32", "content_id": "86c9b76c5d1124b3d3c653dd05608619b2106cd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 62, "license_type": "no_license", "max_line_length": 36, "num_lines": 2, "path": "/README.md", "repo_name": "shivani-2001/Image-Video-Captioning", "src_encoding": "UTF-8", "text": "# Image-Video-Captioning\nImage Captioning on flick-8k dataset\n" }, { "alpha_fraction": 0.6196428537368774, "alphanum_fraction": 0.6497023701667786, "avg_line_length": 30.019046783447266, "blob_id": "acaf05d77ab92c641d3a5be6312bdedeed5028e1", "content_id": "2c90389fcaa3c1506c3df0d32a7a1259af10b651", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3360, "license_type": "no_license", "max_line_length": 100, "num_lines": 105, "path": "/Image_Video captioning/video_caption.py", "repo_name": "shivani-2001/Image-Video-Captioning", "src_encoding": "UTF-8", "text": "import cv2\r\nimport numpy as np\r\nimport ast\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom tensorflow.keras.models import Model\r\nfrom tensorflow.keras.preprocessing.image import img_to_array\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\r\nfrom tensorflow.keras.applications.inception_v3 import preprocess_input\r\nfrom tensorflow.keras.layers import Input, Dropout, Dense, Embedding, LSTM, add\r\n\r\nencode_model = InceptionV3(weights='imagenet')\r\nencode_model = Model(encode_model.input, encode_model.layers[-2].output)\r\nWIDTH = 299\r\nHEIGHT = 299\r\nOUTPUT_DIM = 2048\r\n\r\nmax_length = 34\r\nwith open('wordtoidx.txt') as f:\r\n data = f.read()\r\nwordtoidx = ast.literal_eval(data)\r\n\r\nwith open('idxtoword.txt') as f:\r\n data = f.read()\r\nidxtoword = ast.literal_eval(data)\r\n\r\nvocab_size = len(idxtoword) + 1\r\nembedding_dim = 200\r\n\r\ndef generateCaption(photo):\r\n in_text = 'startseq'\r\n for i in range(max_length):\r\n sequence = [wordtoidx[w] for w in in_text.split() if w in wordtoidx]\r\n sequence = pad_sequences([sequence], maxlen=max_length)\r\n yhat = caption_model.predict([photo,sequence], verbose=0)\r\n yhat = np.argmax(yhat)\r\n word = idxtoword[yhat]\r\n in_text += ' ' + word\r\n if word == 'endseq':\r\n break\r\n final = in_text.split()\r\n final = final[1:-1]\r\n final = ' '.join(final)\r\n return final\r\n\r\ndef extract_features(img):\r\n img = img.resize((WIDTH, HEIGHT), Image.ANTIALIAS)\r\n x = img_to_array(img)\r\n x = np.expand_dims(x, axis=0)\r\n x = preprocess_input(x)\r\n x = encode_model.predict(x)\r\n x = np.reshape(x, OUTPUT_DIM)\r\n return x\r\n\r\ninputs1 = Input(shape=(OUTPUT_DIM,))\r\nfe1 = Dropout(0.5)(inputs1)\r\nfe2 = Dense(256, activation='relu')(fe1)\r\ninputs2 = Input(shape=(max_length,))\r\nse1 = Embedding(vocab_size, embedding_dim, mask_zero=True)(inputs2)\r\nse2 = Dropout(0.5)(se1)\r\nse3 = LSTM(256)(se2)\r\ndecoder1 = add([fe2, se3])\r\ndecoder2 = Dense(256, activation='relu')(decoder1)\r\noutputs = Dense(vocab_size, activation='softmax')(decoder2)\r\ncaption_model = Model(inputs=[inputs1, inputs2], outputs=outputs)\r\n\r\ncaption_model.load_weights('caption-model.hdf5')\r\n\r\nvideo = cv2.VideoCapture('1.mp4')\r\nwidth1 = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))\r\nheight1 = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\nthreshold = 100.\r\n\r\nwriter = cv2.VideoWriter('Output_video.mp4', cv2.VideoWriter_fourcc(*'DIVX'), 25, (width1, height1))\r\nret, frame1 = video.read()\r\ncurrent_frame = frame1\r\ncaption = ''\r\n\r\nwhile True:\r\n ret, frame = video.read()\r\n if ret is True:\r\n if (((np.sum(np.absolute(frame-current_frame))/np.size(frame)) > threshold)):\r\n img_file = Image.fromarray(frame)\r\n img = extract_features(img_file).reshape((1,OUTPUT_DIM))\r\n caption = generateCaption(img)\r\n print(\"Caption:\", caption)\r\n current_frame = frame\r\n else:\r\n current_frame = frame\r\n\r\n font = cv2.FONT_HERSHEY_DUPLEX\r\n cv2.putText(frame, caption, (10,350), font, 0.5, (255,0,0), 1, cv2.LINE_AA)\r\n cv2.imshow('frame', frame)\r\n writer.write(frame)\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n if ret is False:\r\n break\r\n\r\nvideo.release()\r\nwriter.release()\r\ncv2.destroyAllWindows()" } ]
3
nagcme/Text-Classification
https://github.com/nagcme/Text-Classification
d67def895f2a601c1c97d4536b66cf9dabceda84
dfa7460bc460be1f71fb68496d9022e9da477a5c
9bc7d35941a9c461471ea845a4a60b4014bb656f
refs/heads/main
2023-07-13T15:10:36.089237
2021-08-19T10:44:08
2021-08-19T10:44:08
397,905,760
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.672583818435669, "alphanum_fraction": 0.680341899394989, "avg_line_length": 38.02631759643555, "blob_id": "ca206063b7abe580d36537e360642ed3860107ad", "content_id": "12b7125ada0d86a6c5f76fe51db8262105388659", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7605, "license_type": "no_license", "max_line_length": 80, "num_lines": 190, "path": "/text_mining.py", "repo_name": "nagcme/Text-Classification", "src_encoding": "UTF-8", "text": "'''\r\nReferences: https://pythonspot.com/nltk-stop-words/\r\n https://docs.python.org/3/library/re.html\r\n https://scikit-learn.org/stable/modules/generated/\r\n sklearn.naive_bayes.MultinomialNB.html\r\n https://scikit-learn.org/stable/modules/generated/\r\n sklearn.feature_extraction.text.CountVectorizer.html\r\n https://scikit-learn.org/stable/modules/generated/s\r\n klearn.feature_extraction.text.TfidfTransformer.html\r\nAssumptions:\r\n 1. The following file is present in the same directory as the\r\n python file:\r\n Corona_NLP_train.csv\r\n 2. An 'outputs' folder will already be created in the current\r\n directory where the code and the data files are kept\r\n'''\r\n\r\n# Import statements\r\nimport nltk\r\nimport pandas as pd\r\nimport re\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom datetime import datetime\r\nimport numpy as np\r\n\r\n# Print the start time of the code execution\r\nprint(datetime.now())\r\n\r\n# Read the Corona_NLP_train dataset in python dataframe\r\ncorona_df = pd.read_csv('Corona_NLP_train.csv', encoding = 'iso-8859-1')\r\n\r\n# Question 1\r\nprint('Question 1...')\r\n# List the possible sentiments that a tweet may have\r\nprint('List of all possible sentiments in the file: '\r\n +str(corona_df.Sentiment.unique()))\r\n\r\n# Fetch the second most popular sentiment in the tweets\r\nsentiment_freq = corona_df.Sentiment.value_counts()\r\nsecond_pop = dict(sentiment_freq[1:2])\r\nprint('Second most popular sentiment: '+str(second_pop))\r\n\r\n# Fetch the date with the greatest number of extremely positive tweets\r\nex_positive_tweet = corona_df[corona_df['Sentiment'] ==\r\n 'Extremely Positive'].TweetAt.value_counts()\r\nex_positive_tweet = dict(ex_positive_tweet[0:1])\r\nprint('Date with the greatest no. of extremely positive tweets: '\r\n +str(ex_positive_tweet))\r\n\r\n# Text pre processing\r\n\r\n# Convert the messages to lower case\r\ncorona_df[\"OriginalTweet\"] = corona_df[\"OriginalTweet\"].str.lower()\r\n\r\n# replace non-alphabetical characters with whitespaces\r\ncorona_df[\"OriginalTweet_Cleaned\"] = [re.sub(\"[^a-z]+\", \" \", str(x))\r\n for x in corona_df[\"OriginalTweet\"]]\r\n# check the words of a message are separated by a single whitespace\r\n# corona_df[\"OriginalTweet_Cleaned\"].replace(to_replace =\" \", value =\" \")\r\ncorona_df[\"OriginalTweet_Cleaned\"] = [re.sub(' +', ' ', str(x))\r\n for x in corona_df[\"OriginalTweet_Cleaned\"]]\r\n\r\n# Question 2\r\nprint('Question 2...')\r\nprint(datetime.now())\r\n# Tokenise the tweets in the Dataframe using split()\r\ncorona_df[\"Tweet_tokenised\"] = corona_df[\"OriginalTweet_Cleaned\"].str.split()\r\n\r\n# Count the total number of all words (including repetitions)\r\n# First map the length of each tweet document and then sum the total\r\nprint('Total number of all words: '+str(sum(map(len,\r\n corona_df[\"Tweet_tokenised\"]))))\r\n\r\n# Count the total number of distinct words\r\nresults = set()\r\ncorona_df[\"Tweet_tokenised\"].apply(results.update)\r\nprint('Total number of distinct words: '+str(len(results)))\r\n\r\n# Calculate the word frequency\r\nword_freq = pd.DataFrame(\r\n corona_df[\"Tweet_tokenised\"].to_list()).stack().value_counts()\r\n\r\n# Print the 10 most frequent words in the corpus\r\nprint('The 10 most frequent words in the corpus:')\r\nprint(word_freq.head(10))\r\n\r\n# Stopwords Removal\r\n\r\n# Fetch the list of stopwords from NLTK\r\nstopwords_nltk = nltk.corpus.stopwords.words('english')\r\n\r\n# Remove all stopwords and words having length less than or equal to 2 character\r\ncorona_df[\"Tweet_WO_SW\"] = corona_df[\"Tweet_tokenised\"].apply(lambda x:\r\n [item for item in x if item not in stopwords_nltk\r\n and len(item) > 2])\r\n\r\n# Count the total number of all words (including repetitions)\r\n# First map the length of each tweet document and then sum the total\r\nprint('Total number of all words: '+str(sum(map(len,\r\n corona_df[\"Tweet_WO_SW\"]))))\r\n\r\n# Count the total number of distinct words\r\ncorona_df['Tweet_WO_SW_Uniq'] = corona_df['Tweet_WO_SW'].apply(set)\r\nresults = set()\r\ncorona_df[\"Tweet_WO_SW\"].apply(results.update)\r\nprint('Total number of distinct words: '+str(len(results)))\r\n\r\n# Print the 10 most frequent words in the corpus\r\nword_freq = pd.DataFrame(\r\n corona_df[\"Tweet_WO_SW\"].to_list()).stack().value_counts()\r\nprint('The 10 most frequent words in the corpus:')\r\nprint(word_freq.head(10))\r\n\r\n# Question 3\r\nprint('Question 3...')\r\nprint(datetime.now())\r\n# Plot a line chart with word frequencies, where the horizontal axis corresponds\r\n# to words, while the vertical axis indicates the fraction of documents in a\r\n# which a word appears.\r\n# The words should be sorted in increasing order of their frequencies\r\n\r\n# Remove duplicate words from each row\r\ncorona_df['Tweet_WO_SW_Uniq'] = corona_df['Tweet_WO_SW'].apply(set)\r\n\r\n# Fetch the frequency of occurrence of each word in a tweet\r\nword_freq = pd.DataFrame(\r\n corona_df[\"Tweet_WO_SW_Uniq\"].to_list()).stack().value_counts()\r\n\r\n## Plot all the words having the below axes details:\r\n# x-axis: word index\r\n# y-axis: fraction of documents where the word is present\r\nword_docs = (word_freq.sort_values())/len(corona_df)\r\nword_docs = word_docs.reset_index()\r\nword_docs.plot(legend=False)\r\nplt.title('Word Frequencies')\r\nplt.xlabel('Words')\r\nplt.ylabel('Fraction of documents')\r\nprint('Saving the document frequency graph in the \"outputs\" folder...')\r\nplt.savefig('outputs/word_freq_all.png')\r\n\r\n# Commented the below code, this was for analysis part\r\n# DId not remove the code, as the output graph is there in the report\r\n# Start of comment\r\n# # Plot only the top 20 words (sorted in increasing order of their frequencies)\r\n# # This plot is used to get a better insight of the corpus\r\n# word_docs_50 = word_freq.sort_values().tail(50)\r\n# # Calculate the fraction of document where the word exists\r\n# word_docs_50_frac = word_docs_50/len(corona_df)\r\n#\r\n# # Plot the graph\r\n# word_docs_50_frac.plot(figsize=(12,14))\r\n# tick_labels = tuple(word_docs_50_frac.index)\r\n# plt.xticks(range(0, 50), tick_labels, rotation=90)\r\n# plt.xlabel('Words')\r\n# plt.ylabel('Fraction of documents')\r\n# Save the graph\r\n# plt.savefig('outputs/word_freq.png')\r\n# End of comment\r\n\r\n# Question 4\r\nprint('Question 4...')\r\nprint(datetime.now())\r\n# Produce a Multinomial Naive Bayes classifier for the\r\n# Coronavirus Tweets NLP data set using scikit-learn.\r\n\r\n# Get an instance of the Count Vectorizer\r\n# Count Vectorizer converts a collection of text documents\r\n# to a matrix of token counts\r\nvectorizer = CountVectorizer()\r\n\r\n# Store the corpus in a numpy array\r\ncorpus_np = corona_df['OriginalTweet_Cleaned'].to_numpy()\r\n# Fit and transform the corpus using vectorizer\r\n# This returns a sparse matrix\r\ntweets = vectorizer.fit_transform(corpus_np)\r\n\r\n# Fitting the Multinominal Naive Bayes Theorem for the corpus\r\nclf = MultinomialNB()\r\nclf.fit(tweets, np.array(corona_df['Sentiment']))\r\n\r\n# Calculate and print the Error Rate\r\n# The data has not been split into training and test set\r\n# Hence the entire data is used to calculate the error rate\r\nprint('Error Rate: '+str(1 - round(clf.score(tweets,np.array(corona_df[\r\n 'Sentiment'])),2)))\r\n\r\n# Print the End time of code execution\r\nprint(datetime.now())\r\n" }, { "alpha_fraction": 0.6238338947296143, "alphanum_fraction": 0.6322600245475769, "avg_line_length": 54.38333511352539, "blob_id": "45027fe5ac3c2e08d31e11d57315812719b03937", "content_id": "acc6ffaf250c9f581e32be2953848eddab8dba45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3323, "license_type": "no_license", "max_line_length": 105, "num_lines": 60, "path": "/README.md", "repo_name": "nagcme/Text-Classification", "src_encoding": "UTF-8", "text": "# Text-Classification\nSentiment Analysis using Python\nVersions:\npython '3.8.5'\npandas '1.1.4'\nsklearn '0.24.1'\nmatplotlib '3.3.2'\nnumpy '1.19.3'\nskimage '0.18.1'\n\nFiles: The below files (python and data) should be placed in the same folder:\n\ttext_mining.py\n\tCorona_NLP_train.csv\n \n \n *******************************************************************************************************\n*******************************************TEXT MINING*************************************************\n*******************************************************************************************************\n\nFiles:\ntext_mining.py\nCorona_NLP_train.csv\n\nCode Structure:\nThe Corona_NLP_train.csv file has been read into pandas dataframe for text mining.\n1. a) All the possible sentiments have been fetched from the Sentiment column of the dataframe\n b) The frequency of each of the sentiments has been computed and the second most popular sentiment\nhas been returned.\n c) The date that received the maximum no. of 'Extremely Positive' tweets has been fetched by \ncounting the rows with 'Extremely Positive' tweets by grouping the 'TweetAt' column. The first item\nhas been returned.\n d) Text Preprocessing: Data in the 'OriginalTweet' column is first converted to lower case\n\t\t\t All non-alphabetical characters has been replaced with space\n\t\t\t A check is performed to determine two words are separated only by a single \n\t\t\t space.\n2. a) A new column is generated in the existing dataframe that consists of the tokenised tweets. The\ntokenisation of tweets is achieved by using split() of python.\n b) First map the length of each tokenised tweet document and then sum the total to get the total\nno. of words in the corpus \n c) To fetch the total no. of distinct words, a set() is applied on the dataframe column to remove\nthe duplicate words. Then the length of the set is calculated to generate the total no. of distinct\nwords in the corpus.\n d) The word frequency of the corpus is calculated by using the functions to_list(), stack() and \nvalue_counts() and then the top 10 frequent words are displayed.\n e) The stopwords from nltk are fetched. All the words that belongs to the stopwords set and any word\nthat has length less than or equal to 2chars are removed to clean the corpus and the above steps are \nagain performed.\n3. Duplicate words from each document is first removed to generate the graph showing the fraction of\ndocuments in which a word appears. Then the word frequency is generated and the line chart is plotted \nwhere Y axis shows the fraction of documents and X axis shows the word index. \n4. a) The preprocessed cleaned tweets are saved in a numpy array\n b) Use CountVectoriser to fit and transform the corpus into a sparse matrix of terms\n c) MultinomialNB() function from sklearn is used to create the classifier\n d) The sparse matrix computed using CountVectoriser is passed into the classifier along with the \nSentiment column\n e) Calculate the Error Rate of the classifier\n\n*******************************************************************************************************\n***********************************************END*****************************************************\n*******************************************************************************************************\n" } ]
2
sanjeevbhatia3/PythonCodeYoutube
https://github.com/sanjeevbhatia3/PythonCodeYoutube
42e8811848a31896328c84561873f925d1653376
bf3e771078b18d0cd552a71e65f5c9f63961c815
308710d20b26f6e08d1740ebeb7e9a322412c39d
refs/heads/master
2023-06-25T07:15:05.426182
2021-07-23T16:15:46
2021-07-23T16:16:33
388,835,592
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5285024046897888, "alphanum_fraction": 0.5700483322143555, "avg_line_length": 18.185184478759766, "blob_id": "36aafe8aee870e403892e62cc94b0c8c586aa15a", "content_id": "0df8b8d66bb152cc9221a9ee52f5d67166eb2f9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1035, "license_type": "no_license", "max_line_length": 54, "num_lines": 54, "path": "/builtInOperators.py", "repo_name": "sanjeevbhatia3/PythonCodeYoutube", "src_encoding": "UTF-8", "text": "# range\n# start, stop, step\n# for num in range(3,11,3):\n# print(num)\n#\n# num_list = list(range(1,51))\n# print(num_list)\n\n# enumerate\n# name = 'mickey'\n# for index, value in enumerate(name):\n# print(f'{value} is at index {index}')\n\n# zip\n# num = [1,2,3,4,5,6]\n# character = ['a','b','c','d']\n# name = ['john', 'jake', 'mike']\n#\n# for item in zip(num, character, name):\n# print(item)\n\n# in\n# num = [1,2,3,4,5]\n# print(12 in num)\n\n# name = {'first_name': 'john', 'last_name': 'oliver'}\n# print('mike' in name.values())\n\n# min, max\n# num = [1,3,6,2,8,5,6]\n# print(max(num))\n\n# from random import randint\n# i = 1\n# while i <= 5:\n# random_num = randint(1,10)\n# print(random_num)\n# i += 1\n\n# from random import choice\n# names = ['john', 'mike', 'jake', 'sanj']\n# for num in range(5):\n# print(choice(names))\n\n# input\n# name = input(\"Enter your name:\")\n# print(\"hello \" + name)\n#\n# age = int(input(\"Enter your age:\"))\n# print(f'you are {age} years old.')\n\n# sorted\nmy_list = [12,3,4,6,2,9,3,6]\nprint(sorted(my_list))" }, { "alpha_fraction": 0.551581859588623, "alphanum_fraction": 0.5722146034240723, "avg_line_length": 20.397058486938477, "blob_id": "0eaf489249aaf2201c183e4fc66b54a9913227d7", "content_id": "9bfd19e616ed419c92733b1a6743a3c9a430b78e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1454, "license_type": "no_license", "max_line_length": 94, "num_lines": 68, "path": "/functions.py", "repo_name": "sanjeevbhatia3/PythonCodeYoutube", "src_encoding": "UTF-8", "text": "# def say_hello(name=\"John\"):\n# print(\"Hello \" + name)\n#\n# say_hello(\"Jake\")\n\n# def add_num(a=2, b=5):\n# return a + b\n#\n# num_sum = add_num()\n# print(num_sum)\n\n# def even_odd(num):\n# if num % 2 == 0:\n# print(\"Given number is even\")\n# else:\n# print(\"Given number is odd\")\n#\n# even_odd(8)\n\n\n# inventory = [('macbook', 5), ('tablet', 20), ('chromebook', 7), ('iPad', 4), ('iPhone', 10)]\n# def inventory_check(inventory):\n# max_inventory_item = \"\"\n# current_inventory = 0\n# for item, num in inventory:\n# if num > current_inventory:\n# current_inventory = num\n# max_inventory_item = item\n# return max_inventory_item, current_inventory\n#\n# result = inventory_check((inventory))\n# print(result)\n\n# def full_name(first_name, last_name):\n# return first_name + \" \" + last_name\n#\n# name = full_name(\"John\", \"Oliver\")\n#\n# def person_info(given_name=name):\n# age = 53\n# print(f'{given_name} is {age} years old.')\n#\n# person_info('Mike')\n\n# *args and **kwargs\n# def num_sum(*args):\n# print(sum(args))\n#\n# num_sum(1,2,3,4,5,3,4,5,5,6,6,6)\n\ndef fav_color(**kwargs):\n if 'color' in kwargs:\n print('My favorite color is {}.'.format(kwargs['color']))\n else:\n print('I did not find any color')\n\nfav_color(rose='red', juice='orange', color='brown')\n\n\ntotal = 0\ndef number():\n global total\n total = 2\n total += 1\n print(total)\n\nnumber()\nprint(total)" }, { "alpha_fraction": 0.5878199338912964, "alphanum_fraction": 0.5984113216400146, "avg_line_length": 21.639999389648438, "blob_id": "d111d4d4d068696f43a1040aad1836c3863d6e69", "content_id": "9850db235dc2a0709709b3dd19f451134b5e58b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1133, "license_type": "no_license", "max_line_length": 78, "num_lines": 50, "path": "/objectOrientedProgramming.py", "repo_name": "sanjeevbhatia3/PythonCodeYoutube", "src_encoding": "UTF-8", "text": "# class car_package:\n# color = 'blue'\n#\n# def __init__(self, make, model):\n# self.make = make\n# self.model = model\n#\n# def car_description(self, battery):\n# print(f'I love my {self.make} and its color is {car_package.color}')\n# print(f'Car has a battery of {battery}')\n#\n#\n# my_car1 = car_package(make=\"Tesla\", model=\"Model-X\")\n# # print(my_car1.make)\n# my_car2 = car_package(\"Tesla\", \"Model 3\")\n# # print(my_car2.model)\n# # print(my_car1.color)\n# # print(my_car2.color)\n# my_car1.car_description(\"75kWh\")\n\n\n# Inheritance\nclass Car:\n def __init__(self):\n print(f'Car class created')\n\n def music_system(self):\n print(f'Car has BOSS music system')\n\n def tire_brand(self):\n print(f'Car comes with Bridgestone tires')\n\n\nclass Tesla(Car):\n def __init__(self):\n Car.__init__(self)\n print(f'Tesla class created')\n\n def color(self):\n print(f'car color is blue')\n\n def music_system(self):\n print(f'Car has Harman-Kardon music system')\n\n\nmy_car = Tesla()\nmy_car.color()\nmy_car.music_system()\nmy_car1 = Car()\nmy_car1.music_system()\n\n" }, { "alpha_fraction": 0.5873213410377502, "alphanum_fraction": 0.6239900588989258, "avg_line_length": 22.647058486938477, "blob_id": "ca93ceea97caa4123414885a87ec455c13063065", "content_id": "3421c4160c71bd55b96fe4f252cb90c09b273c05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1609, "license_type": "no_license", "max_line_length": 59, "num_lines": 68, "path": "/regex.py", "repo_name": "sanjeevbhatia3/PythonCodeYoutube", "src_encoding": "UTF-8", "text": "import re\n\n# text = \"you can call me at 123-234-4567\"\n# pattern = re.compile(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d')\n# result = re.search(pattern, text)\n# print(result)\n# print(result.span())\n# print(result.start())\n# print(result.group())\n\n# text = \"you can call me at 123-234-4567 or 333-333-3333\"\n# pattern = re.compile(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d')\n# # result = re.findall(pattern, text)\n# # print(result)\n#\n# for item in re.finditer(pattern, text):\n# print(item)\n# print(item.start())\n\n# Character identifier\n# \\d -> digit, \\w -> alphanumeric D_og-1 \\w\\w\\w\\w-\\w\n# \\s -> space\n# \\D -> non-digit XYZ \\D\\D\\D\n# \\W -> non-alphanumeric *+-)=\n\n\n# Quantifier\n# + (Occurs one or more time)\n# * (Occurs zero or more time)\n# ? (once or more)\n# {3} exactly 3 times\n\n# text = \"you can call me at 123-234-4567\"\n# pattern = re.compile(r'(\\d{3})-(\\d{3})-(\\d{4})')\n# result = re.search(pattern, text)\n# print(result)\n# print(result.span())\n# print(result.group(1))\n\n# or (|) operator\n# text = \"I have Tesla car\"\n# pattern = re.compile(r'Tesla | Honda')\n# result = re.search(pattern, text)\n# print(result)\n\n# . (dot) operator\n# text = \"It is best to take rest during fest\"\n# pattern = re.compile(r'.est')\n# result = re.findall(pattern, text)\n# print(result)\n\n# ^ starts with\n# text = 'date 1/1/2021'\n# result = re.findall(\"^\\d\", text)\n# print(result)\n\n# $ ends with\n# text = '1/1/2021 date'\n# result = re.findall(\"\\d$\", text)\n# print(result)\n\n\n# [] to exclude data\ntext = \"This is sanjeev! the founder of interviewbox.tech?\"\npattern = re.compile(r'[^!?]+')\nresult = re.findall(pattern, text)\nprint(result)\nprint(\"\".join(result))\n\n" }, { "alpha_fraction": 0.6120689511299133, "alphanum_fraction": 0.6293103694915771, "avg_line_length": 18.41666603088379, "blob_id": "ac69728a10d002e8cfb082aad200f459618abd02", "content_id": "b02b47416e71b82e888b76ff58666682df3cba07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 43, "num_lines": 12, "path": "/misc.py", "repo_name": "sanjeevbhatia3/PythonCodeYoutube", "src_encoding": "UTF-8", "text": "def function1(function):\n def wrapper():\n print(\"hello\")\n function()\n print(\"Welcome to python tutorial\")\n return wrapper\n\ndef function2():\n print(\"pythonista\")\n\nmy_func = function1(function2)\nmy_func()" }, { "alpha_fraction": 0.5786163806915283, "alphanum_fraction": 0.5849056839942932, "avg_line_length": 23.538461685180664, "blob_id": "8582141226119eed300fefc31412b6754acd224a", "content_id": "c5a31b2bb6606d9f07a063af32c4817f3101d808", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 318, "license_type": "no_license", "max_line_length": 66, "num_lines": 13, "path": "/errorHandling.py", "repo_name": "sanjeevbhatia3/PythonCodeYoutube", "src_encoding": "UTF-8", "text": "def divide_num(a, b):\n try:\n output = a / b\n except (ZeroDivisionError, TypeError) as err:\n print(f\"Some error occurs!\")\n print(err)\n else:\n print(f'Division output of {a} divide by {b} is {output}')\n finally:\n print(f'divide_num function is executed!')\n\n\ndivide_num(3,0)" } ]
6
HEP-FCC/HoughTransform
https://github.com/HEP-FCC/HoughTransform
78e6fc833aa9098b2226a7f00c9dcf47d0db2065
81e889f7f0bab96111dda7748b6877d6054cb0a5
3d679a4f032d71988c8ed59bff2660733e634c13
refs/heads/master
2020-05-07T14:16:50.357512
2019-04-09T17:53:38
2019-04-09T17:53:38
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6624390482902527, "alphanum_fraction": 0.6624390482902527, "avg_line_length": 24.625, "blob_id": "7e74f2c58f594d367248e0a73a1eef78593be915", "content_id": "f3ad5fc983c751ed588e930dba999954c22b0966", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1025, "license_type": "permissive", "max_line_length": 98, "num_lines": 40, "path": "/rootTree2CSV.py", "repo_name": "HEP-FCC/HoughTransform", "src_encoding": "UTF-8", "text": "from ROOT import gSystem\nfrom ROOT import *\nimport csv\nimport argparse\nimport os\nimport sys\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--input', type=str, default=None, help='specify an input file (ROOT ntuple)')\nparser.add_argument('--output', type=str, default=None, help='specify an output file (csv file)')\n\nmy_args, _ = parser.parse_known_args()\n\nfilename = \"\"\nfilename_csv = \"out.csv\"\n\nif (my_args.input != None and os.path.isfile(my_args.input)):\n filename = my_args.input\nelse:\n print(\"Incorrect input file!! Exit the program!\")\n sys.exit()\n\nif (my_args.output != None):\n filename_csv = my_args.output\n\nfile = TFile(filename)\ntree=file.Get(\"analysis\")\n\nwith open(filename_csv, 'w') as csvfile:\n csv_writer=csv.writer(csvfile, delimiter=',')\n csv_writer.writerow([\"trackNum\", \"MCx\", \"MCy\" , \"MCz\"])\n\n for entry in tree:\n trackNum = tree.trackNum\n MCx = tree.MC_x\n MCy = tree.MC_y\n MCz = tree.MC_z\n\n csv_writer.writerow([trackNum, MCx, MCy, MCz])\n" }, { "alpha_fraction": 0.539733350276947, "alphanum_fraction": 0.5453333258628845, "avg_line_length": 26.985074996948242, "blob_id": "7fd1d5403d5e9ce46621c0780721ccdbdeb63f59", "content_id": "6e262b68084437135304037f1e2d40e40269ac5d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3750, "license_type": "permissive", "max_line_length": 95, "num_lines": 134, "path": "/Hits.py", "repo_name": "HEP-FCC/HoughTransform", "src_encoding": "UTF-8", "text": "import os\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nmatplotlib.get_configdir()\nplt.style.use('seaborn-poster')\nfrom mpl_toolkits.mplot3d import Axes3D\n\nFONTSIZE = 40\n# Looking into all the hits\nclass Hits:\n def __init__(self, filename):\n\n self._filename = filename\n self._data = self.read_csv_file()\n self._MCx = self._data[\"MCx\"]\n self._MCy = self._data[\"MCy\"]\n self._MCz = self._data[\"MCz\"]\n\n\n def read_csv_file(self):\n return pd.read_csv(self._filename)\n\n\n def returnEvent(self, event=0):\n if 'trackNum' in self._data:\n return self._data.loc[self._data['trackNum'] == event]\n else:\n return self._data\n\n\n def drawAllEvents(self):\n figHits = plt.figure()\n ax = Axes3D(figHits)\n ax.scatter(self._MCx, self._MCz, self._MCy, c = 'blue', marker = 'o', label=\"MC Truth\")\n plt.legend(loc='upper left')\n ax.set_xlabel(\"x\", fontsize=FONTSIZE)\n ax.set_ylabel(\"z\", fontsize=FONTSIZE)\n ax.set_ylabel(\"y\", fontsize=FONTSIZE)\n plt.tight_layout()\n ax.xaxis.labelpad = 20\n ax.yaxis.labelpad = 20\n ax.zaxis.labelpad = 20\n plt.show()\n\n\n# Looking into each event\nclass Event:\n def __init__(self, hits, event=0):\n self._hits = hits\n self._data = hits.returnEvent(event)\n self.update()\n # self._MCx = self._data[\"MCx\"]\n # self._MCy = self._data[\"MCy\"]\n # self._MCz = self._data[\"MCz\"]\n self._event = event\n\n\n @property\n def data(self):\n return self._MCx, self._MCy, self._MCz\n\n @property\n def data_df(self):\n return self._data\n\n @data.setter\n def data(self, event):\n self._event = event\n self._data = self._hits.returnEvent(event)\n self.update()\n # self._MCx = self._data[\"MCx\"]\n # self._MCy = self._data[\"MCy\"]\n # self._MCz = self._data[\"MCz\"]\n\n\n def drawEvent3D(self, plotName=\"\"):\n figHits = plt.figure()\n ax = Axes3D(figHits)\n ax.scatter(self._MCx, self._MCz, self._MCy, c = 'blue', marker = 'o', label=\"MC Truth\")\n plt.legend(loc='upper left')\n ax.set_xlabel(\"x [mm]\")\n ax.set_ylabel(\"z [mm]\")\n ax.set_ylabel(\"y [mm]\")\n plt.tight_layout()\n ax.xaxis.labelpad = 20\n ax.yaxis.labelpad = 20\n ax.zaxis.labelpad = 20\n\n if plotName:\n plt.savefig(plotName)\n else:\n plt.show()\n\n def drawEventXY(self, plotName=\"\"):\n fig_xy = plt.figure()\n plt.scatter(self._MCx, self._MCy, c = 'red', marker = '+', label=\"MC Truth\")\n plt.legend(loc='upper left')\n plt.xlabel('x [mm]')\n plt.ylabel('y [mm]')\n plt.tight_layout()\n\n if plotName:\n plt.savefig(plotName)\n else:\n plt.show()\n\n def drawEventXZ(self):\n fig_xz = plt.figure()\n plt.scatter(self._MCx, self._MCz, c = 'red', marker = '+', label=\"MC Truth\")\n plt.legend(loc='upper left')\n plt.xlabel('x [mm]')\n plt.ylabel('z [mm]')\n plt.tight_layout()\n plt.show()\n\n def drawEventYZ(self):\n fig_xz = plt.figure()\n plt.scatter(self._MCy, self._MCz, c = 'red', marker = '+', label=\"MC Truth\")\n plt.legend(loc='upper left')\n plt.xlabel('y [mm]')\n plt.ylabel('z [mm]')\n plt.tight_layout()\n plt.show()\n\n def update(self):\n self._MCx = self._data[\"MCx\"]\n self._MCy = self._data[\"MCy\"]\n self._MCz = self._data[\"MCz\"]\n\n def combineEvents(self, events):\n self._data = pd.concat([self._data]+[e.data_df for e in events], ignore_index=True)\n self.update()\n" }, { "alpha_fraction": 0.6775884628295898, "alphanum_fraction": 0.6893839836120605, "avg_line_length": 26.25, "blob_id": "624203758a6e390f9243fb043505862e4d2c7895", "content_id": "b51dbe7137ed49a8e166ea7d28d3f5038c0e6489", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1526, "license_type": "permissive", "max_line_length": 103, "num_lines": 56, "path": "/main.py", "repo_name": "HEP-FCC/HoughTransform", "src_encoding": "UTF-8", "text": "import Hits\nimport Transforms\nimport numpy as np\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport argparse\nimport os\nimport sys\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--input', type=str, default=None, help='specify an input file')\nparser.add_argument('--background', type=str, default=None, help='specify an input file as background')\nparser.add_argument('--output', type=str, default=None, help='specify an output path')\nmy_args, _ = parser.parse_known_args()\n\n\nfilename = \"\"\nplotpath = \"./\"\n\nif (my_args.input != None and os.path.isfile(my_args.input)):\n filename = my_args.input\nelse:\n print(\"Incorrect input file!! Exit the program!\")\n sys.exit()\n\n\nif my_args.output != None:\n plotpath = my_args.output + \"/\"\n\n# DATA_PATH = \"./data/pythia/\"\n# filename = \"reco_simu_Zdd.csv\"\n#\n# BCG_PATH = './data/'\n# Filename_background = \"reco_0.csv\"\n\n\nh = Hits.Hits(filename)\nev = Hits.Event(h) #, 11)\n\n# h.drawAllEvents()\n# Combine events (background, or several events)\n# ev.combineEvents([Hits.Event(h_background)])\n# ev.combineEvents([Hits.Event(h, 12), Hits.Event(h, 11)])\n\n\nev.drawEvent3D(plotName=plotpath+\"3D_Zdd.pdf\")\n# ev.drawEventXY()#plotName=plotpath+\"3tracks_XY.pdf\")\n# ev.drawEventXZ()\n# ev.drawEventYZ()\nd = ev.data\ntr = Transforms.Transforms(ev)\n\nH, xedges, yedges = tr.HoughTransform_phi(numpoints=200, binx=200,\n biny = 50, plotName = plotpath+\"HT_Zdd_maxima.pdf\")\ntr.plotConformalTransform(plotpath+\"CT_Zdd.pdf\")\n" }, { "alpha_fraction": 0.519013524055481, "alphanum_fraction": 0.5326969027519226, "avg_line_length": 35.3294792175293, "blob_id": "fb1a7d82952f882bbf05dc89689ef30da1ef5b6f", "content_id": "936cd2a4f62bbc8c10856d8cca34c9a1a316a02a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6285, "license_type": "permissive", "max_line_length": 131, "num_lines": 173, "path": "/Transforms.py", "repo_name": "HEP-FCC/HoughTransform", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom numpy import unravel_index\nfrom sklearn.cluster import DBSCAN\nimport matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.get_configdir()\nplt.style.use('seaborn-poster')\nfrom mpl_toolkits.mplot3d import Axes3D\n\nFONTSIZE = 50\n\nclass Transforms:\n\n def __init__(self, event):\n self._EventData = event\n self._X, self._Y, self._Z = self._EventData.data\n self._XYp = [self.conformalTransform(x, y) for (x, y) in zip(self._X,\n self._Y) if self.conformalTransform(x, y)[2]]\n self._Xp, self._Yp, self._Rsquared = zip(*self._XYp)\n\n def conformalTransform(self, x, y):\n rhit_squared = (x**2 + y**2)\n if rhit_squared:\n xp = x / rhit_squared\n yp = y / rhit_squared\n return xp, yp, rhit_squared\n else:\n print(\"r2: \", rhit_squared)\n return 0, 0, 0\n\n def rho(self, rhit_squared, xp, yp, phi):\n r = (xp * np.cos(phi) + yp * np.sin(phi))\n return r\n\n def rho_phi(self, rhit_squared, xp, yp, numpoints):\n phis = np.linspace(0, 2*np.pi, numpoints)\n rhos = [] # [self.rho(rhit_squared, xp, yp, phi) for phi in phis]\n phis_return = []\n for phi in phis:\n rho = self.rho(rhit_squared, xp, yp, phi)\n if (rho>=0):\n phis_return.append(phi)\n rhos.append(rho)\n return phis_return, rhos\n\n def HoughTransform_phi(self, numpoints, binx, biny, plotName=\"\"):\n\n ht_phi = []\n ht_rho = []\n for i in range(0, len(self._Xp)):\n phis, rhos = self.rho_phi(self._Rsquared[i], self._Xp[i], self._Yp[i], numpoints)\n\n ht_phi.extend(phis)\n ht_rho.extend(rhos)\n\n # myrange=[[0, 2*np.pi], [min(ht_rho), 0.0008]]\n myrange=[[0, 2*np.pi], [min(ht_rho), max(ht_rho)]]\n print(\"*** myrange: \", myrange)\n\n H, xedges, yedges = np.histogram2d(ht_phi, ht_rho, bins = (binx, biny), range=myrange)\n print(\"xedge: \", xedges.shape)\n print(\"yedge: \", yedges.shape)\n\n print(\"min rho: \", min(ht_rho))\n print(\"max rho: \", max(ht_rho))\n\n\n bx = (myrange[0][1]-myrange[0][0])/binx\n by = (myrange[1][1]-myrange[1][0])/biny\n trackpos, labels = self.cluster_test(H)\n unique_labels = set(labels)\n max_x, max_y = self.getCoords(trackpos, xedges, yedges, bx, by)\n\n\n fig_HT_phi = plt.figure()\n h=plt.hist2d(ht_phi, ht_rho, bins=(binx, biny), cmap=plt.cm.jet, range=myrange)\n plt.scatter(max_x, max_y, marker=\"o\", alpha=0.5, facecolors='black', edgecolors='black', label=\"# hits > 112\")\n plt.scatter(max_x, max_y, marker = 'x',\n c=[matplotlib.cm.nipy_spectral((float(i)+0.5)/len(unique_labels)) for i in labels], label=\"Cluster\")\n plt.legend()\n\n # for i in range(0, len(labels)):\n # print(\"label: \", labels[i], \"color: \", (float(labels[i])+1)/len(unique_labels), \", x: \", max_x[i], \", y: \", max_y[i])\n\n plt.colorbar(h[3])\n plt.xlabel(r'$\\phi$ [rad]', fontsize=FONTSIZE)\n plt.ylabel(r'$\\rho$ [1/mm]', fontsize=FONTSIZE)\n plt.tight_layout()\n if plotName:\n plt.savefig(plotName)\n else:\n plt.show()\n\n\n return H, xedges, yedges\n\n\n def cluster_test(self, H):\n am = H.argmax()\n r_idx = am % H.shape[1]\n c_idx = am // H.shape[1]\n\n trackpos = np.argwhere(H>112)\n\n print(\"size H: \", H.shape)\n # print(\"Ultimate max: \", r_idx, \", \", c_idx)\n print(\"Ultimate max: \", unravel_index(am, H.shape))\n print(\"Above threshold: \", trackpos.shape)\n # print(H[trackpos[0][1]][trackpos[0][1]])\n # print(trackpos[0][0])\n print(trackpos)\n\n clustering = DBSCAN(eps=np.sqrt(2), min_samples=2).fit(trackpos)\n clustering.fit(trackpos)\n labels = clustering.labels_\n unique_labels = set(labels)\n # clu_center = clustering.cluster_centers_\n print(\"labels: \", labels)\n print(\"Components: \", clustering.core_sample_indices_)\n print(\"unique labels: \", unique_labels)\n # print(\"centers: \", clu_center)\n n_clusters = len(set(labels)) - (1 if -1 in labels else 0)\n print (\"num clusters: \", n_clusters)\n print(\"H at centers:\", [H[pos[0]][pos[1]] for pos in trackpos])\n return trackpos, labels\n\n def getCoords(self, trackpos, x, y, bx, by):\n xp = [x[a[0]]+bx/2.0 for a in trackpos]\n yp = [y[a[1]]+by/2.0 for a in trackpos]\n\n # for i in range(0, len(trackpos)):\n # print(trackpos[i], \" *** \", xp[i], \" *** \", yp[i])\n\n return xp, yp\n\n def plotConformalTransform(self, plotName=\"\"):\n fig_conformalTransform = plt.figure()\n plt.scatter(self._Xp, self._Yp)#, c = 'DarkBlue', linestyle='-')\n # plt.title(\"Conformal transform\")\n plt.legend(loc='upper left')\n plt.xlabel(\"u\", fontsize=FONTSIZE)\n plt.ylabel(\"v\", fontsize=FONTSIZE)\n # print(\"rangeCOnf: \", rangeConf[0])\n plt.xlim([min(self._Xp), max(self._Xp)])\n plt.ylim([min(self._Yp), max(self._Yp)])\n plt.tight_layout()\n if plotName:\n plt.savefig(plotName)\n else:\n plt.show()\n\n\n # def DoFullHT(self, mrange, rangeConf, numpoints=500, binx=200, biny = 200, plotName=\"\"):\n # Xp, Yp, rhit_squared = zip(*XY_p)\n # fig_conformalTransform = plt.figure()\n # plt.scatter(Xp, Yp, c = 'DarkBlue', linestyle='-')\n # plt.title(\"Conformal transform\")\n # plt.legend(loc='upper left')\n # plt.xlabel(\"u\")\n # plt.ylabel(\"v\")\n # plt.xlim(rangeConf[0])\n # plt.ylim(rangeConf[1])\n # plt.tight_layout()\n # # plt.show()\n #\n # R_, theta_ = HoughTransform_phi(Rsquared=rhit_squared, Xp=Xp, Yp=Yp,\n # numpoints=numpoints,\n # binx=binx, biny=biny, myrange=mrange, plotName = plotName)\n # radius_calc = 1./(2*R_)\n # a_calc = np.cos(theta_)/(2*R_)\n # b_calc = np.sin(theta_)/(2*R_)\n #\n # return radius_calc, a_calc, b_calc, theta_\n" }, { "alpha_fraction": 0.7497291564941406, "alphanum_fraction": 0.7529793977737427, "avg_line_length": 30.827587127685547, "blob_id": "cfe24604c59b64d8b9eb0e8dac564f8b0eb509dc", "content_id": "ee3588250839b5cb7596142dbdcabbd425b52b94", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 923, "license_type": "permissive", "max_line_length": 108, "num_lines": 29, "path": "/README.md", "repo_name": "HEP-FCC/HoughTransform", "src_encoding": "UTF-8", "text": "# Hough Transform\n\nA package for track reconstruction using the Hough Transformation.\nDeveloped for the tracking of the drift chamber of the FCCeeIDEA detector concept.\n\n## Installation (for Mac OS X)\n\n* Clone the repository: `git clone https://github.com/nalipour/HoughTransform.git`\n* Install python: `brew install python3`\n* Create a virtual environment *my-env*, install the required packages and run the program\n\n * `virtualenv --python python3 my-env`\n * `source my-env/bin/activate`\n * `pip install -r requirements.txt `\n\n## Run\n\nFirst, the output hits from the FCCSW simulation needs to be written in a CSV file format using the command:\n\n `python rootTree2CSV.py --input=hits.root --output = hits.csv`\n\n\nThe Hough transform can be run using the following command:\n\n`python main.py --input=hits.csv --output=./plot/`\n\n\n## The Hough transform for one particle track\n![your_image_name](images/zoom_HT_withMax.png)\n" } ]
5
artmortal93/Yolo
https://github.com/artmortal93/Yolo
1774ceea8e3e38633333eb218b4c4fe42bd575aa
2cadf41898d0cc6ace9879350f107d266fe088da
31c13fec75de847edd9077a04bf40f5d8c85527f
refs/heads/master
2020-04-11T11:41:08.034816
2018-12-16T09:43:52
2018-12-16T09:43:52
161,756,287
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5178700089454651, "alphanum_fraction": 0.5859918594360352, "avg_line_length": 37.58333206176758, "blob_id": "b9f2314e46dbf07e81cf15649cdcdd3a8b4cee39", "content_id": "61f2546665482a5d94ba115a81a2584a3360d870", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4169, "license_type": "no_license", "max_line_length": 130, "num_lines": 108, "path": "/yolov1/yolo_net.py", "repo_name": "artmortal93/Yolo", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport re\nfrom .net import Net\n\n\nclass YoloNet(Net):\n def __init__(self,common_params,net_params,test=False):\n super().__init__(common_params,net_params)\n self.image_size=int(common_params['image_size'])\n self.num_classes=int(common_params['num_classes'])\n self.cell_size=int(net_params['cell_size'])\n self.boxes_per_cell=int(net_params['boxes_per_cell'])\n self.batch_size=int(common_params['batch_size'])\n self.weighted_decay=float(net_params['weight_decay'])\n\n if not test:\n self.object_scale=float(net_params['object_scale'])\n self.noobject_scale=float(net_params['noobject_scale'])\n self.class_scale=float(net_params['class_scale'])\n self.coord_scale=float(net_params['coord_scale'])\n\n\n\n\n def inference(self,images):\n conv_num=1\n temp_conv=self.conv2d('conv'+str(conv_num),images,[7,7,3,64],stride=2)\n conv_num+=1\n\n temp_pool=self.max_pool(temp_conv,[2,2],2)\n temp_conv=self.conv2d('conv'+str(conv_num),temp_pool,[3,3,64,192],stride=1)\n conv_num+=1\n\n temp_pool=self.max_pool(temp_conv,[2,2],2)\n temp_conv=self.conv2d('conv'+str(conv_num),temp_pool,[1,1,192,128],stride=1)\n conv_num+=1\n\n temp_conv = self.conv2d('conv' + str(conv_num), temp_conv, [3, 3, 128, 256], stride=1)\n conv_num+=1\n\n temp_conv = self.conv2d('conv' + str(conv_num), temp_conv, [1, 1, 256, 256], stride=1)\n conv_num += 1\n\n temp_conv = self.conv2d('conv' + str(conv_num), temp_conv, [3, 3, 256, 512], stride=1)\n conv_num += 1\n\n temp_conv=self.max_pool(temp_conv,[2,2],2)\n\n for i in range(4):\n temp_conv=self.conv2d('conv'+str(conv_num),temp_conv,[1,1,512,256],stride=1)\n conv_num+=1\n temp_conv = self.conv2d('conv' + str(conv_num), temp_conv, [3,3,256,512], stride=1)\n conv_num += 1\n\n temp_conv = self.conv2d('conv' + str(conv_num), temp_conv, [1, 1, 512, 512], stride=1)\n conv_num += 1\n temp_conv = self.conv2d('conv' + str(conv_num), temp_conv, [3, 3, 512, 1024], stride=1)\n conv_num += 1\n\n temp_conv=self.max_pool(temp_conv,[2,2],2)\n\n for i in range(2):\n temp_conv=self.conv2d('conv'+str(conv_num),temp_conv,[1,1,1024,512],stride=1)\n conv_num+=1\n temp_conv=self.conv2d('conv'+str(conv_num),temp_conv,[3,3,512,1024],stride=1)\n conv_num+=1\n\n temp_conv=self.conv2d('conv'+str(conv_num),temp_conv,[3,3,1024,1024],stride=1)\n conv_num+=1\n temp_conv=self.conv2d('conv'+str(conv_num),temp_conv,[3,3,1024,1024],stride=2)\n conv_num+=1\n\n\n temp_conv=self.conv2d('conv'+str(conv_num),temp_conv,[3,3,1024,1024],stride=1)\n conv_num+=1\n temp_conv = self.conv2d('conv' + str(conv_num), temp_conv, [3, 3, 1024, 1024], stride=1)\n conv_num += 1\n\n\n\n local1=self.local('local1',temp_conv,49*1024,4096)\n local1=tf.nn.dropout(local1,keep_prob=0.5)\n\n local2=self.local('local2',local1,4096,self.cell_size*self.cell_size*(self.num_classes+5*self.boxes_per_cell),leaky=False)\n\n local2=tf.reshape(local2,[tf.shape(local2)[0],self.cell_size,self.cell_size,self.num_classes+5*self.boxes_per_cell])\n predicts=local2\n return predicts\n\n def iou(self,boxes1,boxes2):\n \"\"\"\n\n :param boxes1:[cell,cell,boxes_per_cell,4]==>(x_center,y_center,w,h),4D tensor\n :param boxes2: 1-D tensor with (x_center,y_center,w,h)\n :return: 3-D tensor[CELL_SIZE,CELL_SIZE,BOXES_PER_CELL]\n \"\"\"\n #transfer to topleft(x,y) & bottomright(x,y)\n boxes1=tf.stack(\n [boxes1[:,:,:,0]-boxes1[:,:,:,2]/2,boxes1[:,:,:,1]-boxes1[:,:,:,3]/2,\n boxes1[:,:,:,0]+boxes1[:,:,:,2]/2,boxes1[:,:,:,1]+boxes1[:,:,:,3]/2]\n )\n boxes1=tf.transpose(boxes1,[1,2,3,0]) #y_top,y_bottom,x_bottom,x_top\n #x,y,x,y\n boxes2=tf.stack([boxes2[0]-boxes2[2]/2,boxes2[1]-boxes2[3]/2,boxes2[0]+boxes2[2]/2,boxes2[1]+boxes2[3]/2])\n\n def loss(self,predicts,labels,objects_num):\n pass\n\n\n" }, { "alpha_fraction": 0.5979467034339905, "alphanum_fraction": 0.6109877824783325, "avg_line_length": 38.16304397583008, "blob_id": "3e4c0e1251020f220dc0860d9e2151c96b07e49c", "content_id": "9243f57c06d1402cf740d176f77d9c17dc676bcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3604, "license_type": "no_license", "max_line_length": 151, "num_lines": 92, "path": "/yolov1/net.py", "repo_name": "artmortal93/Yolo", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom easydict import EasyDict as edict\nimport numpy\n\n\nclass Net(object):\n def __init__(self,commmon_params,net_params):\n self.pretrained_collection=[]\n self.trainable_collection=[]\n\n def _variable_on_cpu(self,name,shape,initializer,pretrain=True,train=True):\n with tf.device('/cpu:0'):\n var=tf.get_variable(name,shape,initializer=initializer,dtype=tf.float32)\n if pretrain==True:\n self.pretrained_collection.append(var)\n if train==True:\n self.trainable_collection.append(var)\n return var\n\n def _variable_with_weight_decay(self,name,shape,stddev,wd,pretrain=True,train=True):\n \"\"\"\n\n :param name:\n :param shape:\n :param stddev:\n :param wd:short for weight decay\n :param pretrain:\n :param train:\n :return:\n \"\"\"\n var=self._variable_on_cpu(name,shape,initializer=tf.truncated_normal_initializer(stddev=stddev,dtype=tf.float32),pretrain=pretrain,train=train)\n if wd is not None:\n weight_decay=tf.multiply(tf.nn.l2_loss(var),wd,name='weight_loss')\n tf.add_to_collection('losses',weight_decay)\n return var\n\n def conv2d(self,scope,input,kernel_size,stride=1,pretrain=True,train=True):\n with tf.variable_scope(scope) as scope:\n kernel=self._variable_with_weight_decay('weights',shape=kernel_size,stddev=5e-2,wd=self.weight_decay,\n pretrain=pretrain,train=train)\n conv=tf.nn.conv2d(input,kernel,[1,stride,stride,1],padding='SAME')\n biases=self._variable_on_cpu('biases',kernel_size[3:],tf.constant_initializer(0.0),pretrain,train)\n bias=tf.nn.bias_add(conv,biases)\n conv1=self.leaky_relu(bias)\n return conv1\n\n\n def max_pool(self,input,kernel_size,stride):\n return tf.nn.max_pool(input,ksize=[1,kernel_size[0],kernel_size[1],1],strides=[1,stride,stride,1],padding='SAME')\n\n\n def local(self,scope,input,in_dimension,out_dimension,leaky=True,pretrain=True,train=True):\n with tf.variable_scope(scope) as scope:\n reshape=tf.reshape(input,[tf.shape(input)[0],-1])\n weights=self._variable_with_weight_decay('weights',shape=[in_dimension,out_dimension],\n stddev=0.04,wd=self.weight_decay,pretrain=pretrain,train=train)\n biases=self._variable_on_cpu('biases',[out_dimension],tf.constant_initializer(0.0),pretrain,train)\n local=tf.matmul(reshape,weights)+biases\n\n if leaky:\n local=self.leaky_relu(local)\n else:\n local=tf.identity(local,name=scope.name)\n return local\n\n\n def leaky_relu(self,x,alpha=0.1,dtype=tf.float32):\n x=tf.cast(x,dtype=dtype)\n bool_mask=(x>0)\n mask=tf.cast(bool_mask,dtype=dtype)\n return 1.0*mask*x+alpha*(1-mask)*x\n\n\n\n def inference(self,images):\n \"\"\"\n\n :param images:\n :return: 4D TENSOR with[batch,cell,cell.num_classes+5*boxes_per_cell]\n \"\"\"\n raise NotImplementedError\n\n def loss(self, predicts, labels, objects_num):\n\n \"\"\"Add Loss to all the trainable variables\n Args:\n predicts: 4-D tensor [batch_size, cell_size, cell_size, 5 * boxes_per_cell]\n ===> (num_classes, boxes_per_cell, 4 * boxes_per_cell)\n labels : 3-D tensor of [batch_size, max_objects, 5]\n objects_num: 1-D tensor [batch_size]\n \"\"\"\n raise NotImplementedError\n\n" } ]
2
dimaskarabass/hinterfa
https://github.com/dimaskarabass/hinterfa
430521411a734c9be82b549466bc1c12d902a499
d645609d27811d6a68c0cb1f43077ec86f34cc22
7656d93cb9d995d44c49ea5d346c4c1380703a75
refs/heads/master
2020-09-10T18:13:04.162864
2020-03-20T12:31:17
2020-03-20T12:31:17
221,791,283
0
4
null
null
null
null
null
[ { "alpha_fraction": 0.507080614566803, "alphanum_fraction": 0.5185185074806213, "avg_line_length": 35.720001220703125, "blob_id": "338f6cabd329674bcc76282eb9383564d00ec7fd", "content_id": "f41ca1d23434f4cb294b8ad1215c97df7a7a9421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1836, "license_type": "no_license", "max_line_length": 122, "num_lines": 50, "path": "/parsing/test.py", "repo_name": "dimaskarabass/hinterfa", "src_encoding": "UTF-8", "text": "import csv\nfrom lxml import html\nfrom urllib.request import urlopen\nfrom lxml import etree\n\ndef addto_csv(html_doc): #adding to .csv\n tree = html.fromstring(html_doc)\n xml_tr = tree.xpath('//tr') #xml lines\n names = []\n phones = []\n npi = []\n primary = []\n adressfp = []\n adresssp = []\n adress = []\n for i in range(len(xml_tr)):\n str_tr = etree.tostring(xml_tr[i])\n tree2 = html.fromstring(str_tr)\n xml_td = tree2.xpath('//td')\n if len(xml_td) == 6:\n names.append(xml_td[1].text)\n phones.append(xml_td[4].text)\n adressfp.append(xml_td[3].text)\n tree3 = html.fromstring(etree.tostring(xml_td[0]))\n xml_a = tree3.xpath('//a')\n npi.append(xml_a[0].text)\n tree4 = html.fromstring(etree.tostring(xml_td[5]))\n xml_div = tree4.xpath('//div')\n try:\n primary.append(xml_div[0].text)\n except IndexError:\n xml_div = tree4.xpath('//td')\n primary.append(xml_div[0].text)\n str_adds = etree.tostring(xml_td[3])\n str_adds = str_adds.decode('utf-8').replace(\"\\t\", \"\")\n n = str_adds.find(\"<br/>\")\n str_adds = str_adds.replace(\"\\n\", \"\")\n str_adds = str_adds[n + 5:]\n str_adds = str_adds[:str_adds.find('<')]\n adress.append(xml_td[3].text)\n adress[-1] += str_adds\n\n\n with open(\"data.csv\", 'a') as file:\n fieldnames = ['NPI', 'names', 'adress', 'phones', 'primary']\n writer = csv.DictWriter(file, fieldnames=fieldnames)\n\n writer.writeheader()\n for i in range(len(npi)):\n writer.writerow({'NPI':npi[i],'names':names[i],'adress': adress[i],'phones': phones[i],'primary': primary[i]})\n" }, { "alpha_fraction": 0.7941176295280457, "alphanum_fraction": 0.7941176295280457, "avg_line_length": 33, "blob_id": "b3f4923d38e7d15a992f76f1694e9131a5b3d6f5", "content_id": "564255a40aa925fede2d533d255adb81303a9d4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 34, "license_type": "no_license", "max_line_length": 33, "num_lines": 1, "path": "/readme.txt", "repo_name": "dimaskarabass/hinterfa", "src_encoding": "UTF-8", "text": "parsing data in .csv from website\n" }, { "alpha_fraction": 0.5625479817390442, "alphanum_fraction": 0.5786646008491516, "avg_line_length": 38.48484802246094, "blob_id": "58ca77bd1fe532f51970b4dfd9bcb57cd75d584c", "content_id": "6cc20c5c91ed402cc70082f4b760006ec6e840aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1303, "license_type": "no_license", "max_line_length": 165, "num_lines": 33, "path": "/parsing/just_for_fun.py", "repo_name": "dimaskarabass/hinterfa", "src_encoding": "UTF-8", "text": "import aiohttp\nimport asyncio\nimport csv #add to .csv\nfrom test import addto_csv\nfrom lxml import html #parsing lib\nfrom lxml import etree\n\nasync def fetch(url, session):\n async with session.get(url) as response:\n return await response.read()\n\nn = 0;\n\nasync def run(r):\n url = 'https://npiregistry.cms.hhs.gov/registry/search-results-table?entity_type=NPI-1&amp;taxonomy_description=REGISTERED+NURSE&amp;addressType=ANY&amp;skip={}'\n tasks = []\n global n\n timeout = aiohttp.ClientTimeout(total=60 * 40)\n async with aiohttp.ClientSession(timeout = timeout) as session:\n for i in range(r): #creating tasks\n task = asyncio.ensure_future(fetch(url.format(i * 100 + (n * 1000)), session))\n tasks.append(task)\n responses = await asyncio.gather(*tasks) #running tasks\n n += 1;\n for k in responses:\n addto_csv(k) #adding to .csv\n session.close()\n\nwhile(n <= 171): #creating a lot of sessions with 10 parallel tasks\n loop = asyncio.get_event_loop()\n future = asyncio.ensure_future(run(10))\n loop.run_until_complete(future)\n print (n)\n" } ]
3
venkat7568/project-2
https://github.com/venkat7568/project-2
548afa9141e9c607cec8efdbbde1c4d12e90f19d
182838c9e04e7f79f020803598ca4eb1383b08e5
af4657d19e7f6167043cf44faa83bb94b9170813
refs/heads/main
2023-06-23T18:18:15.723722
2021-07-26T13:35:01
2021-07-26T13:35:01
389,645,946
0
0
null
2021-07-26T13:39:19
2021-07-26T13:35:03
2021-07-26T13:35:00
null
[ { "alpha_fraction": 0.5384825468063354, "alphanum_fraction": 0.5652292370796204, "avg_line_length": 25.08148193359375, "blob_id": "ebc7eb2a51ad0c91380df01666bbe091e6e8f9c6", "content_id": "68d217d67e8f493fc257b6973c3b6f4b14ea8e8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3664, "license_type": "no_license", "max_line_length": 91, "num_lines": 135, "path": "/Space Battle/main.py", "repo_name": "venkat7568/project-2", "src_encoding": "UTF-8", "text": "import pygame\r\nimport random\r\nimport math\r\n\r\n# Intialize the pygame\r\npygame.init()\r\n# create the screen\r\nscreen = pygame.display.set_mode((800, 600))\r\n# Background\r\nbackground = pygame.image.load('background.jpg')\r\n\r\n# Caption and Icon\r\npygame.display.set_caption(\"Space Batlle\")\r\nicon = pygame.image.load('spaceship.png')\r\npygame.display.set_icon(icon)\r\n# Player\r\nplayerImg = pygame.image.load('player.png')\r\nplayerX = 340\r\nplayerY = 480\r\nplayerX_change = 0\r\n# Enemy\r\nalienImg = []\r\nalienX = []\r\nalienY = []\r\nalienX_change = []\r\nalienY_change = []\r\nnum_of_aliens = 6\r\n\r\nfor i in range(num_of_aliens):\r\n alienImg.append(pygame.image.load('alien.png'))\r\n alienX.append(random.randint(0, 735))\r\n alienY = random.randint(50, 150)\r\n alienX_change.append(0.2)\r\n alienY_change.append(40)\r\n\r\n# Bullet\r\n# Ready - You can't see the bullet on the screen\r\n# Fire - The bullet is currently moving\r\nbulletImg = pygame.image.load('bullet.png')\r\nbulletX = 0\r\nbulletY = 480\r\nbulletX_change = 0\r\nbulletY_change = 2\r\nbullet_state = \"ready\"\r\n\r\nscore = 0\r\n\r\n\r\ndef player(x, y):\r\n screen.blit(playerImg, (x, y))\r\n\r\n\r\ndef alien(x, y, i):\r\n screen.blit(alienImg[i], (x, y))\r\n\r\n\r\ndef fire_bullet(x, y):\r\n global bullet_state\r\n bullet_state = \"fire\"\r\n screen.blit(bulletImg, (x + 35, y + 10))\r\n\r\n\r\ndef isCollision(alienX, alienY, bulletX, bulletY):\r\n distance = math.sqrt((math.pow(alienX - bulletX, 2)) + (math.pow(alienY - bulletY, 2)))\r\n if distance < 27:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n# Game Loop\r\nrunning = True\r\nwhile running:\r\n screen.fill((0, 0, 80))\r\n # Background Image\r\n screen.blit(background, (0, 0))\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n # if keystroke is pressed check whether its right or left\r\n if event.type == pygame.KEYDOWN:\r\n\r\n if event.key == pygame.K_LEFT:\r\n playerX_change = -0.3\r\n if event.key == pygame.K_RIGHT:\r\n playerX_change = 0.3\r\n if event.key == pygame.K_SPACE:\r\n if bullet_state == \"ready\":\r\n # Get the current x cordinate of the spaceship\r\n bulletX = playerX\r\n fire_bullet(bulletX, bulletY)\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n playerX_change = 0\r\n # 5 = 5 + -0.1 -> 5 = 5 - 0.1\r\n # 5 = 5 + 0.1\r\n\r\n # checking for boundaries of spaceship so it doesn't go out of bound\r\n playerX += playerX_change\r\n if playerX <= 0:\r\n playerX = 0\r\n elif playerX >= 700:\r\n playerX = 700\r\n # Enemy Movement\r\n for i in range(num_of_aliens):\r\n alienX[i] += alienX_change[i]\r\n if alienX[i] <= 0:\r\n alienX_change[i] = 0.2\r\n alienY[i] += alienY_change[i]\r\n elif alienX[i] >= 700:\r\n alienX_change[i] = -0.2\r\n alienY[i] += alienY_change[i]\r\n # Collision\r\n collision = isCollision(alienX(i), alienY(i), bulletX, bulletY)\r\n if collision:\r\n bulletY = 480\r\n bullet_state = \"ready\"\r\n score += 1\r\n print(score)\r\n alienX[i] = random.randint(0, 735)\r\n alienY[i] = random.randint(50, 150)\r\n\r\n alien(alienX[i], alienY[i], i)\r\n\r\n # Bullet Movement\r\n if bulletY <= 0:\r\n bulletY = 480\r\n bullet_state = \"ready\"\r\n if bullet_state == \"fire\":\r\n fire_bullet(bulletX, bulletY)\r\n bulletY -= bulletY_change\r\n\r\n player(playerX, playerY)\r\n\r\n pygame.display.update()\r\n\r\n\r\n\r\n\r\n" } ]
1
SoumyaSreedhar/Data-Structures-Algorithms
https://github.com/SoumyaSreedhar/Data-Structures-Algorithms
49fe4a22b32b734d2d1081018293ff7a42bcde27
952d3306a22802cf5a9137551895a557f863754c
1fe869efe16612ad3d573690947843f138ae074d
refs/heads/master
2020-05-16T21:50:11.564137
2020-03-02T22:04:45
2020-03-02T22:04:45
183,319,400
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5396518111228943, "alphanum_fraction": 0.5609284043312073, "avg_line_length": 26.61111068725586, "blob_id": "ba581d25b50cd8241840602c6aa3ade5bb6d6f49", "content_id": "5036d689cbc345567392d747fca0ff8e171c6b65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 68, "num_lines": 18, "path": "/Searches/Binary Search.py", "repo_name": "SoumyaSreedhar/Data-Structures-Algorithms", "src_encoding": "UTF-8", "text": "def binary_search(list,item): # item is the one we are searching for\r\n low=0\r\n high=len(list)-1\r\n\r\n while low <=high :\r\n mid =int((low+high)/2) #list of integers work\r\n guess=list[mid]\r\n if guess==item:\r\n return mid\r\n if guess > item:\r\n high=mid-1\r\n else:\r\n low=mid+1\r\n return None # the item does not exist\r\n\r\n# let's check, remember array needs to be sorted for binary search\r\nmy_list=[1,3,5,6,8]\r\nprint( binary_search(my_list,6))\r\n\r\n" }, { "alpha_fraction": 0.795918345451355, "alphanum_fraction": 0.8163265585899353, "avg_line_length": 48, "blob_id": "4ada244671a3682bb39e687d4d5a2ab00d9740af", "content_id": "b332f67986c6acebf3dde147e852d59540dbfd4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 49, "license_type": "no_license", "max_line_length": 48, "num_lines": 1, "path": "/Searches/README.md", "repo_name": "SoumyaSreedhar/Data-Structures-Algorithms", "src_encoding": "UTF-8", "text": "This Files contain cods for searches in Python 3\n" } ]
2
nochos55/flask-docker
https://github.com/nochos55/flask-docker
73336c747e6eb070fd55afbabf122914928d735d
1a6a60fdde3e900b44662325ca712e309a28c779
14d5b07767c6f5b450a0bbdb64935ff024fd7efa
refs/heads/main
2023-08-06T00:34:22.644188
2021-09-30T22:59:18
2021-09-30T22:59:18
412,251,462
0
0
null
2021-09-30T22:47:51
2021-09-30T22:31:36
2021-09-30T22:31:33
null
[ { "alpha_fraction": 0.6260346174240112, "alphanum_fraction": 0.638073742389679, "avg_line_length": 26.58333396911621, "blob_id": "166c3fb15a51f4e6ceede20b8b1b71e342ec415d", "content_id": "101a82c85c38dcaf4cb348f2cdcb78e6e8fdde71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1329, "license_type": "no_license", "max_line_length": 73, "num_lines": 48, "path": "/web/app.py", "repo_name": "nochos55/flask-docker", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, url_for, jsonify, make_response\nimport logging \nimport json \n \napp = Flask(__name__)\n\nlogging.basicConfig(filename='logs/app.log', level=logging.DEBUG)\n \[email protected]('/')\ndef hello_whale():\n endpoint = \"Home Page\"\n app.logger.info(f\"{endpoint} endpoint was reached\")\n return render_template(\"index.html\")\n\[email protected]('/test')\ndef test():\n endpoint = \"Testing Page\"\n app.logger.info(f\"{endpoint} was reached\")\n return render_template(\"test.html\") \n\[email protected]('/status')\ndef health_check():\n endpoint = \"Status\"\n #return make_response(jsonify(data), status)\n \n response = app.response_class(\n response=json.dumps({\"result\": \"OK - healthy\"}),\n status = 200,\n mimetype='application/json'\n )\n app.logger.info(f\"{endpoint} was reached\")\n return response\n\[email protected]('/metrics')\ndef metrics():\n data = {\"UserCount\" : 140, \"UserCountActive\" : 23}\n endpoint = \"Metrics\"\n# return make_response(jsonify(data), status)\n response = app.response_class(\n response=json.dumps({\"status\":\"success\",\"code\":0, \"data\":data}),\n status = 200,\n mimetype='application/json'\n )\n app.logger.info(f\"{endpoint} was reached\")\n return response\n \nif __name__ == '__main__':\n app.run(debug=True,port=5000)\n \n" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 11, "blob_id": "fd9157a2bf3a2986fd4ff7ea99d353b10c8d3460", "content_id": "bb744b49314123d003bc995a662ccf0b2145f128", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 12, "license_type": "no_license", "max_line_length": 11, "num_lines": 1, "path": "/web/requirements.txt", "repo_name": "nochos55/flask-docker", "src_encoding": "UTF-8", "text": "Flask==1.00\n" }, { "alpha_fraction": 0.656862735748291, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 30.384614944458008, "blob_id": "7993055c372941c78390d7960e5b18dc6a511d99", "content_id": "35c5fce211fbed7b675a62c1db6e77ec295402c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 408, "license_type": "no_license", "max_line_length": 84, "num_lines": 13, "path": "/web/templates/index.html", "repo_name": "nochos55/flask-docker", "src_encoding": "UTF-8", "text": "<!DOCTYPE html> \n<html> \n\t<head>\n\t\t<title>Anthony's Kubernetes Home Page</title>\n\t\t<link rel=\"stylesheet\" href=\"{{ url_for('static', filename='styles/main.css') }}\">\n\t</head>\n\t<body>\n\t\t<h1>This is Anthony's Test Page to learn Kubernetes!!!!</h1>\n\t\t<h2>If you're hitting this page, I guess something's gone right!!!</h2>\n\t\t<p>Maybe there will be some additional content generated below?</p>\n\t</body>\n\n</html>\n" } ]
3
zhaoqun05/Coding-Interviews
https://github.com/zhaoqun05/Coding-Interviews
8efe579b6a1a6186107f599a31a9e96389df52f3
e05c1e6390b3df49dd02571e13fb8a3822eae649
5b19ced6bd173baf11c4b5e9d1c08f17ca635773
refs/heads/master
2022-01-08T13:30:06.542796
2019-06-18T14:00:55
2019-06-18T14:00:55
282,934,693
2
0
null
2020-07-27T15:13:53
2020-05-30T17:45:28
2019-06-18T14:01:05
null
[ { "alpha_fraction": 0.4267241358757019, "alphanum_fraction": 0.48706895112991333, "avg_line_length": 26.280000686645508, "blob_id": "cf40d32f357de54b68189f13d9aeaf0638777eaf", "content_id": "11525ede9dfead4a2c154b2e9f057acbfbf217cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 952, "license_type": "no_license", "max_line_length": 91, "num_lines": 25, "path": "/Python/丑数.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def GetUglyNumber_Solution(self, index):\n # 普通的想法时遍历n个数,找到符合要求的数\n # 更好的思路是丑数都是2,3,5的倍数,直接找到他们。不对非丑数进行取余验证。\n # 空间换时间\n if index < 1 : return 0\n res = [1]\n k2,k3,k5 = 0 ,0 ,0\n for _ in range(1,index):\n min_num = min(res[k2]*2,res[k3]*3,res[k5]*5)\n res.append(min_num)\n if min_num == res[k2]*2:\n k2+=1\n if min_num == res[k3]*3:\n k3+=1\n if min_num == res[k5]*5:\n k5+=1\n return res[-1]\n \n" }, { "alpha_fraction": 0.5374564528465271, "alphanum_fraction": 0.5679442286491394, "avg_line_length": 30.88888931274414, "blob_id": "15b86945e0462e5e16b044cb0520ff5054b7d241", "content_id": "9ef0ae2168dce00df0ea4661ece91465ba5fbe9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1234, "license_type": "no_license", "max_line_length": 123, "num_lines": 36, "path": "/Python/树的子结构.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)\n'''\n\n\n\n# -*- coding:utf-8 -*-\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution:\n def HasSubtree(self, pRoot1, pRoot2):\n # write code here\n # Approach one O(n) 空间复杂度\n #def preRoot(root):\n # if not root: return []\n # return [root.val] + preRoot(root.left) + preRoot(root.right)\n #if not pRoot1 or not pRoot2: return False\n #l1 = preRoot(pRoot1)\n #l2 = preRoot(pRoot2)\n #for i in range(len(l1)):\n # if l1[i] == l2[0] and l1[i:len(l2)+i] == l2:\n # return True\n\n\n # Approach two O(m)~O(n*m) O(1)\n def is_subTree(root1, root2):\n if not root2: return True\n if not root1 or root1.val != root2.val: return False\n return is_subTree(root1.left, root2.left) and is_subTree(root1.right, root2.right)\n\n if not pRoot1 or not pRoot2: return False\n return is_subTree(pRoot1,pRoot2) or self.HasSubtree(pRoot1.left , pRoot2) or self.HasSubtree(pRoot1.right , pRoot2)\n" }, { "alpha_fraction": 0.4615384638309479, "alphanum_fraction": 0.5339366793632507, "avg_line_length": 22.678571701049805, "blob_id": "abcc82ba72d30c409367b0059fa3f1fbd16b6a97", "content_id": "10e1633426fd7d1dd56ad60c1f8b3cd5545740c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1023, "license_type": "no_license", "max_line_length": 64, "num_lines": 28, "path": "/Python/不用加减乘除做加法.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。\n\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def Add(self, num1, num2):\n # 不能用运算符,很容易想到是基于位运算和二进制的解法(加法三步走战略)\n # 第一步:两个数加和但不进位,也就是 0+0=0;0+1=1;1+0=1;1+1=0 可以用异或代替\n # 第二步:找到进位的位置,0+0=0;0+1=0;1+0=0;1+1=10 , 用与运算加左移一位的方式代替,\n # 第三步:重复上述两步,直到没有进位为止。\n\n # 如果出现负数上述方法会有问题,需要额外处理,相当于实现了减法\n MAX = 0x7FFFFFFF\n mask = 0xFFFFFFFF\n while num2:\n num1, num2 = num1 ^ num2, (num1 & num2) << 1\n num1 = num1 & mask\n num2 = num2 & mask\n return num1 if num1 <= MAX else ~(num1 ^ mask)\n\n\n # 瞎抖机灵\n # return sum([num1,num2])\n" }, { "alpha_fraction": 0.5911799669265747, "alphanum_fraction": 0.6019070148468018, "avg_line_length": 26.96666717529297, "blob_id": "459d5c10b6c339b1b8af091b7da7f577ccd131e7", "content_id": "b31302f29a0780d8d58962d43219e97f0dc371c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1021, "license_type": "no_license", "max_line_length": 80, "num_lines": 30, "path": "/Python/二叉搜索树与双向链表.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。\n\n'''\n\n\n# -*- coding:utf-8 -*-\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution:\n def __init__(self):\n self.head = None\n self.tail = None\n def Convert(self, pRootOfTree):\n # write code here\n # 中序遍历与递归,记住最左端节点,另一个辅助指针构建双向链表。\n # 思路解释 https://blog.csdn.net/huhehaotechangsha/article/details/90770854\n if not pRootOfTree: return\n self.Convert(pRootOfTree.left)\n if not self.head :\n self.head,self.tail = pRootOfTree,pRootOfTree\n else:\n self.tail.right,pRootOfTree.left = pRootOfTree,self.tail\n self.tail = self.tail.right\n self.Convert(pRootOfTree.right)\n return self.head\n" }, { "alpha_fraction": 0.49614396691322327, "alphanum_fraction": 0.5, "avg_line_length": 26.785715103149414, "blob_id": "b57a3ca39dd7f6f54552b2c71cce3209b4a4a854", "content_id": "1478c4373ac3e66328e27f28817eb18e2ccfe031", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 922, "license_type": "no_license", "max_line_length": 72, "num_lines": 28, "path": "/Python/按之字形顺序打印二叉树.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。\n'''\n\n\n# -*- coding:utf-8 -*-\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution:\n def Print(self, pRoot):\n # write code here\n if not pRoot: return []\n res , q = [] ,[pRoot]\n next_right = True\n while q:\n length = len(q)\n cur = []\n for _ in range(length):\n node = q.pop(0)\n cur.append(node.val)\n if node.left: q.append(node.left)\n if node.right: q.append(node.right)\n next_right = not next_right\n res.append(cur[::-1] if next_right else cur)\n return res\n" }, { "alpha_fraction": 0.39842984080314636, "alphanum_fraction": 0.4406280815601349, "avg_line_length": 27.30555534362793, "blob_id": "a8262c2a70c8c069aee603733059f1807ad9ca4f", "content_id": "ab61f16567bd595e2fd082280718785074d0f5d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1189, "license_type": "no_license", "max_line_length": 101, "num_lines": 36, "path": "/Python/数组中的逆序对.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "''''\n\n在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007\n''''\n\n\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def InversePairs(self, data):\n # 此题类似于leetcode 315题\n # Approach one 归并排序\n\n def MergeSort(enum):\n global res\n half = len(enum) // 2\n if half:\n left, right = MergeSort(enum[:half]), MergeSort(enum[half:])\n m, n = len(left), len(right)\n i = j = 0\n while i < m or j < n:\n if j == n or i < m and left[i][1] <= right[j][1]:\n enum[i+j] = left[i]\n res += j\n i += 1\n else:\n enum[i+j] = right[j]\n j += 1\n return enum\n\n if len(data) < 2: return [0 for _ in range(len(data))]\n global res\n res = 0\n MergeSort(list(enumerate(data)))\n return res % 1000000007\n" }, { "alpha_fraction": 0.6655948758125305, "alphanum_fraction": 0.672025740146637, "avg_line_length": 24.91666603088379, "blob_id": "b1d9279f741e20eb39dc95b3be60c2b9a5c15c06", "content_id": "11381b560270b84ac9b88b54bf59b3825b6bd5cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 543, "license_type": "no_license", "max_line_length": 145, "num_lines": 12, "path": "/Python/左旋转字符串.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def LeftRotateString(self, s, n):\n # write code here\n return ''.join(list(s)[n:] + list(s)[:n])\n" }, { "alpha_fraction": 0.4880652129650116, "alphanum_fraction": 0.5156219601631165, "avg_line_length": 26.37765884399414, "blob_id": "d4f04a3fc9bf2eeeae500e130248c4242ce47e79", "content_id": "c5a043a1beb65ad33fa8058946cfeb709254a583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5423, "license_type": "no_license", "max_line_length": 88, "num_lines": 188, "path": "/Python/sort.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: sort\n Description :\n Author : bw_zhang\n date: 2019/3/26 14:55\n-------------------------------------------------\n Change Activity: 2019/3/26 14:55\n-------------------------------------------------\n\"\"\"\n\nimport time\nimport random\n\n\n\n\ndef BubbleSort(nums):\n start = time.time()\n if len(nums) < 2: return nums\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] > nums[j]:\n nums[i], nums[j] = nums[j], nums[i]\n print('BubbleSort answer is {}, used {} : '.format(nums, time.time() - start))\n\n\n\ndef BubbleSort_quick(nums):\n start = time.time()\n if len(nums) < 2: return nums\n flag = True\n for i in range(len(nums)):\n if flag == False : break\n flag = False\n for j in range(i + 1, len(nums)):\n if nums[i] > nums[j]:\n nums[i], nums[j] = nums[j], nums[i]\n flag = True\n print('BubbleSort_quick answer is {}, used {} : '.format(nums, time.time() - start))\n\n\ndef SelectSort(nums):\n start = time.time()\n if len(nums) < 2: return nums\n for i in range(len(nums)):\n min_num = i \n for j in range(i + 1, len(nums)):\n if nums[j] < nums[min_num]:\n min_num = j\n if min_num != i:\n nums[min_num], nums[i] = nums[i], nums[min_num]\n print('SelectSort answer is {}, used {} : '.format(nums, time.time() - start))\n\n\ndef InsertSort(nums):\n start = time.time()\n if len(nums) < 2: return nums\n key = 1\n while key < len(nums):\n for i, n in enumerate(nums[:key]):\n if nums[key] < n:\n nums.insert(i, nums.pop(key))\n break\n if i == len(nums[:key]) - 1 : nums.insert(i + 1 , nums.pop(key)) \n key += 1\n print('InsertSort answer is {}, used {} : '.format(nums, time.time() - start))\n\n\n\n\n\ndef QuickSort(nums, left, right):\n if left >= right: return # 快排是一个原地排序,不需要返回nums\n low, high = left, right\n key = nums[low]\n while left < right:\n while left < right and nums[right] > key:\n right -= 1\n nums[left] = nums[right]\n while left < right and nums[left] <= key:\n left += 1\n nums[right] = nums[left]\n nums[right] = key\n QuickSort(nums, low, left - 1)\n QuickSort(nums, left + 1, high)\n\n\n\n\ndef QuickSort_approach_two(array, l, r):\n def partition(array, l, r):\n key = array[l]\n while l < r:\n while l < r and array[r] >= key:\n r -= 1\n if l < r:\n array[l] = array[r]\n while l < r and array[l] < key:\n l += 1\n if l < r:\n array[r] = array[l]\n array[l] = key\n return l\n\n if l < r:\n if len(array) < 2: return\n q = partition(array, l, r)\n QuickSort_approach_two(array, l, q - 1)\n QuickSort_approach_two(array, q + 1, r)\n\n\n\n\n\ndef merge_sort(nums):\n if len(nums) < 2 : return nums \n mid = len(nums) //2\n first = merge_sort(nums[:mid])\n secend = merge_sort(nums[mid:])\n return merge(first, secend)\n\ndef merge(first, secend):\n result = []\n i , j = 0 , 0\n length_f, length_s = len(first), len(secend) \n while i < length_f and j < length_s:\n if first[i] <= secend[j]:\n result.append(first[i])\n i += 1\n else:\n result.append(secend[j])\n j += 1\n return result + first[i:] + secend[j:]\n\n\n\n\n\n\ndef MAX_Heapify(heap,HeapSize,root):#在堆中做结构调整使得父节点的值大于子节点\n left = 2*root + 1\n right = left + 1\n larger = root\n if left < HeapSize and heap[larger] < heap[left]:\n larger = left\n if right < HeapSize and heap[larger] < heap[right]:\n larger = right\n if larger != root:#如果做了堆调整则larger的值等于左节点或者右节点的,这个时候做对调值操作\n heap[larger],heap[root] = heap[root],heap[larger]\n MAX_Heapify(heap, HeapSize, larger)\n\ndef Build_MAX_Heap(heap):#构造一个堆,将堆中所有数据重新排序\n HeapSize = len(heap)#将堆的长度当独拿出来方便\n for i in range((HeapSize -2)//2,-1,-1):#从后往前出数\n MAX_Heapify(heap,HeapSize,i)\n\ndef HeapSort(heap):#将根节点取出与最后一位做对调,对前面len-1个节点继续进行对调整过程。\n if len(heap) < 2 : return heap\n start = time.time()\n Build_MAX_Heap(heap)\n for i in range(len(heap)-1,-1,-1):\n heap[0],heap[i] = heap[i],heap[0]\n MAX_Heapify(heap, i, 0)\n print('InsertSort answer is {}, used {} : '.format(heap, time.time() - start))\n\n\n\n\nif __name__ == '__main__':\n little = [30,50,57,77,62,78,94,80,84]\n nums = [random.randint(1,1000) for i in range(1000)]\n # num = [5, 3, 8, 6, 4, 5, 9, 39, 30, 9, 0, 4, 1, 62, 5]\n # num = [random.randrange(-100000, 100000, 1) for _ in range(10000)]\n\n # BubbleSort(nums+ [i for i in range(1000) ])\n # BubbleSort_quick(nums + [i for i in range(1000) ])\n\n # SelectSort(num)\n # InsertSort(nums)\n # QuickSort_1(num, 0, len(num) - 1)\n # QuickSort(num, 0, len(num) - 1)\n # QuickSort_approach_two(num, 0, len(num) - 1)\n # print(num)\n # print(merge_sort(nums))\n\n HeapSort(little)\n\n\n\n " }, { "alpha_fraction": 0.5021644830703735, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 21, "blob_id": "3e3056342d75b778e04df41159d68f087586574a", "content_id": "8f6aad7bfed259d1d38c6ee5294b5fb3fc681f7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 502, "license_type": "no_license", "max_line_length": 50, "num_lines": 21, "path": "/Python/两个链表的第一个公共结点.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n输入两个链表,找出它们的第一个公共结点。\n\n'''\n\n\n# -*- coding:utf-8 -*-\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\nclass Solution:\n def FindFirstCommonNode(self, pHead1, pHead2):\n # write code here\n if not pHead1 or not pHead2:return None\n p1,p2 = pHead1,pHead2\n while p1 != p2:\n p1 = pHead2 if not p1 else p1.next\n p2 = pHead1 if not p2 else p2.next\n return p1\n" }, { "alpha_fraction": 0.4886363744735718, "alphanum_fraction": 0.49715909361839294, "avg_line_length": 19.705883026123047, "blob_id": "e861c599a845eaa92a963d81f8990da13d69d7b2", "content_id": "72dfd82c073483f5b941c5dabd9737b3cadfc40c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 816, "license_type": "no_license", "max_line_length": 48, "num_lines": 34, "path": "/Python/从尾到头打印链表.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。\n\n\n'''\n\n# -*- coding:utf-8 -*-\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # 返回从尾部到头部的列表值序列,例如[1,2,3]\n def printListFromTailToHead(self, listNode):\n # write code here\n # 简单版本\n #res = []\n #while listNode:\n # res.append(listNode.val)\n # listNode = listNode.next\n #return res[::-1]\n\n\n # 同时复习一下反转链表题目\n res = []\n pre = None\n while listNode:\n res.insert(0, listNode.val)\n cur = listNode\n listNode = listNode.next\n cur.next = pre\n pre = cur\n return res\n" }, { "alpha_fraction": 0.5482406616210938, "alphanum_fraction": 0.561861515045166, "avg_line_length": 30.464284896850586, "blob_id": "987d098a5f5e5df3c54a0ac7fc08144ea5122a36", "content_id": "499b7d663a9faf40b876f49711b428c5f0492cf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1031, "license_type": "no_license", "max_line_length": 72, "num_lines": 28, "path": "/Python/对称的二叉树.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。\n'''\n\n\nclass Solution:\n def isSymmetrical(self, pRoot):\n # write code here\n #def judge(l ,r):\n # if not l and not r : return True\n # if l and r and l.val == r.val:\n # return judge(l.left,r.right) and judge(l.right, r.left)\n # return False\n #\n #if not pRoot : return True\n #return judge(pRoot.left, pRoot.right)\n\n # 递归调用函数会有额外的开销,循环求解如下\n if not pRoot:return True\n stack = [pRoot.left, pRoot.right]\n while stack:\n node1 , node2 = stack.pop(), stack.pop()\n if not node1 and not node2 : continue\n if not node1 or not node2 : return False\n if node1.val != node2.val : return False\n stack += [node1.left,node2.right, node1.right, node2.left]\n return True\n" }, { "alpha_fraction": 0.41786283254623413, "alphanum_fraction": 0.45933014154434204, "avg_line_length": 24.079999923706055, "blob_id": "8b25701a3a88e458c8a9e9f38191f10663b306ab", "content_id": "065640054a4af269c9e7a29a63e3d16e40f8c783", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 789, "license_type": "no_license", "max_line_length": 105, "num_lines": 25, "path": "/Python/数组中出现次数超过一半的数字.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def MoreThanHalfNum_Solution(self, numbers):\n if not numbers: return None\n key, num = numbers[0], 1\n for i in numbers[1:]:\n if i == key:\n num += 1\n else:\n num -= 1\n if num == 0:\n key = i\n num = 1\n num = 0\n for i in numbers:\n if i == key:\n num += 1\n return key if num * 2 > len(numbers) else 0\n" }, { "alpha_fraction": 0.5178571343421936, "alphanum_fraction": 0.5476190447807312, "avg_line_length": 26.243244171142578, "blob_id": "c0d22d13dda27acc07535df10aa27f22e25a2897", "content_id": "de87acf338fe34e890ca1da9e944e2229ecd6da8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1202, "license_type": "no_license", "max_line_length": 57, "num_lines": 37, "path": "/Python/合并两个排序的链表.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。\n\n'''\n\n\n# -*- coding:utf-8 -*-\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\nclass Solution:\n # 返回合并后列表\n def Merge(self, pHead1, pHead2):\n # write code here\n # 递归解法只需要一个新头结点,但注意特殊情况空链表\n if not pHead1: return pHead2\n if not pHead2: return pHead1\n head = ListNode(None)\n if pHead1.val <= pHead2.val:\n pHead1.next = self.Merge(pHead1.next, pHead2)\n return pHead1\n else:\n pHead2.next = self.Merge(pHead1, pHead2.next)\n return pHead2\n\n\n # 循环的解法需要两个新头结点,并注意拼接尾链\n #res = cur = ListNode(None)\n #while pHead1 and pHead2:\n # if pHead1.val <= pHead2.val:\n # cur.next, pHead1 = pHead1, pHead1.next\n # else:\n # cur.next, pHead2 = pHead2, pHead2.next\n # cur = cur.next\n #cur.next = pHead1 if pHead1 else pHead2\n #return res.next\n" }, { "alpha_fraction": 0.5463821887969971, "alphanum_fraction": 0.5482375025749207, "avg_line_length": 23.5, "blob_id": "511e5f2b884db8855f37255649248980b92cd826", "content_id": "3de13b66098e3364c7a508e43eb9bdce66162f26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1408, "license_type": "no_license", "max_line_length": 107, "num_lines": 44, "path": "/Python/复杂链表的复制.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)\n\n\n'''\n\n\n# -*- coding:utf-8 -*-\n# class RandomListNode:\n# def __init__(self, x):\n# self.label = x\n# self.next = None\n# self.random = None\nclass Solution:\n # 返回 RandomListNode\n def Clone(self, pHead):\n # write code here\n\n if not pHead: return None\n\n # 将新结点复制出来,插进原链表\n tmp = pHead\n while tmp:\n node = RandomListNode(tmp.label)\n node.next = tmp.next\n tmp.next, tmp = node , node.next\n\n # 复制随机指针\n tmp = pHead\n while tmp:\n if tmp.random:\n tmp.next.random = tmp.random.next\n tmp = tmp.next.next\n\n # 拆分两个链表(注意边界条件,插入后的链表一个为偶数,原链表结点为空的时候就可以停止)\n res = new_head = RandomListNode(0)\n origin = pHead\n while origin:\n new_head.next = origin.next\n new_head = new_head.next\n origin.next = new_head.next\n origin = origin.next\n return res.next\n" }, { "alpha_fraction": 0.4662998616695404, "alphanum_fraction": 0.4828060567378998, "avg_line_length": 24.964284896850586, "blob_id": "0b987b242d47248a3b54ddf3d3a88e888367c903", "content_id": "583252c19fa7cc0178ee007dca3e34031cf78955", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 885, "license_type": "no_license", "max_line_length": 86, "num_lines": 28, "path": "/Python/删除链表中重复的结点.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5\n\n'''\n\n\n# -*- coding:utf-8 -*-\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\nclass Solution:\n def deleteDuplication(self, pHead):\n # write code here\n\n # 注意所有节点都一样的情况,如何删除最后一个结点\n res = pre = ListNode(-1)\n res.next = tmp = pHead\n while tmp:\n if tmp.next and tmp.val == tmp.next.val:\n cur = tmp.next\n while cur and cur.val == tmp.val:\n cur = cur.next\n pre.next, tmp = cur, cur\n else:\n pre = tmp\n tmp = tmp.next\n return res.next\n" }, { "alpha_fraction": 0.5478690266609192, "alphanum_fraction": 0.5509573817253113, "avg_line_length": 25.112903594970703, "blob_id": "84b8911f95b3d6a22bbbb4b6a4ace4b4f17f741c", "content_id": "6718e1d52163a237bbf7494993009a42bdbac04a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1701, "license_type": "no_license", "max_line_length": 114, "num_lines": 62, "path": "/Python/序列化二叉树.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n请实现两个函数,分别用来序列化和反序列化二叉树\n'''\n\n\n\n# 前序遍历 + 分治递归\n\n# 第一种实现\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution:\n def Serialize(self, root):\n # write code here\n if not root: return \"$\"\n return str(root.val) + \",\" + self.Serialize(root.left) + \",\" + self.Serialize(root.right)\n\n def Deserialize(self, s):\n root, index = self.deserialize(s.split(\",\"), 0)\n return root\n\n def deserialize(self,s,index):\n if s[index]=='$':\n return None,index+1\n root=TreeNode(int(s[index]))\n index += 1\n root.left, index = self.deserialize(s, index)\n root.right, index = self.deserialize(s, index)\n return root, index\n\n\n# 第二种实现\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Codec:\n def serialize(self, root):\n return str(root.val) + \",\" + self.serialize(root.left) + ',' + self.serialize(root.right) if root else \"$\"\n\n def deserialize(self, data):\n self.index = -1\n data = data.split(',')\n def dfs(data):\n self.index += 1\n if data[self.index] == '$':\n return None\n root = TreeNode(int(data[self.index]))\n root.left = dfs(data)\n root.right = dfs(data)\n return root\n return dfs(data)\n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.deserialize(codec.serialize(root))\n" }, { "alpha_fraction": 0.5097402334213257, "alphanum_fraction": 0.548701286315918, "avg_line_length": 18.25, "blob_id": "1fd5a2350b5a8f2b640a1e2739a2a3ff4b8f609c", "content_id": "56a7c95d12a57e19677e1a8de8edd227e9fb83f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 64, "num_lines": 16, "path": "/Python/矩形覆盖.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?\n\n'''\n\n\n\nclass Solution:\n def rectCover(self, number):\n number <= 0: return 0\n a, b = 1,2\n while number > 2:\n a, b = b, a+b\n number -= 1\n return b if number != 1 else a# write code here\n" }, { "alpha_fraction": 0.4465493857860565, "alphanum_fraction": 0.4749661684036255, "avg_line_length": 25.39285659790039, "blob_id": "fe26cdcd770975c2e0558e732114c89ed5fd43d7", "content_id": "ab815af297a68ce382f2394ddc87d1d39e0c90fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 881, "license_type": "no_license", "max_line_length": 106, "num_lines": 28, "path": "/Python/把字符串转换成整数.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。\n\n'''\n\n\n# -*- coding:utf-8 -*-\nimport re\nclass Solution:\n def StrToInt(self, s):\n INT_MAX, INT_MIN = 2 ** 31, -2 ** 31 - 1\n all_str = list(map(str, range(10)))\n tmp = s.strip()\n if not tmp: return 0\n flag = False\n res = 0\n for i in tmp:\n if i == '-': flag = True\n if i in all_str:\n if res != 0:\n res *= 10\n res += all_str.index(i)\n elif i != '+' and i != '-':\n return 0\n if flag:\n return -res if -res > INT_MIN else 0\n return res if res < INT_MAX else 0\n" }, { "alpha_fraction": 0.45011085271835327, "alphanum_fraction": 0.48337027430534363, "avg_line_length": 25.52941131591797, "blob_id": "45b942b11bc51e54fc8b4715566ea204952c92c0", "content_id": "00cc6460b18ab1925c91a8a85d66c7aca5b28d7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 68, "num_lines": 17, "path": "/Python/跳台阶.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nclass Solution:\n def jumpFloor(self, number):\n # write code here\n # 迭代法\n if number == 1: return 1\n if number == 2: return 2\n a,b = 1,2\n while number > 2:\n a,b = b,a+b\n number -= 1\n return b\n\n # 递归法 时间开销过大,栈溢出\n # if number == 1: return 1\n # if number == 2: return 2\n # return self.jumpFloor(number-1) + self.jumpFloor(number-2)\n" }, { "alpha_fraction": 0.4127516746520996, "alphanum_fraction": 0.42617449164390564, "avg_line_length": 24.913043975830078, "blob_id": "37a475be2f88198e990123a22d6a924b9c160b84", "content_id": "8a38ac71014e7f92d27e0b2d8b63e40094fe10e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 49, "num_lines": 23, "path": "/Python/二维数组中的查找.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nclass Solution:\n # array 二维列表\n def Find(self, target, array):\n # write code here\n\n # Approach one\n # return any(target in n for n in array)\n\n\n # Approach two\n if array == ([] or [[]]) : return False\n col , row = len(array[0]) , len(array)\n r, c = row - 1 ,0\n while 0 <= c < col and 0 <= r < row :\n print(r,c )\n if array[r][c] < target:\n c += 1\n elif array[r][c] > target:\n r -= 1\n else:\n return True\n return False\n" }, { "alpha_fraction": 0.5503355860710144, "alphanum_fraction": 0.5819750428199768, "avg_line_length": 33.766666412353516, "blob_id": "207e539b31dc7e57f73d34fb39ca3b223be6bd86", "content_id": "687b2b27bb0f19db2641f28a79dd289bc62b54ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1633, "license_type": "no_license", "max_line_length": 337, "num_lines": 30, "path": "/Python/扑克牌顺子.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\nLL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子.....LL不高兴了,他想了想,决定大\\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。\n\n\n'''\n\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def IsContinuous(self, numbers):\n # 数组中有非零重复一定不是顺子\n # 其余情况,统计零的个数,将其与其余各数的间隔(相差一相当于没有间隔)比较,如果零的个数更多则是顺子;反之不是\n if not numbers: return False\n numbers = sorted(numbers)\n key = numbers.count(0)\n numbers = numbers[key:]\n length = len(numbers) - 1\n while key >= 0 and length:\n value = numbers[length] - numbers[length - 1]\n if value == 0:\n return False\n elif value > 1:\n if value - 1 > key:\n return False\n else:\n key = (value - 1) - key\n length -= 1\n return True\n" }, { "alpha_fraction": 0.446494460105896, "alphanum_fraction": 0.4584870934486389, "avg_line_length": 24.595237731933594, "blob_id": "29f7f11fd181697958b2b045ba3290e0b7624738", "content_id": "e316b16431c46b26610b9b500ee15b10bc30fc9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1202, "license_type": "no_license", "max_line_length": 71, "num_lines": 42, "path": "/Python/二叉搜索树的第k个结点.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。\n\n''''\n\n\n# -*- coding:utf-8 -*-\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution:\n # 返回对应节点TreeNode\n def KthNode(self, pRoot, k):\n\n # Approach one\n if not pRoot or k <= 0: return None\n def inorder(pRoot):\n if not pRoot: return []\n return inorder(pRoot.left) + [pRoot] + inorder(pRoot.right)\n res = inorder(pRoot)\n return res[k-1] if k <= len(res) else None\n\n\n\n # Approach two\n # if not root or k <= 0: return None\n # res , stack = [], []\n # while True:\n # while root:\n # stack.append(root)\n # root = root.left\n # if not stack:\n # if k > len(res):\n # return None\n # else:\n # return res[k-1]\n # node = stack.pop()\n # res.append(node)\n # if node.right: root = node.right\n \n" }, { "alpha_fraction": 0.4000000059604645, "alphanum_fraction": 0.41862744092941284, "avg_line_length": 30.875, "blob_id": "86eb527d9ecf663a3ccd8af29cddc06ee69fe3dd", "content_id": "bb9d5824aa2d93dc7f5a0cf1a745d18be21230b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1196, "license_type": "no_license", "max_line_length": 84, "num_lines": 32, "path": "/Python/调整数组顺序使奇数位于偶数前面.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def reOrderArray(self, array):\n # write code here\n #if len(array) < 2: return array\n #i = 0\n #while True:\n # if not (array[i] & 1):\n # for j in range(i + 1, len(array)):\n # if array[j] & 1:\n # key = j\n # break\n # elif j == len(array) -1:\n # return array\n # while key > i:\n # array[key], array[key - 1] = array[key - 1], array[key]\n # key -= 1\n # else:\n # i += 1\n\n # 简化版本\n if len(array) < 2: return array\n for i in range(len(array)):\n for j in range(len(array) - 1, i, -1):\n if array[j] & 1 and not (array[j - 1] & 1):\n array[j], array[j - 1] = array[j - 1], array[j]\n return array\n" }, { "alpha_fraction": 0.607798159122467, "alphanum_fraction": 0.6376146674156189, "avg_line_length": 26.25, "blob_id": "3525736e5bacc2e692924736f823fc59722388da", "content_id": "c3fdeb427e2d75ebea75030c3e8ae67d78fb8af2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "no_license", "max_line_length": 88, "num_lines": 16, "path": "/Python/把数组排成最小的数.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。\n\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def PrintMinNumber(self, numbers):\n # 由于整数的拼接很容易造成大数问题导致溢出,这里按照字符串拼接来处理。\n if not numbers: return \"\"\n compare = lambda a, b:int(str(a) + str(b)) - int(str(b) + str(a))\n min_string = sorted(numbers, cmp = compare)\n return ''.join(str(s) for s in min_string)\n" }, { "alpha_fraction": 0.43111109733581543, "alphanum_fraction": 0.4770370423793793, "avg_line_length": 24.961538314819336, "blob_id": "5a87fd295d43f7a29f3d1fb8514ed89c8bd5264b", "content_id": "8379b851e981cd6b142198352d9caa3a641ba4ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 939, "license_type": "no_license", "max_line_length": 83, "num_lines": 26, "path": "/Python/二进制中1的个数.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nclass Solution:\n def NumberOf1(self, n):\n # write code here\n # 复数的补码前面自动填充1\n # 方法一\n # return sum([(n>>i & 1) for i in range(0,32)])\n\n # 方法二\n # 标志位一路左移,做“与”操作\n #flag = 1\n #count = 0\n #for _ in range(32):\n # if flag & n: count += 1\n # flag = flag << 1\n #return count\n\n\n # python中 -4294967296 的二进制位 Ob0, 虽然一个负数在做了若干次“与”操作后,二进制为零,但是其十进制数是一个越来越小的负数\n # 因此在采用,“n与(n-1)做与操作恰好去掉n的最右位1”,这一性质时,终止条件不能以十进制来表示,否则是个死循环。\n # 方法三\n count = 0\n while n & 0xffffffff != 0:\n count += 1\n n = n & (n - 1)\n return count\n" }, { "alpha_fraction": 0.5180000066757202, "alphanum_fraction": 0.5320000052452087, "avg_line_length": 21.727272033691406, "blob_id": "39111f90b01f5c8bc3e40ca0abe9fd8b3dd6c931", "content_id": "e240dc1dd33b97a160ed2a9131afbc9e26f0aed5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 720, "license_type": "no_license", "max_line_length": 71, "num_lines": 22, "path": "/Python/求1+2+3+...+n.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "''''\n求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。\n'''\n# -*- coding:utf-8 -*-\nclass Solution:\n # 主要考察面试人的心态是否积极,这个题目本身意义不大,实际环境中不会涉及到\n # 想法一: 构造函数求解\n # 想法二: 虚函数求解\n # 想法三: 利用函数指针求解\n # 想法四: 利用模板类型求解\n\n def __init__(self):\n self.sum = 0\n def Sum_Solution(self, n):\n # write code here\n def qiusum(n):\n self.sum += n\n n -= 1\n return n>0 and self.Sum_Solution(n)\n\n qiusum(n)\n return self.sum\n" }, { "alpha_fraction": 0.5634920597076416, "alphanum_fraction": 0.5857142806053162, "avg_line_length": 51.5, "blob_id": "ba197cd9875fb040fe36d443abb6b29a6c5c9888", "content_id": "1cd2ee197e7b25b57c8f9b928a27c527fc8c8ea8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 128, "num_lines": 12, "path": "/Python/机器人的运动范围.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nclass Solution:\n def movingCount(self, threshold, rows, cols):\n # write code here\n if threshold < 0 or rows <= 0 or cols <= 0: return 0\n visited = [[1 for _ in range(cols)] for _ in range(rows)]\n return self.count(threshold, cols, rows, 0 ,0 ,visited)\n\n def count(self,threshold, cols, rows, i , j ,visited):\n if i >= rows or j >= cols or visited[i][j] == 0 or threshold < sum(map(int,str(i)+str(j))): return 0\n visited[i][j] = 0\n return 1 + self.count(threshold, cols, rows, i + 1 , j ,visited) + self.count(threshold, cols, rows, i , j + 1,visited)\n" }, { "alpha_fraction": 0.5190891027450562, "alphanum_fraction": 0.5291359424591064, "avg_line_length": 33.72093200683594, "blob_id": "2e2a286cfff1c3dece8141c7e5643ab0f2be799f", "content_id": "5bd58056e8b6e2dc7b55194c2e6f64b88e097b34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1955, "license_type": "no_license", "max_line_length": 141, "num_lines": 43, "path": "/Python/数据流中的中位数.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "''''\n\n如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。\n\n''''\n\n\n\n# -*- coding:utf-8 -*-\nfrom heapq import *\nclass Solution:\n # 用平衡的二叉搜索树或者最大最小堆实现, O(logn) 插入新数据 , O(1) 获取中位数\n\n def __init__ (self):\n self.maxheap = []\n self.minheap = []\n def Insert(self, num):\n if (len(self.maxheap)+len(self.minheap))&1: #总数为奇数插入最大堆\n if len(self.minheap)> 0:\n if num > self.minheap[0]:#大于最小堆里的元素\n heappush(self.minheap, num)#新数据插入最小堆\n heappush(self.maxheap, -self.minheap[0])#最小堆中的最小插入最大堆\n heappop(self.minheap)\n else:\n heappush(self.maxheap, -num)\n else:\n heappush(self.maxheap, -num)\n else: #总数为偶数 插入最小堆\n if len(self.maxheap)> 0: #小于最大堆里的元素\n if num < -self.maxheap[0]:\n heappush(self.maxheap, -num)#新数据插入最大堆\n heappush(self.minheap, -self.maxheap[0])#最大堆中的最大元素插入最小堆\n heappop(self.maxheap)\n else:\n heappush(self.minheap, num)\n else:\n heappush(self.minheap, num)\n def GetMedian(self,n=None):\n if (len(self.maxheap)+len(self.minheap))&1:\n mid = self.minheap[0]\n else:\n mid = (self.minheap[0]-self.maxheap[0])/2.0\n return mid\n" }, { "alpha_fraction": 0.4950248897075653, "alphanum_fraction": 0.5190712809562683, "avg_line_length": 43.66666793823242, "blob_id": "43139e32be96e097a16fb33717a8c234871efd37", "content_id": "6028c954607c9fba5acfbef9677b4baa6088e141", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1312, "license_type": "no_license", "max_line_length": 78, "num_lines": 27, "path": "/Python/矩阵中的路径.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nclass Solution:\n def hasPath(self, matrix, rows, cols, path):\n # write code here\n if len(matrix) < 1 or rows <= 0 or cols <= 0 or not path: return False\n # 对于python来说,set、list、dict都是可变对象,不能直接在上边操作防止重复遍历。\n # 但如果输入是string是不可变对象,可以直接在上面操作。\n for i in range(rows):\n for j in range(cols):\n if path[0] == matrix[i*cols+j]:\n if self.find(list(matrix), rows, cols, path[1:], i, j):\n return True\n return False\n\n def find(self, matrix, rows, cols, path, i, j):\n if not path: return True\n matrix[i*cols+j] ='0'\n if j + 1 < cols and matrix[i*cols+j+ 1] == path[0]:\n return self.find(matrix, rows, cols, path[1:], i, j + 1)\n elif j - 1 >= 0 and matrix[i*cols+j- 1] == path[0]:\n return self.find(matrix, rows, cols, path[1:], i, j - 1)\n elif i + 1 < rows and matrix[(i+1)*cols+j] == path[0]:\n return self.find(matrix, rows, cols, path[1:], i + 1, j)\n elif i - 1 >= 0 and matrix[(i-1)*cols+j] == path[0]:\n return self.find(matrix, rows, cols, path[1:], i - 1, j)\n else:\n return False\n" }, { "alpha_fraction": 0.43515849113464355, "alphanum_fraction": 0.48559078574180603, "avg_line_length": 25.69230842590332, "blob_id": "577e5c146005c1efaba4f1bd2aab0035bc06daca", "content_id": "041811228b478da94930a9e24c70e1c3b7f83bde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 940, "license_type": "no_license", "max_line_length": 172, "num_lines": 26, "path": "/Python/和为S的连续正数序列.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!\n\n'''\n\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def FindContinuousSequence(self, tsum):\n # write code here\n res = []\n l, r = 1, 2\n max_num = tsum // 2 + 1\n tsum = 2 * tsum\n while r <= max_num:\n key = (l + r) * (r - l + 1)\n if key == tsum:\n if r - l + 1 > 1: res.append([i for i in range(l, r + 1)])\n r += 1\n elif key < tsum:\n r += 1\n else:\n l += 1\n return res\n" }, { "alpha_fraction": 0.4247449040412903, "alphanum_fraction": 0.49234694242477417, "avg_line_length": 30.360000610351562, "blob_id": "5d5821ee6c8882cd82af54395e3afb7624879a38", "content_id": "ceac4e3f5c03a5610e6890a564b052112dd26071", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1074, "license_type": "no_license", "max_line_length": 157, "num_lines": 25, "path": "/Python/整数中1出现的次数(从1到n整数中1出现的次数).py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def NumberOf1Between1AndN_Solution(self, n):\n # write code here\n res = 0\n s = str(n)\n length = len(s)\n for idx, i in enumerate(s):\n place = length - idx # 当前位数(个位是1,十位是2……)\n pre = n // (10 ** place) # 当前位数的高位数字\n aft = n % (10 ** (place - 1)) # 当前位数的低位数字\n if i == '0':\n res += pre * 10 ** (place - 1)\n elif i == '1':\n res += pre * 10 ** (place - 1) + aft + 1\n else:\n res += (pre + 1) * 10 ** (place - 1)\n return res\n" }, { "alpha_fraction": 0.5414746403694153, "alphanum_fraction": 0.5887096524238586, "avg_line_length": 23.799999237060547, "blob_id": "e9101071649ebc4fc299befad8acacd30a69ff95", "content_id": "257b66c50b5fa6a36dd98e76cd0be220fc1f4630", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1090, "license_type": "no_license", "max_line_length": 43, "num_lines": 35, "path": "/Python/数值的整数次方.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "# 貌似简单的一道题,其实是一个大坑!考察边界条件思考是否全面。 O(n), O(1)\n# 0的0次方数学上没有任何意义,做除法的时候需要单独考虑。返回0或者1都可以接受。\ndef offer16(base, exponent):\n if exponent == 0: return 1\n if exponent == 1: return base\n if exponent < 0:\n exponent = -exponent\n base = 1 / base if base != 0 else 0\n res = base\n while exponent > 1:\n res *= base\n exponent -= 1\n return res\n\n\n# 根据奇数和偶数的乘方性质优化代码。 O(logn),O(1)\n# 彻底优化代码,位运算和位移运算比除法和取余运算更加高效。\ndef offer16_1(base, exponent):\n if exponent == 0: return 1\n if exponent == 1: return base\n if exponent < 0:\n exponent = -exponent\n base = 1 / base if base != 0 else 0\n flag = False\n if exponent & 1 == 1: flag = True\n res = base\n while exponent > 1:\n res *= res\n exponent = exponent >> 1\n return res * base if flag else res\n\n-----\n\nprint(offer16_1(-2, -9))\nprint(offer16_1(2, 0))\n" }, { "alpha_fraction": 0.4414941370487213, "alphanum_fraction": 0.4612961411476135, "avg_line_length": 36.03333282470703, "blob_id": "9504666c9e6695bcee86d18a2d53ae1957d125e0", "content_id": "82ee1de99cef4eeee3a6bb1c1797682d8a9c03ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2744, "license_type": "no_license", "max_line_length": 88, "num_lines": 60, "path": "/Python/最小的K个数.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def GetLeastNumbers_Solution(self, tinput, k):\n # 如果最小的k个数字不要求顺序输出,O(n),O(1) 但是要修改原数组\n # def partition(tinput, l, r):\n # key = tinput[l]\n # while l < r:\n # while l < r and key <= tinput[r]:\n # r -= 1\n # tinput[l] = tinput[r]\n # while l < r and key > tinput[l]:\n # l += 1\n # tinput[r] = tinput[l]\n # tinput[l] = key\n # return l\n #\n # if not tinput: return []\n # n = len(tinput)\n # if n < k or k <= 0: return list()\n # left, right = 0, n - 1\n # index = partition(tinput, left, right)\n # while index + 1 != k:\n # if index + 1 < k:\n # left = index + 1\n # else:\n # right = index - 1\n # index = partition(tinput, left, right)\n # return sorted(tinput[:k])\n\n # 不需要修改原数字,O(nlogk),O(1) ,当n非常大时,占用内存小,仅读入一个大小为k的堆。对增量式数据也很友好。\n def heapAjust(nums, start, end):\n temp = nums[start] # 记录较大的那个孩子下标\n child = 2 * start + 1\n while child <= end: # 比较左右孩子,记录较大的那个\n if child + 1 <= end and nums[child] < nums[child + 1]: # 如果右孩子比较大,下标往右移\n child += 1\n if temp >= nums[child]: # 如果根已经比左右孩子都大了,直接退出\n break\n nums[start] = nums[child] # 如果根小于某个孩子,将较大值提到根位置\n # nums[start], nums[child] = nums[child], nums[start]\n start = child # 接着比较被降下去是否符合要求,此时的根下标为原来被换上去的那个孩子下标\n child = child * 2 + 1 # 孩子下标也要下降一层\n nums[start] = temp # 最后将一开始的根值放入合适的位置(如果前面是交换,这句就不要)\n\n n = len(tinput)\n if not tinput: return []\n if k <= 0 or k > n: return []\n for i in range(int(k / 2) - 1, -1, -1): # 建立大顶堆\n heapAjust(tinput, i, k - 1)\n for i in range(k, n):\n if tinput[i] < tinput[0]:\n tinput[0], tinput[i] = tinput[i], tinput[0]\n heapAjust(tinput, 0, k - 1) # 调整前k个数\n return sorted(tinput[:k])\n" }, { "alpha_fraction": 0.31705591082572937, "alphanum_fraction": 0.3864118754863739, "avg_line_length": 29.434782028198242, "blob_id": "c1b2b9b0ea300650e234b12f04e2b01cdb24f3fa", "content_id": "196903a8cb0440d41091ddb9bc2f1a9ceb2bad4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1607, "license_type": "no_license", "max_line_length": 262, "num_lines": 46, "path": "/Python/滑动窗口的最大值.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。\n\n'''\n\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def maxInWindows(self, num, size):\n # Approach one O(n) ~ O(kn)\n # length = len(nums)\n # if k > length or k <= 0: return []\n # l , r = 0 , k-1\n # res = [max(nums[l:r+1])]\n # r += 1\n # while r < length:\n # if nums[r] >= res[-1]:\n # res.append(nums[r])\n # l += 1\n # r += 1\n # elif nums[l] == res[-1]:\n # l += 1\n # res.append(max(nums[l:r+1]))\n # r += 1\n # else:\n # res.append(res[-1])\n # l += 1\n # r += 1\n # return res\n\n\n\n # Approch two 一个双向队列 O(n) , O(1)\n res , tmp = [] , []\n if size > len(num) or size <= 0 : return []\n for i in range(len(num)):\n if len(tmp) > 0 and tmp[0] <= i - size:\n tmp.pop(0)\n while len(tmp) > 0 and num[tmp[-1]] <= num[i]:\n tmp.pop()\n tmp.append(i)\n if i >= size-1:\n res.append(num[tmp[0]])\n return res\n \n" }, { "alpha_fraction": 0.4749498963356018, "alphanum_fraction": 0.48496994376182556, "avg_line_length": 22.761905670166016, "blob_id": "eaf3d389c625588f616a2887fb4e2317862dbb18", "content_id": "ee04dc8261da72251752c9301a92fd674a068a61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 639, "license_type": "no_license", "max_line_length": 73, "num_lines": 21, "path": "/Python/和为S的两个数字.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的,且小的数字在前面。\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def FindNumbersWithSum(self, array, tsum):\n # write code here\n if not array: return []\n l , r = 0 , len(array) -1\n while l < r:\n if array[l] + array[r] == tsum:\n return [array[l],array[r]]\n elif array[l] + array[r] < tsum:\n l += 1\n else:\n r -= 1\n return []\n" }, { "alpha_fraction": 0.5293333530426025, "alphanum_fraction": 0.5479999780654907, "avg_line_length": 22.90322494506836, "blob_id": "a8abf74d6c2377fcec099aa25a4387b6600241b4", "content_id": "f6b10466ce0a0279f50e5253c61fec21734a3076", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1286, "license_type": "no_license", "max_line_length": 73, "num_lines": 31, "path": "/Python/数组中只出现一次的数字.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n # 返回[a,b] 其中ab是出现一次的两个数字\n def FindNumsAppearOnce(self, array):\n # 类比于 136 题,将两个只出现一次的数字分类分入两个组别,即可转化为我们的已知问题。\n # 关键在于如何区分两个只出现过一次的数字\n\n # 当一次遍历异或后得到的是两个只出现过一次的数字的异或值,因为他们不同,最终的key值中至少有一个1,且最高位一定是1。\n # 我们就可以根据最后key值的最高位是否是 1 ,将所有数字分成两组(两个单一的数字必然在不同组,其他出现两次的数字一定同组)。\n # 为了方便检测每个数字的特定位是否为1 , 可以将其右移到最低位,和1 进行与操作即可检测。\n\n if not array : return None\n key = 0\n for i in array:\n key ^= i\n num = len(bin(key)) - 3\n\n a,b = 0,0\n for i in array:\n if (i >> num) & 1:\n a ^= i\n else:\n b ^= i\n return [a,b]\n \n" }, { "alpha_fraction": 0.5284450054168701, "alphanum_fraction": 0.5625790357589722, "avg_line_length": 30.639999389648438, "blob_id": "8bc99d9fb19ff72581a34a4e4513556cc8b72a33", "content_id": "c5546ca5e03843290192fe30631cfcfa2b846b11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 975, "license_type": "no_license", "max_line_length": 118, "num_lines": 25, "path": "/Python/重建二叉树.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。\n\n\n'''\n\n\n# -*- coding:utf-8 -*-\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution:\n # 返回构造的TreeNode根节点\n def reConstructBinaryTree(self, pre, tin):\n # write code here\n if len(pre) == 0 or len(tin) == 0: return None\n if len(pre) == 1 or len(tin) == 1: return TreeNode(pre[0])\n root = TreeNode(pre[0])\n for i, n in enumerate(tin):\n if n == root.val:\n root.left = self.reConstructBinaryTree(pre[1:i + 1], tin[:i])\n root.right = self.reConstructBinaryTree(pre[i + 1:], tin[i + 1:])\n return root\n" }, { "alpha_fraction": 0.457446813583374, "alphanum_fraction": 0.4680851101875305, "avg_line_length": 30.33333396911621, "blob_id": "c2c5e8ee6aef9a97982ff613080185451a1430e0", "content_id": "5c3a169bb621d1f5be103f9e3dd767da7baafa22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 51, "num_lines": 15, "path": "/Python/旋转数组的最小数字.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nclass Solution:\n def minNumberInRotateArray(self, rotateArray):\n # write code here\n if rotateArray == []: return None\n l, r = 0, len(rotateArray) - 1\n while l < r:\n mid = (r + l) // 2\n if rotateArray[mid] > rotateArray[l]:\n l = mid\n elif rotateArray[mid] < rotateArray[l]:\n r = mid\n else:\n l += 1\n return rotateArray[l]\n" }, { "alpha_fraction": 0.4351939558982849, "alphanum_fraction": 0.4522232711315155, "avg_line_length": 29.200000762939453, "blob_id": "c764dffcf73e377fbeab0b1e3fe032ab8004b975", "content_id": "3f6a48c6ebcbfd2edb992331e21d261b5f5d29a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 74, "num_lines": 35, "path": "/Python/数字在排序数组中出现的次数.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n统计一个数字在排序数组中出现的次数。\n'''\n\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def GetNumberOfK(self, data, k):\n # 直观的想法从前到后的顺序遍历,但是算法题几乎不会将顺序查找作为考察要点……\n\n def getFirst(nums):\n start, end = 0, len(nums) - 1\n while start <= end:\n mid = (start + end) // 2\n if data[mid] >= k: # 注意前后两个二分查找条件不一致\n end = mid - 1\n else:\n start = mid + 1\n # 导致两个函数越界的指针不一致,应该返回的指针是非越界指针\n return start if start < len(nums) and nums[start] == k else -1\n def getLast(nums):\n start, end = 0, len(nums) - 1\n while start <= end:\n mid = (start + end) // 2\n if data[mid] <= k:\n start = mid + 1\n else:\n end = mid - 1\n return end if end < len(nums) and nums[end] == k else -1\n\n if not data: return 0\n first, last = getFirst(data), getLast(data)\n return last - first + 1 if first != -1 and last != -1 else 0\n" }, { "alpha_fraction": 0.5413153171539307, "alphanum_fraction": 0.5497470498085022, "avg_line_length": 26.809524536132812, "blob_id": "c74a3abfa206bcd04109bf0ac91daba736240a05", "content_id": "09d76f43de2b63fa75c2c22aea7c032816eb4fb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 779, "license_type": "no_license", "max_line_length": 106, "num_lines": 21, "path": "/Python/字符流中第一个不重复的字符.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符\"go\"时,第一个只出现一次的字符是\"g\"。当从该字符流中读出前六个字符“google\"时,第一个只出现一次的字符是\"l\"。\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n # 返回对应char\n def __init__(self):\n self.nums = []\n self.key_loc = 0\n self.dic = dict()\n def FirstAppearingOnce(self):\n for i in self.nums[self.key_loc:]:\n if self.dic.get(i) == 1:\n self.key_loc = self.nums.index(i)\n return i\n return '#'\n def Insert(self, char):\n self.nums.append(char)\n self.dic[char] = self.dic.get(char,0)+1\n \n" }, { "alpha_fraction": 0.40354329347610474, "alphanum_fraction": 0.44685038924217224, "avg_line_length": 28.882352828979492, "blob_id": "9d4926389e9cc99510e770aeda8b053fda4979eb", "content_id": "d5527d894536c5c712290b876c4e47b22d7fc002", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 562, "license_type": "no_license", "max_line_length": 101, "num_lines": 17, "path": "/Python/构建乘积数组.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def multiply(self, A):\n length = len(A)\n if not length: return []\n C, D = [1 for _ in range(length)], [1 for _ in range(length)]\n for i in range(1, length):\n C[i] = C[i - 1] * A[i - 1]\n for i in range(length - 2, -1, -1):\n D[i] = D[i + 1] * A[i + 1]\n return [i * j for i, j in zip(C, D)]\n" }, { "alpha_fraction": 0.553875207901001, "alphanum_fraction": 0.5633270144462585, "avg_line_length": 20.15999984741211, "blob_id": "0dd1e866fb9304d4f0ae5e50e396e992a0de3d4e", "content_id": "35f815abcdf0e71d6b6b9753129f208f0f811eb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 715, "license_type": "no_license", "max_line_length": 87, "num_lines": 25, "path": "/Python/字符串的排列.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n\n题目描述\n输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。\n\n输入描述:\n输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。\n\n\n'''\n\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def Permutation(self, ss):\n # write code here\n length = len(ss)\n if length == 0: return []\n if length == 1: return [ss]\n res = []\n for i in range(length):\n for j in self.Permutation(ss[:i]+ss[i+1:]):\n if ss[i] + j not in res : res.append(ss[i] + j)\n return res\n" }, { "alpha_fraction": 0.6115702390670776, "alphanum_fraction": 0.63445645570755, "avg_line_length": 29.25, "blob_id": "9bb2ac3293e51769abf713404cb05bdb2ffc98e9", "content_id": "670f533a27383fe1d3cf62e3ea9de3948d461ad0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2747, "license_type": "no_license", "max_line_length": 133, "num_lines": 52, "path": "/Python/第一个只出现一次的字符位置.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "''''\n在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).\n\n\n'''\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def offer50(s):\n # 注意时间与空间的平衡 O(n) O(1)\n dic = dict()\n for i in s:\n dic[i] = dic.get(i, 0) + 1\n for idx, n in enumerate(s):\n if dic.get(n, 0) == 1:\n return idx\n return -1\n\n \t# Approach two 因为候选的字符有限,可以从字符的角度循环,不需要辅助的存储空间,还能加速运算\n # res = [s.index(i) for i in string.ascii_lowercase if s.count(i) == 1 ]\n # return min(res) if res else -1\n\n# 相关题目1 : 输入两个字符串,从第一个字符串中删除在第二个字符串中出现过的所有字符。\n# 类似解决思路:将第二个字符串中出现的字符建立哈希表。再遍历第一个字符串中的每个字符,查询只需O(1)。总的时间复杂度O(n),空间复杂度O(1)\n\n# 相关题目2:删除一个字符串中出现的所有重复字符。\n# 类似解决思路:根据ASCII建立一个哈希表,默认所有为0。如果出现一次则改为1。遍历过程中每个字符都查询哈希表O(1)。总的时间复杂度O(n),空间复杂度O(1)\n\n# 相关题目3:如果两个字符串出现的字符类型以及其数量都完全一致,只是位置不一样,成为变位词。如何检测是否是变位词。\n# 类似解决思路:遍历第一个字符串建立哈希表统计出现的字符及其个数,再对第二个字符串进行遍历的时候出现相同字符就减一(前提哈希表中存在这个字符),如果最后哈希表中所有的字符数量都为0,则是变位数。\n\n# 进阶问题:找到一个字符流中第一个只出现一次的字符位置。\n# 相似解法:首先考虑如何存放字符流方便查找操作,这里选用哈希表。同样根据字符的读入逐渐建立。如果该字符不存在于哈希表,则value记录其位置;如果已存在,将其value改为-1。当字符流终止时,只需要遍历哈希表,找到其value值为正,且数值最小的value输出。\n\nclass Offer50_1:\n # 字符流中的第一个不重复的字符\n def __init__(self):\n self.nums = []\n self.key_loc = 0\n self.dic = dict()\n\n def FirstAppearingOnce(self):\n for i in self.nums[self.key_loc:]:\n if self.dic.get(i) == 1:\n self.key_loc = self.nums.index(i)\n return i\n return '#'\n\n def Insert(self, char):\n self.nums.append(char)\n self.dic[char] = self.dic.get(char, 0) + 1\n" }, { "alpha_fraction": 0.5046511888504028, "alphanum_fraction": 0.5069767236709595, "avg_line_length": 27.733333587646484, "blob_id": "2ce918bd5699d6b28e82fa5eba340a199cf2e4a6", "content_id": "c74969a57fb81b11d0e280d54d2e335386961783", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 55, "num_lines": 15, "path": "/Python/用两个栈实现队列.py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nclass Solution:\n def __init__(self):\n self.stack_A = []\n self.stack_B = []\n def push(self, node):\n # write code here\n self.stack_A.append(node)\n def pop(self):\n # return xx\n if self.stack_B: return self.stack_B.pop()\n else:\n while self.stack_A:\n self.stack_B.append(self.stack_A.pop())\n return self.stack_B.pop()" }, { "alpha_fraction": 0.5361794233322144, "alphanum_fraction": 0.5564399361610413, "avg_line_length": 30.409090042114258, "blob_id": "8af662d0f9585a29593b060c57eafa6842087f79", "content_id": "a7c1979461a97e8b85c2dece6e642a0dead576e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2224, "license_type": "no_license", "max_line_length": 285, "num_lines": 44, "path": "/Python/孩子们的游戏(圆圈中最后剩下的数).py", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "'''\n每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)\n\n'''\n\n\n# -*- coding:utf-8 -*-\n\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def LastRemaining_Solution(self, n, m):\n # 本题式著名的约瑟夫环问题\n\n # Approach one 动规求解\n # 第n次选中某个数字是建立在第n-1次选中某个数字的基础上。因此关键是找到递归公式。\n # 每次递归的起点是不一样的,要找到起点的规律(角标映射的规律)\n # 如果第1次删除第k个数字,那么下次的起点就是k+1,考虑k之间的数字会补在最后, 加入取余运算。因此可以有映射关系P(x)=(x-k-1)%n\n # 但是现在需要逆向的关系公式, 因此逆映射为 p^-1(x) = (x+k+)%n = (x+m)%n\n # 另外,当只有一个数字可选的时候,显然f(0) = 0, 这是动规边界条件。\n # if n <= 0 or m <= 0: return -1\n # res = 0\n # for i in range(2, n + 1):\n # res = (res + m) % i\n # return res\n\n # Approach two 环形链表求解\n if n <= 0 or m <= 0: return -1\n head = q = ListNode(0)\n for i in range(1, n):\n q.next = ListNode(i)\n q = q.next\n q.next = head\n\n while n > 1:\n for i in range(1, m):\n head = head.next\n head.val = head.next.val\n head.next = head.next.next\n n -= 1\n return head.val\n" }, { "alpha_fraction": 0.5979003310203552, "alphanum_fraction": 0.7005401849746704, "avg_line_length": 135.26388549804688, "blob_id": "c17466d5ccc250461fcceadcbf7c0dabf84dd8d0", "content_id": "90f3d27538c6f9f6f081a5d86cbb14cdc027b8f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12513, "license_type": "no_license", "max_line_length": 239, "num_lines": 72, "path": "/README.md", "repo_name": "zhaoqun05/Coding-Interviews", "src_encoding": "UTF-8", "text": "# [《剑指offer》牛客网刷题总结](https://www.nowcoder.com/ta/coding-interviews)\n\n点击题目可以跳转到牛客网上对应的AC提交记录,点击python可以跳转到库中存储的多种求解代码。\n\n| Title | Solution | Time | Space | Category |\n| --- | --- | --- | --- | --- |\n| [二维数组中的查找](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=42453621) | [Python](./Python/二维数组中的查找.py) | O(n) | O(1) | 数组 |\n| [替换空格](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=42460839) | [Python](./Python/替换空格.py) | O(n) | O(1) | 字符串 |\n| [从尾到头打印链表](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=47907823) | [Python](./Python/从尾到头打印链表.py) | O(n) | O(1) | 链表 |\n| [斐波那契数列](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=45227866) | [Python](./Python/斐波那契数列.py) | O(n) | O(1) | 循环》递归 |\n| [跳台阶](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=45230720) | [Python](./Python/跳台阶.py) | O(n) | O(1) | 循环》递归 |\n| [用两个栈实现队列](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=45235801) | [Python](./Python/用两个栈实现队列.py) | _ | _ | 栈、队列 |\n| [变态跳台阶](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=45235366) | [Python](./Python/变态跳台阶.py) | O(1) | O(1) | 循环 |\n| [旋转数组的最小数字](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=45236648) | [Python](./Python/旋转数组的最小数字.py) | O(logn) | O(1) | 查找 |\n| [二进制中1的个数](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=46075299) | [Python](./Python/二进制中1的个数.py) | O(n) | O(1) | 位运算 |\n| [重建二叉树](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48882118) | [Python](./Python/重建二叉树.py) | O(logn) | O(1) | 二叉树 |\n| [链表中倒数第k个结点](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=47803984) | [Python](./Python/链表中倒数第k个结点.py) | O(n) | O(1) | 链表,代码完整性 |\n| [矩形覆盖](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48958443) | [Python](./Python/矩形覆盖.py) | O(n) | O(1) | 动规 |\n| [反转链表](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=47806389) | [Python](./Python/反转链表.py) | O(n) | O(1) | 链表、代码完整性 |\n| [调整数组顺序使奇数位于偶数前面](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=47802170) | [Python](./Python/调整数组顺序使奇数位于偶数前面.py) | O(nlogn) | O(1) | 数组 |\n| [数值的整数次方](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=46083470) | [Python](./Python/数值的整数次方.py) | O(logn) | O(1) | 代码完整性 |\n| [合并两个排序的链表](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=47808433) \\\\\\ [进阶题目:合并k个有序链表](https://blog.csdn.net/huhehaotechangsha/article/details/90573890) | [Python](./Python/合并两个排序的链表.py) | O(n+m) | O(1) | 代码鲁棒性 |\n| [二叉树的镜像](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=47899162) | [Python](./Python/二叉树的镜像.py) | O(logn) | O(1) | 二叉树 |\n| [树的子结构](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=47831600) | [Python](./Python/树的子结构.py) | O(m)~O(n*m) | O(1) | 代码鲁棒性 |\n| [从上往下打印二叉树](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48153093) | [Python](./Python/从上往下打印二叉树.py) | O(n) | O(n) | 二叉树 |\n| [栈的压入、弹出序列](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48152705) | [Python](./Python/栈的压入、弹出序列.py) | O(n) | O(1)~O(n) | 栈 |\n| [包含min函数的栈](https://www.nowcoder.com/profile/4727991/codeBooks?problemId=3707) | [Python](./Python/包含min函数的栈.py) | O(1) | O(n) | 栈 |\n| [顺时针打印矩阵](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48149659) | [Python](./Python/顺时针打印矩阵.py) | O(n*m) | O(1) | 数组 |\n| [数组中出现次数超过一半的数字](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48765916) | [Python](./Python/数组中出现次数超过一半的数字.py) | O(2n) | O(1) | 数组 |\n| [二叉搜索树的后序遍历序列](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48194445) | [Python](./Python/二叉搜索树的后序遍历序列.py) | O(nlogn) | O(1) | 二叉树 |\n| [最小的K个数](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48784255) | [Python](./Python/最小的K个数.py) | O(n) | O(1) | 数组 |\n| [连续子数组的最大和](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48795341) | [Python](./Python/连续子数组的最大和.py) | O(n) | O(1) | 动规 |\n| [二叉树中和为某一值的路径](https://www.nowcoder.com/profile/4727991/codeBooks?problemId=3715) | [Python](./Python/二叉树中和为某一值的路径.py) | O(logn) | O(1) | 二叉树 |\n| [二叉树的深度](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48856625) | [Python](./Python/二叉树的深度.py) | O(logn) | O(1) | 二叉树 |\n| [第一个只出现一次的字符位置](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48824416) | [Python](./Python/第一个只出现一次的字符位置.py) | O(n) | O(1) | 字符串 |\n| [求1+2+3+...+n]() | [Python](./Python/求1+2+3+...+n.py) | O(n) | O(1) | 构造函数 |\n| [字符串的排列](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48511020) | [Python](./Python/字符串的排列.py) | O(n^2) | O(1) | 递归 |\n| [两个链表的第一个公共结点](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48301223) | [Python](./Python/两个链表的第一个公共结点.py) | O(n+m) | O(1) | 链表 |\n| [数字在排序数组中出现的次数](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48845221) | [Python](./Python/数字在排序数组中出现的次数.py) | O(logn) | O(1) | 二分 |\n| [复杂链表的复制](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48274777) | [Python](./Python/复杂链表的复制.py) | O(n) | O(1) | 链表 |\n| [数组中只出现一次的数字](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48874883) | [Python](./Python/数组中只出现一次的数字.py) | O(n) | O(1) | 位运算 |\n| [丑数](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48823768) | [Python](./Python/丑数.py) | O(n) | O(n) | 数学 |\n| [数组中重复的数字](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48987133) | [Python](./Python/数组中重复的数字.py) | O(n) | O(1) | 数组 |\n| [把数组排成最小的数](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48805812) | [Python](./Python/把数组排成最小的数.py) | O(nlogn) | O(1) | 数组 |\n| [和为S的两个数字](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48876217) | [Python](./Python/和为S的两个数字.py) | O(n) | O(1) | 双指针 |\n| [整数中1出现的次数(从1到n整数中1出现的次数)](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48800319) | [Python](./Python/整数中1出现的次数(从1到n整数中1出现的次数).py) | O(logn) | O(1) | 数学规律 |\n| [左旋转字符串](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48879336) | [Python](./Python/左旋转字符串.py) | O(n) | O(1) | 字符串 |\n| [平衡二叉树](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48857880) | [Python](./Python/平衡二叉树.py) | O(logn) | O(1) | 二叉树 |\n| [翻转单词顺序列](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48879115) | [Python](./Python/翻转单词顺序列.py) | O(n) | O(1) | 字符串 |\n| [二叉搜索树与双向链表](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48297086) | [Python](./Python/二叉搜索树与双向链表.py) | O(n) | O(1) | 二叉树、双向链表 |\n| [和为S的连续正数序列](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48877303) | [Python](./Python/和为S的连续正数序列.py) | O(n) | O(1) | 双指针 |\n| [不用加减乘除做加法](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48944904) | [Python](./Python/不用加减乘除做加法.py) | O(1) | O(1) | 位运算 |\n| [删除链表中重复的结点](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48280756) | [Python](./Python/删除链表中重复的结点.py) | O(n) | O(1) | 链表 |\n| [链表中环的入口结点](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=47805238) | [Python](./Python/链表中环的入口结点.py) | O(n) | O(1) | 链表 |\n| [数组中的逆序对](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48839900) | [Python](./Python/数组中的逆序对.py) | O(nlogn) | O(n) | 归并 |\n| [把字符串转换成整数]() | [Python](./Python/把字符串转换成整数.py) | O(n) | O(1) | 字符串 |\n| [对称的二叉树](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=47902100) | [Python](./Python/对称的二叉树.py) | O(logn) | O(1) | 二叉树 |\n| [扑克牌顺子](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48916316) | [Python](./Python/扑克牌顺子.py) | O(1) | O(1) | 数学规律 |\n| [孩子们的游戏(圆圈中最后剩下的数)](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48930061) | [Python](./Python/孩子们的游戏(圆圈中最后剩下的数).py) | O(n) | O(1) | 动规、环形链表 |\n| [二叉树的下一个结点](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=46016477) | [Python](./Python/二叉树的下一个结点.py) | O(n) | O(1) | 二叉树 |\n| [构建乘积数组](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48950978) | [Python](./Python/构建乘积数组.py) | O(n) | O(n) | 数组 |\n| [把二叉树打印成多行](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48153495) | [Python](./Python/把二叉树打印成多行.py) | O(n) | O(n) | 二叉树 |\n| [二叉搜索树的第k个结点](https://www.nowcoder.com/profile/4727991/codeBooks?problemId=3748) | [Python](./Python/二叉搜索树的第k个结点.py) | O(nlogn) | O(n) | 树 |\n| [按之字形顺序打印二叉树](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48155836) | [Python](./Python/按之字形顺序打印二叉树.py) | O(n) | O(n) | 二叉树 |\n| [字符流中第一个不重复的字符](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48968261) | [Python](./Python/字符流中第一个不重复的字符.py) | O(n) | O(1) | 字符串 |\n| [滑动窗口的最大值](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48881205) | [Python](./Python/滑动窗口的最大值.py) | O(n) | O(1) | 双向队列 |\n| [表示数值的字符串](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=46774923) | [Python](./Python/表示数值的字符串.py) | O(1) | O(1) | 正则表达式 |\n| [机器人的运动范围]() | [Python](./Python/机器人的运动范围.py) | O(n^2) | O(n^2) | 回溯法 |\n| [正则表达式匹配](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48997600) | [Python](./Python/正则表达式匹配.py) | O(n) | O(1) | 正则表达式 |\n| [矩阵中的路径]() | [Python](./Python/矩阵中的路径.py) | O(n^2) | O(1) | 回溯法 |\n| [序列化二叉树](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48504812) | [Python](./Python/序列化二叉树.py) | O(logn) | O(1) | 二叉树 |\n| [数据流中的中位数](https://www.nowcoder.com/profile/4727991/codeBookDetail?submissionId=48792471) | [Python](./Python/数据流中的中位数.py) | 插入O(logn) \\ 中位数O(1) | O(1) | 树、堆 |\n" } ]
46
whliu91/python_utils
https://github.com/whliu91/python_utils
fbc4076518294d9d089d4a57ddb2c49a432b408a
2c13a6effc90df858140e2f559021cc439ad062f
5ff86bda55e5ee35a199b1e0668c589ca8180572
refs/heads/master
2020-03-29T04:48:18.054222
2018-10-25T03:18:11
2018-10-25T03:18:11
149,549,228
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5024121403694153, "alphanum_fraction": 0.5058580040931702, "avg_line_length": 32.76744079589844, "blob_id": "52e60c3443e2ad1e6c25f812323f97ab61199a56", "content_id": "b7b7de35ce50b1dd78aff76d2b439c2c84a0a519", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1451, "license_type": "no_license", "max_line_length": 103, "num_lines": 43, "path": "/generate_property_for_each_ds.py", "repo_name": "whliu91/python_utils", "src_encoding": "UTF-8", "text": "import os\n\nPROJECT_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"datasource-properties\")\n\njson_template = ''' \"{data_set}\": {{\n \"spark_properties\": {{\n \"targetPartition\": \"src_date\",\n \"recordDelimiter\": \"\",\n \"fieldDelimiter\": \"\",\n \"readerOptions\": \"sep=;\",\n \"readerFormat\": \"csv\",\n \"cleanseChar\": \"\",\n \"srcFormats\": \"src_date=yyyyMMdd\",\n \"srcToTgtColMap\": \"\",\n \"errorThresholdPercent\": \"\",\n \"writeMode\": \"append\",\n \"fileBasedTagPattern\": \"{data_set}_(\\\\\\\\d{{8}}).*.csv$\",\n \"fileBasedTagColumns\": \"src_date\"\n }},\n \"oozie_properties\": {{\n \"source_files_pattern\": \"{data_set}_*.csv\"\n }},\n \"test_properties\":{{\n \"expected_rows\": \"10\"\n }}\n }},\n'''\n\nds_property_json = \"\"\n\nfor file in os.listdir(os.path.join(PROJECT_ROOT, \"src\\\\main\\\\sources\\\\headspin\\\\hive\")):\n if file.endswith(\".hql\"):\n ds_property = json_template.format(data_set=file[:-4])\n ds_property_json += ds_property\n\nvscode_dir = os.path.join(PROJECT_ROOT, \"..\", \".vscode\")\nif not os.path.exists(vscode_dir):\n os.makedirs(vscode_dir)\n\n# write to specific location\nf = open(os.path.join(vscode_dir, \"temp.json\"), 'w+')\nf.write(ds_property_json[:-2])\nf.close()" }, { "alpha_fraction": 0.5778923034667969, "alphanum_fraction": 0.5840015411376953, "avg_line_length": 29.45930290222168, "blob_id": "d9ee3cbe94a468f0a8409da3c6fbdc3984da124c", "content_id": "019ca797b33a602e2c58c882b14bc5d96ace1546", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5238, "license_type": "no_license", "max_line_length": 90, "num_lines": 172, "path": "/utils.py", "repo_name": "whliu91/python_utils", "src_encoding": "UTF-8", "text": "import os\nimport csv\nimport decimal\nimport re\nfrom shutil import copyfile\nfrom datetime import datetime\n\nSCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))\n\ndef transpose_list_of_list(mat):\n '''Transpose a list of list\n '''\n return map(list, zip(*mat))\n\n\ndef underscore_to_camelcase(val):\n '''Convert underscore based naming format to camel case based, with the first letter \n capitalised, with first char capitalised\n '''\n list_val = list(val)\n list_val[0] = list_val[0].upper()\n while '_' in list_val:\n ind = list_val.index('_')\n list_val[ind+1] = list_val[ind+1].upper()\n list_val[ind] = ''\n\n res = ''.join(list_val)\n return res\n\ndef is_number(s):\n '''decided whether a string is number\n '''\n try:\n float(s)\n return True\n except ValueError:\n pass\n \n try:\n import unicodedata\n unicodedata.numeric(s)\n return True\n except (TypeError, ValueError):\n pass\n \n return False\n\ndef read_csv_to_list(file_name):\n '''Read csv file to list of list\n '''\n with open(file_name, 'rU') as f:\n reader = csv.reader(f)\n data = list(list(rec) for rec in csv.reader(f, delimiter=','))\n \n return data\n\ndef write_list_to_csv(list_of_col, file_name):\n '''Write list of col to file as csv\n '''\n text = \"\"\n for item in list_of_col:\n line = ','.join(item)\n text += line + '\\n'\n \n text = text[:-1]\n \n f = open(file_name, 'w+')\n f.write(text)\n f.close()\n\n\ndef reduce_to_decimals(value, decimals=8):\n '''Reduce a float number to (default 8) decimals\n '''\n format_str = \"{{0:.{decimals}f}}\".format(decimals=decimals)\n return float(format_str.format(float(value)))\n\ndef scientific_to_normal(val, prec=8):\n '''\n Convert the given float to a string,\n without resorting to scientific notation\n '''\n ctx = decimal.Context()\n ctx.prec = prec\n d1 = ctx.create_decimal(repr(float(val)))\n return format(d1, 'f')\n\ndef get_list_of_fields_from_ddl(ddl):\n '''Get all column names as list from ddl\n depends on column names to be between `` and line separated\n '''\n lines = ddl.split(\"\\n\")\n results = []\n for line in lines:\n result = re.search('`(.*)`', line)\n if result:\n results.append(result.group(1))\n return results\n\ndef append_header_to_csv(csv_file, headers):\n '''Append header (in a list) to csv file\n '''\n with open(csv_file, newline='') as f:\n r = csv.reader(f)\n data = [line for line in r]\n with open(csv_file, 'w', newline='') as f:\n w = csv.writer(f)\n w.writerow(headers)\n w.writerows(data)\n\ndef append_to_file_name_in_folder_with_extensions(folder, extension, addon):\n '''\n something.csv to somethingaddon.csv\n '''\n for file in os.listdir(folder):\n if file.endswith(extension):\n newname = file.replace(extension, addon + extension)\n os.rename(os.path.join(folder, file), os.path.join(folder, newname))\n\ndef create_folder_in_folder_from_list(folder, folder_list):\n '''Create all folders in the list in the folder given\n '''\n for item in folder_list:\n full_path = os.path.join(folder, item)\n if not os.path.exists(full_path):\n os.makedirs(full_path)\n\ndef copy_file_from_list_to_corresponding_folder(src_dir, dst_dir, ext):\n '''Copy files from src dir to corresponding folder in dst_dir, by name\n /src_dir/something_123456.csv -> /dst_dir/something/something_123456.csv\n '''\n for file in os.listdir(src_dir):\n if file.endswith(ext):\n file_full_path = os.path.join(src_dir, file)\n for folder in os.listdir(dst_dir):\n if folder in file:\n copyfile(file_full_path, os.path.join(dst_dir, folder, file))\n\ndef add_date_to_csv_from_filename(src_dir):\n for folder in os.listdir(src_dir):\n regex_pattern = folder + \"_(\\d{8}).*.csv\"\n for file in os.listdir(os.path.join(src_dir, folder)):\n result = re.search(regex_pattern, file)\n src_date_raw = result.group(1)\n src_date = datetime.strptime(src_date_raw, \"%Y%m%d\")\n src_date_formatted = src_date.strftime(\"%Y-%m-%d\")\n file_full_path = os.path.join(src_dir, folder, file)\n csv_data = read_csv_to_list(file_full_path)\n if \"src_date\" not in csv_data[0]:\n count = 0\n for row in csv_data:\n if count == 0:\n row.append(\"src_date\")\n else:\n row.append(src_date_formatted)\n count += 1\n \n write_list_to_csv(csv_data, file_full_path)\n\n\ndef get_field_from_create_table_statement(stmt):\n '''Get fields from sql create table statement\n WIP: this is buggy: does not work if there is Decimal(xxx,xxx) within fields\n '''\n pattern = r'\\(((.|\\n)*?)\\)'\n fields = re.search(pattern, stmt).group(1)\n rows = [item.strip() for item in fields.replace(\"\\n\", \"\").replace(\"`\", \"\").split(',')]\n field_names = [row.split()[0] for row in rows]\n return field_names\n\nif __name__ == \"__main__\":\n pass" } ]
2
rusg77/allure-python
https://github.com/rusg77/allure-python
5170764feb030f63c472d1f11fa8ae6bb1ceda69
4cf375a335313df8a90fcabe5e7c5576bc4892db
77a5649c6fd65fa9a744fd71e2c40ed47efb6395
refs/heads/master
2021-01-16T21:31:54.909502
2014-06-11T09:45:51
2014-06-11T09:45:51
21,209,993
0
1
null
2014-06-25T16:17:43
2014-06-19T14:56:49
2015-10-15T12:03:41
Python
[ { "alpha_fraction": 0.550262987613678, "alphanum_fraction": 0.5559127330780029, "avg_line_length": 37.022220611572266, "blob_id": "3ea43e693fee544f15f934bbc1252dba1bb608a3", "content_id": "a94ac133db1d0ad559fcb34d0aed8744998afe48", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10266, "license_type": "permissive", "max_line_length": 80, "num_lines": 270, "path": "/allure/contrib/recordtype.py", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "#######################################################################\n# Similar to namedtuple, but supports default values and is writable.\n#\n# Copyright 2011-2013 True Blade Systems, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Notes:\n# See http://code.activestate.com/recipes/576555/ for a similar\n# concept.\n#\n# When moving to a newer version of unittest, check that the exceptions\n# being caught have the expected text in them.\n#\n# When moving to Python 3, change __iter__ to use format_map.\n#\n# When moving to Python 3, make keyword params to recordtype() be\n# keyword-only.\n########################################################################\n\n__all__ = ['recordtype', 'NO_DEFAULT']\n\nimport sys as _sys\nfrom keyword import iskeyword as _iskeyword\nfrom collections import Mapping as _Mapping\n\nNO_DEFAULT = object()\n\n\n# Keep track of fields, both with and without defaults.\nclass _Fields(object):\n def __init__(self, default):\n self.default = default\n self.with_defaults = [] # List of (field_name, default).\n self.without_defaults = [] # List of field_name.\n\n def add_with_default(self, field_name, default):\n if default is NO_DEFAULT:\n self.add_without_default(field_name)\n else:\n self.with_defaults.append((field_name, default))\n\n def add_without_default(self, field_name):\n if self.default is NO_DEFAULT:\n # No default. There can't be any defaults already specified.\n if self.with_defaults:\n raise ValueError('field {0} without a default follows fields '\n 'with defaults'.format(field_name))\n self.without_defaults.append(field_name)\n else:\n self.add_with_default(field_name, self.default)\n\n\n# Used for both the type name and field names. If is_type_name is\n# False, seen_names must be provided. Raise ValueError if the name is\n# bad.\ndef _check_name(name, is_type_name=False, seen_names=None):\n if len(name) == 0:\n raise ValueError('Type names and field names cannot be zero '\n 'length: {0!r}'.format(name))\n if not all(c.isalnum() or c == '_' for c in name):\n raise ValueError('Type names and field names can only contain '\n 'alphanumeric characters and underscores: '\n '{0!r}'.format(name))\n if _iskeyword(name):\n raise ValueError('Type names and field names cannot be a keyword: '\n '{0!r}'.format(name))\n if name[0].isdigit():\n raise ValueError('Type names and field names cannot start with a '\n 'number: {0!r}'.format(name))\n\n if not is_type_name:\n # these tests don't apply for the typename, just the fieldnames\n if name in seen_names:\n raise ValueError('Encountered duplicate field name: '\n '{0!r}'.format(name))\n\n if name.startswith('_'):\n raise ValueError('Field names cannot start with an underscore: '\n '{0!r}'.format(name))\n\n\n# Validate a field name. If it's a bad name, and if rename is True,\n# then return a 'sanitized' name. Raise ValueError if the name is bad.\ndef _check_field_name(name, seen_names, rename, idx):\n try:\n _check_name(name, seen_names=seen_names)\n except ValueError:\n if rename:\n return '_' + str(idx)\n else:\n raise\n\n seen_names.add(name)\n return name\n\n\ndef _default_name(field_name):\n # Can't just use _{0}_default, because then a field name '_0'\n # would give a default name of '__0_default'. Since it begins\n # with 2 underscores, the name gets mangled.\n return '_x_{0}_default'.format(field_name)\n\n\ndef recordtype(typename, field_names, default=NO_DEFAULT, rename=False,\n use_slots=True):\n # field_names must be a string or an iterable, consisting of fieldname\n # strings or 2-tuples. Each 2-tuple is of the form (fieldname,\n # default).\n\n fields = _Fields(default)\n\n _check_name(typename, is_type_name=True)\n\n if isinstance(field_names, basestring):\n # No per-field defaults. So it's like a namedtuple, but with\n # a possible default value.\n field_names = field_names.replace(',', ' ').split()\n\n # If field_names is a Mapping, change it to return the\n # (field_name, default) pairs, as if it were a list\n if isinstance(field_names, _Mapping):\n field_names = field_names.items()\n\n # Parse and validate the field names. Validation serves two\n # purposes: generating informative error messages and preventing\n # template injection attacks.\n\n # field_names is now an iterable. Walk through it,\n # sanitizing as needed, and add to fields.\n\n seen_names = set()\n for idx, field_name in enumerate(field_names):\n if isinstance(field_name, basestring):\n field_name = _check_field_name(field_name, seen_names, rename,\n idx)\n fields.add_without_default(field_name)\n else:\n try:\n if len(field_name) != 2:\n raise ValueError('field_name must be a 2-tuple: '\n '{0!r}'.format(field_name))\n except TypeError:\n # field_name doesn't have a __len__.\n raise ValueError('field_name must be a 2-tuple: '\n '{0!r}'.format(field_name))\n default = field_name[1]\n field_name = _check_field_name(field_name[0], seen_names, rename,\n idx)\n fields.add_with_default(field_name, default)\n\n all_field_names = fields.without_defaults + [name for name, default in\n fields.with_defaults]\n\n # Create and fill-in the class template.\n argtxt = ', '.join(all_field_names)\n quoted_argtxt = ', '.join(repr(name) for name in all_field_names)\n if len(all_field_names) == 1:\n # special case for a tuple of 1\n quoted_argtxt += ','\n initargs = ', '.join(fields.without_defaults +\n ['{0}={1}'.format(name, _default_name(name))\n for name, default in fields.with_defaults])\n reprtxt = ', '.join('{0}={{{0}!r}}'.format(f) for f in all_field_names)\n dicttxt = ', '.join('{0!r}:self.{0}'.format(f) for f in all_field_names)\n\n # These values change depending on whether or not we have any fields.\n if all_field_names:\n inittxt = '; '.join('self.{0}={0}'.format(f) for f in all_field_names)\n eqtxt = 'and ' + ' and '.join('self.{0}==other.{0}'.format(f)\n for f in all_field_names)\n itertxt = '; '.join('yield self.{0}'.format(f)\n for f in all_field_names)\n tupletxt = '(' + ', '.join('self.{0}'.format(f)\n for f in all_field_names) + ')'\n getstate = 'return ' + tupletxt\n setstate = tupletxt + ' = state'\n else:\n # No fields at all in this recordtype.\n inittxt = 'pass'\n eqtxt = ''\n itertxt = 'return iter([])'\n getstate = 'return ()'\n setstate = 'pass'\n\n if use_slots:\n slotstxt = '__slots__ = _fields'\n else:\n slotstxt = ''\n\n template = '''class {typename}(object):\n \"{typename}({argtxt})\"\n\n _fields = ({quoted_argtxt})\n {slotstxt}\n\n def __init__(self, {initargs}):\n {inittxt}\n\n def __len__(self):\n return {num_fields}\n\n def __iter__(self):\n {itertxt}\n\n def _asdict(self):\n return {{{dicttxt}}}\n\n def __repr__(self):\n return \"{typename}(\" + \"{reprtxt}\".format(**self._asdict()) + \")\"\n\n def __eq__(self, other):\n return isinstance(other, self.__class__) {eqtxt}\n\n def __ne__(self, other):\n return not self==other\n\n def __getstate__(self):\n {getstate}\n\n def __setstate__(self, state):\n {setstate}\\n'''.format(typename=typename,\n argtxt=argtxt,\n quoted_argtxt=quoted_argtxt,\n initargs=initargs,\n inittxt=inittxt,\n dicttxt=dicttxt,\n reprtxt=reprtxt,\n eqtxt=eqtxt,\n num_fields=len(all_field_names),\n itertxt=itertxt,\n getstate=getstate,\n setstate=setstate,\n slotstxt=slotstxt,\n )\n\n # Execute the template string in a temporary namespace.\n namespace = {}\n # Add the default values into the namespace.\n for name, default in fields.with_defaults:\n namespace[_default_name(name)] = default\n\n try:\n exec template in namespace\n except SyntaxError as e:\n raise SyntaxError(e.message + ':\\n' + template)\n\n # Find the class we created, set its _source attribute to the\n # template used to create it.\n cls = namespace[typename]\n cls._source = template\n\n # For pickling to work, the __module__ variable needs to be set to\n # the frame where the named tuple is created. Bypass this step in\n # enviroments where sys._getframe is not defined (Jython for\n # example).\n if hasattr(_sys, '_getframe') and _sys.platform != 'cli':\n cls.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')\n\n return cls\n" }, { "alpha_fraction": 0.634412944316864, "alphanum_fraction": 0.6360324025154114, "avg_line_length": 26.44444465637207, "blob_id": "b239c8ac52d31661eb1bcd328a1c2c6d4e1c6cf5", "content_id": "a9ef4d1bb595999b33dc0ed3727c541bd50c6405", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2470, "license_type": "permissive", "max_line_length": 102, "num_lines": 90, "path": "/tests/conftest.py", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "import os\nimport pytest\n\nfrom lxml import etree, objectify\n\nfrom hamcrest.core.helpers.wrap_matcher import wrap_matcher\nfrom hamcrest.core.base_matcher import BaseMatcher\nimport allure\n\npytest_plugins = [\"pytester\"]\n\n\[email protected]\ndef schema():\n \"\"\"\n Returns :py:class:`lxml.etree.XMLSchema` object configured with schema for reports\n \"\"\"\n path_to_schema = os.path.join(os.path.dirname(__file__), 'allure.xsd')\n return etree.XMLSchema(etree.parse(path_to_schema))\n\n\[email protected]\ndef reportdir(testdir):\n return testdir.tmpdir.join(\"my_report_dir\")\n\n\[email protected]\ndef reports_for(testdir, reportdir, schema):\n \"\"\"\n Fixture that takes a map of name-values, runs it with --alluredir,\n parses all the XML, validates them against ``schema`` and\n :returns list of :py:module:`lxml.objectify`-parsed reports\n \"\"\"\n def impl(body='', extra_run_args=[], extra_plugins=(), **kw):\n testdir.makeconftest(\"\"\"\n import sys\n\n # FIXME: THIS IS HOLY FUCKING SHIT, need to investigate why pytest adds this extra path\n EVIL = '/usr/share/pyshared'\n if EVIL in sys.path:\n sys.path.remove(EVIL)\n\n sys.path.insert(0, '%s')\n\n pytest_plugins = [%s]\n \"\"\" % (os.path.dirname(os.path.dirname(allure.__file__)),\n \", \".join(map(lambda p: \"'{0}'\".format(p), list(extra_plugins) + ['allure.adaptor']))))\n testdir.makepyfile(body, **kw)\n\n resultpath = str(reportdir)\n testdir.runpytest(\"--alluredir\", resultpath, *extra_run_args)\n\n files = [os.path.join(resultpath, f) for f in os.listdir(resultpath) if '-testsuite.xml' in f]\n\n [schema.assertValid(etree.parse(f)) for f in files]\n\n return [objectify.parse(f).getroot() for f in files]\n\n return impl\n\n\[email protected]\ndef report_for(reports_for):\n \"\"\"\n as ``reports_for``, but returns a single report\n \"\"\"\n def impl(*a, **kw):\n reports = reports_for(*a, **kw)\n\n assert len(reports) == 1\n\n return reports[0]\n return impl\n\n\nclass HasFloat(BaseMatcher):\n\n def __init__(self, str_matcher):\n self.str_matcher = str_matcher\n\n def _matches(self, item):\n return self.str_matcher.matches(float(item))\n\n def describe_to(self, description):\n description.append_text('an object with float ') \\\n .append_description_of(self.str_matcher)\n\n\ndef has_float(match):\n return HasFloat(wrap_matcher(match))\n" }, { "alpha_fraction": 0.6839622855186462, "alphanum_fraction": 0.6839622855186462, "avg_line_length": 18.978260040283203, "blob_id": "311397b9af28a6d187c13b7f770778b60c3ada1f", "content_id": "8441b98eb0b426823d3ee74e648f9f008ece8fd4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3360, "license_type": "permissive", "max_line_length": 141, "num_lines": 138, "path": "/README.rst", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "Allure-Pytest-Adaptor\n=====================\n\n.. image:: https://pypip.in/v/pytest-allure-adaptor/badge.png\n :alt: Release Status\n :target: https://pypi.python.org/pypi/pytest-allure-adaptor\n.. image:: https://pypip.in/d/pytest-allure-adaptor/badge.png\n :alt: Downloads\n :target: https://pypi.python.org/pypi/pytest-allure-adaptor\n\nПлагин для ``py.test`` который может генерировать отчеты в удобочитаемом виде для ``allure-report``\n\nUsage\n=====\n.. code:: python\n\n py.test --alluredir [path_to_report_dir]\n # WARNING [path_to_report_dir] will be purged at first run\n\n\nПлагин автоматически подключается к ``py.test`` через ``entry point``, если установлен.\n\nПодключение плагина в IDE:\n\n.. code:: python\n\n pytest_plugins = 'allure.pytest_plugin',\\\n\n\nAdvanced usage\n==============\n\nВ плагине есть возможность генерировать данные сверх того, что делает ``pytest``.\n\nAttachments\n===========\n\nДля того, чтобы сохранить что-нибудь в тесте:\n\n.. code:: python\n\n import allure\n\n def test_foo():\n allure.attach('my attach', 'Hello, World')\n\n\nSteps\n=====\n\nДля того, чтобы побить тест на шаги:\n\n.. code:: python\n\n import pytest\n\n def test_foo():\n with pytest.allure.step('step one'):\n # do stuff\n\n with pytest.allure.step('step two'):\n # do more stuff\n\n\nРаботает и как декоратор.\nПо умолчанию название степа - это имя декорируемого метода\n\n.. code:: python\n\n import pytest\n\n @pytest.allure.step\n def make_test_data_foo():\n # do stuff\n\n def test_foo():\n assert make_some_data_foo() is not None\n\n @pytest.allure.step('make_some_data_foo')\n def make_some_data_bar():\n # do another stuff\n\n def test_bar():\n assert make_some_data_bar() is not None\n\n\nПри необходимости использования step'ов в коде, который нужен и без pytest, вместо ``pytest.allure.step`` можно использовать ``allure.step``:\n\n.. code:: python\n\n import allure\n\n @allure.step('some operation')\n def do_operation():\n # do stuff\n\n\nДля фикстур поддержка несколько ограничена.\n\n\nSeverity\n========\n\nДля тестов, модулей и классов можно задавать приоритеты:\n\n.. code:: python\n\n import pytest\n\n @pytest.allure.severity(pytest.allure.severity_level.MINOR)\n def test_minor():\n assert False\n\n\n @pytest.allure.severity(pytest.allure.severity_level.CRITICAL)\n class TestBar:\n\n # will have CRITICAL priority\n def test_bar(self):\n pass\n\n # will have BLOCKER priority via a short-cut decorator\n @pytest.allure.BLOCKER\n def test_bar(self):\n pass\n\n\nЧтобы запустить тесты только определенных приоритетов:\n\n.. code:: rest\n\n py.test my_tests/ --allure_severities=critical,blocker\n\n\nExtention\n=========\n\nДля использования в других фреймворках выделен класс ``allure.common.AllureImpl``, облегчающий создание привязок." }, { "alpha_fraction": 0.7061224579811096, "alphanum_fraction": 0.7306122183799744, "avg_line_length": 19.41666603088379, "blob_id": "28a346fc857d3c15c4f0b50237e84edd67dd618b", "content_id": "4b7a5c1ec8744efc297489c2c2460658775c83b8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "permissive", "max_line_length": 84, "num_lines": 12, "path": "/allure/adaptor.py", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 23, 2014\n\n@author: pupssman\n'''\n\nimport warnings\n\nwarnings.warn('\"allure.adaptor\" is deprecated, use \"allure.pytest_plugin\" instead.')\n\n# impersonate the old ``adaptor``\nfrom allure.pytest_plugin import * # @UnusedWildImport\n" }, { "alpha_fraction": 0.6929637789726257, "alphanum_fraction": 0.6929637789726257, "avg_line_length": 23.6842098236084, "blob_id": "81eea8bd6b1b53453a31cf91ebfd3a28533ce66e", "content_id": "9f1e3db5c96453973a7f01c1a6deaab11a88475a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 469, "license_type": "permissive", "max_line_length": 85, "num_lines": 19, "path": "/tests/libs/util_fixture.py", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "import pytest\nimport allure\n\n\[email protected](scope='session')\ndef allure_test_fixture():\n '''\n This is a fixture used by test checking lazy initialization of steps context.\n It must be in a separate module, to be initialized before pytest configure stage.\n Don't move it to tests code.\n '''\n return allure_test_fixture_impl()\n\n\nclass allure_test_fixture_impl():\n\n @allure.step('allure_test_fixture_step')\n def test(self):\n print \"Hello\"\n" }, { "alpha_fraction": 0.8056871891021729, "alphanum_fraction": 0.8056871891021729, "avg_line_length": 29.14285659790039, "blob_id": "f46bf231d4cda1a19b94f4b9b4e27bc9decab8f4", "content_id": "61a90d69e685b7dc4c22deb8458953fcd4f3f338", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 211, "license_type": "permissive", "max_line_length": 65, "num_lines": 7, "path": "/allure/__init__.py", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "from allure.pytest_plugin import MASTER_HELPER\n\n\n# allow using allure.step decorator instead of pytest.allure.step\nstep = MASTER_HELPER.step\nattach = MASTER_HELPER.attach\nsingle_step = MASTER_HELPER.single_step\n" }, { "alpha_fraction": 0.6282781958580017, "alphanum_fraction": 0.637400209903717, "avg_line_length": 22.078947067260742, "blob_id": "37f8035fab5bab2a873223d20931b22a2eaf32a2", "content_id": "9d0a7e5663efb70b1ee6b5971ec33d2a7fa5d73c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 877, "license_type": "permissive", "max_line_length": 79, "num_lines": 38, "path": "/tests/test_common.py", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "\"\"\"\nTests for module ``common``\n\nCreated on Feb 23, 2014\n\n@author: pupssman\n\"\"\"\nfrom lxml import etree\nfrom allure.constants import Status\n\n\ndef test_module_is_importable():\n import allure.common # @UnusedImport\n\n\nclass TestCommonImpl:\n def test_class_exists(self):\n import allure.common as c\n\n assert c.AllureImpl\n\n def test_smoke(self, tmpdir, schema):\n \"\"\"\n Check that a very basic common workflow results in a valid XML produced\n \"\"\"\n import allure.common as c\n\n result_dir = tmpdir.mkdir('target')\n impl = c.AllureImpl(str(result_dir))\n\n impl.start_suite(name='A_suite')\n impl.start_case(name='A_case')\n impl.stop_case(status=Status.PASSED)\n impl.stop_suite()\n\n assert len(result_dir.listdir()) == 1\n\n schema.assertValid(etree.parse(str(result_dir.listdir()[0])))\n" }, { "alpha_fraction": 0.7567567825317383, "alphanum_fraction": 0.7567567825317383, "avg_line_length": 36, "blob_id": "67b8b00b12d2ac7e0334d1034643b3912e1be94b", "content_id": "2be8d0cc33fbdd01f70007c29a75392e881bd9be", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 111, "license_type": "permissive", "max_line_length": 102, "num_lines": 3, "path": "/allure/contrib/__init__.py", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "\"\"\"\nThis package holds various third-party stuff that we need here but dont want to install as a dependecy\n\"\"\"\n" }, { "alpha_fraction": 0.6109254956245422, "alphanum_fraction": 0.6241229772567749, "avg_line_length": 26.085973739624023, "blob_id": "8a718b397bcba8c8b3cac72f8562938fa6c1a776", "content_id": "ec5f843219446da3cc4b4d6316e139ffc2b81da7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5986, "license_type": "permissive", "max_line_length": 172, "num_lines": 221, "path": "/allure/utils.py", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "# encoding: utf-8\n\n'''\nThis module holds utils for the adaptor\n\nCreated on Oct 22, 2013\n\n@author: pupssman\n'''\n\nimport re\nimport sys\nimport time\nimport hashlib\nimport inspect\n\nfrom lxml import objectify\nfrom traceback import format_exception_only\n\nfrom _pytest.python import Module\n\nfrom allure.contrib.recordtype import recordtype\nfrom allure.constants import Severity\n\n\ndef element_maker(name, namespace):\n return getattr(objectify.ElementMaker(annotate=False, namespace=namespace,), name)\n\n\nclass Rule:\n _check = None\n\n def value(self, name, what):\n raise NotImplemented()\n\n def if_(self, check):\n self._check = check\n return self\n\n def check(self, what):\n if self._check:\n return self._check(what)\n else:\n return True\n\n\n# see http://en.wikipedia.org/wiki/Valid_characters_in_XML#Non-restricted_characters\n\n# We need to get the subset of the invalid unicode ranges according to\n# XML 1.0 which are valid in this python build. Hence we calculate\n# this dynamically instead of hardcoding it. The spec range of valid\n# chars is: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]\n# | [#x10000-#x10FFFF]\n_legal_chars = (0x09, 0x0A, 0x0d)\n_legal_ranges = (\n (0x20, 0x7E),\n (0x80, 0xD7FF),\n (0xE000, 0xFFFD),\n (0x10000, 0x10FFFF),\n)\n_legal_xml_re = [unicode(\"%s-%s\") % (unichr(low), unichr(high)) for (low, high) in _legal_ranges if low < sys.maxunicode]\n_legal_xml_re = [unichr(x) for x in _legal_chars] + _legal_xml_re\nillegal_xml_re = re.compile(unicode('[^%s]') % unicode('').join(_legal_xml_re))\n\n\ndef legalize_xml(arg):\n def repl(matchobj):\n i = ord(matchobj.group())\n if i <= 0xFF:\n return unicode('#x%02X') % i\n else:\n return unicode('#x%04X') % i\n return illegal_xml_re.sub(repl, arg)\n\n\nclass Element(Rule):\n def __init__(self, name='', namespace=''):\n self.name = name\n self.namespace = namespace\n\n def value(self, name, what):\n if not isinstance(what, basestring):\n return self.value(name, str(what))\n\n if not isinstance(what, unicode):\n try:\n what = unicode(what, 'utf-8')\n except UnicodeDecodeError:\n what = unicode(what, 'utf-8', errors='replace')\n\n return element_maker(self.name or name, self.namespace)(legalize_xml(what))\n\n\nclass Attribute(Rule):\n def value(self, name, what):\n return str(what)\n\n\nclass Nested(Rule):\n def value(self, name, what):\n return what.toxml()\n\n\nclass Many(Rule):\n def __init__(self, rule, name='', namespace=''):\n self.rule = rule\n self.name = name\n self.namespace = namespace\n\n def value(self, name, what):\n el = element_maker(self.name or name, self.namespace)\n\n return el(*[self.rule.value(name, x) for x in what])\n\n\ndef xmlfied(el_name, namespace='', fields=[], **kw):\n items = fields + kw.items()\n\n class MyImpl(recordtype('XMLFied', [(item[0], None) for item in items])):\n def toxml(self):\n el = element_maker(el_name, namespace)\n entries = lambda clazz: [(name, rule.value(name, getattr(self, name))) for (name, rule) in items if isinstance(rule, clazz) and rule.check(getattr(self, name))]\n\n elements = entries(Element)\n attributes = entries(Attribute)\n nested = entries(Nested)\n manys = sum([[(m[0], v) for v in m[1]] for m in entries(Many)], [])\n\n return el(*([element for (_, element) in elements + nested + manys]),\n **{name: attr for (name, attr) in attributes})\n\n return MyImpl\n\n\ndef parents_of(item):\n \"\"\"\n Returns list of parents (i.e. object.parent values) starting from the top one (Session)\n \"\"\"\n parents = [item]\n current = item\n\n while current.parent is not None:\n parents.append(current.parent)\n current = current.parent\n\n return parents[::-1]\n\n\ndef parent_module(item):\n return filter(lambda x: isinstance(x, Module), parents_of(item))[0]\n\n\ndef parent_down_from_module(item):\n parents = parents_of(item)\n return parents[parents.index(parent_module(item)) + 1:]\n\n\ndef sec2ms(sec):\n return int(round(sec * 1000.0))\n\n\ndef uid(name):\n \"\"\"\n Generates fancy UID uniquely for ``name`` by the means of hash function\n \"\"\"\n return hashlib.sha256(name).hexdigest()\n\n\ndef now():\n \"\"\"\n Return current time in the allure-way representation. No further conversion required.\n \"\"\"\n return sec2ms(time.time())\n\n\ndef severity_of(item):\n severity_marker = item.get_marker('allure_severity')\n if severity_marker:\n return severity_marker.args[0]\n else:\n return Severity.NORMAL\n\n\ndef all_of(enum):\n \"\"\"\n returns list of name-value pairs for ``enum`` from :py:mod:`allure.constants`\n \"\"\"\n return filter(lambda (n, v): not n.startswith('_'), inspect.getmembers(enum))\n\n\ndef unicodify(something):\n def convert(x):\n try:\n return unicode(x)\n except UnicodeDecodeError:\n return unicode(x, 'utf-8', errors='replace')\n\n try:\n return convert(something) # @UndefinedVariable\n except TypeError:\n try:\n return convert(str(something)) # @UndefinedVariable\n except UnicodeEncodeError:\n return convert('<nonpresentable %s>' % type(something)) # @UndefinedVariable\n\n\ndef present_exception(e):\n \"\"\"\n Try our best at presenting the exception in a readable form\n \"\"\"\n if not isinstance(e, SyntaxError):\n return unicodify('%s: %s' % (type(e).__name__, unicodify(e)))\n else:\n return unicodify(format_exception_only(e))\n\n\ndef get_exception_message(report):\n \"\"\"\n get exception message from pytest's internal ``report`` object\n \"\"\"\n return (getattr(report, 'exception', None) and present_exception(report.exception.value)) or (hasattr(report, 'result') and report.result) or report.outcome\n" }, { "alpha_fraction": 0.4736519753932953, "alphanum_fraction": 0.47732841968536377, "avg_line_length": 29.22222137451172, "blob_id": "b02bb6d6bcfe67abf2c4f90ca523b889a5bccfba", "content_id": "4bace60ecaadfdb14afbf13f08c784a4bd1febd4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1632, "license_type": "permissive", "max_line_length": 66, "num_lines": 54, "path": "/allure/structure.py", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "'''\nThis holds allure report xml structures\n\nCreated on Oct 23, 2013\n\n@author: pupssman\n'''\n\nfrom allure.utils import xmlfied, Attribute, Element, Many, Nested\nfrom allure.constants import ALLURE_NAMESPACE\n\n\nAttach = xmlfied('attachment',\n source=Attribute(),\n title=Attribute(),\n type=Attribute())\n\n\nFailure = xmlfied('failure',\n message=Element(),\n trace=Element('stack-trace'))\n\n\nTestCase = xmlfied('test-case',\n name=Element(),\n title=Element().if_(lambda x: x),\n description=Element().if_(lambda x: x),\n failure=Nested().if_(lambda x: x),\n steps=Many(Nested()),\n attachments=Many(Nested()),\n status=Attribute(),\n start=Attribute(),\n stop=Attribute(),\n severity=Attribute())\n\n\nTestSuite = xmlfied('test-suite',\n namespace=ALLURE_NAMESPACE,\n name=Element(),\n title=Element().if_(lambda x: x),\n description=Element().if_(lambda x: x),\n tests=Many(Nested(), name='test-cases'),\n start=Attribute(),\n stop=Attribute())\n\n\nTestStep = xmlfied('step',\n name=Element(),\n title=Element().if_(lambda x: x),\n attachments=Many(Nested()),\n steps=Many(Nested()),\n start=Attribute(),\n stop=Attribute(),\n status=Attribute())\n" }, { "alpha_fraction": 0.6013628840446472, "alphanum_fraction": 0.6115843057632446, "avg_line_length": 14.447368621826172, "blob_id": "18362d1e3ca9a4028938ff7cd1130592270dd377", "content_id": "be04beda2948a0fb61643fe49624a3168bda9a60", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 587, "license_type": "permissive", "max_line_length": 55, "num_lines": 38, "path": "/allure/constants.py", "repo_name": "rusg77/allure-python", "src_encoding": "UTF-8", "text": "'''\nVarious constants extracted from schema.\n\nCreated on Oct 15, 2013\n\n@author: pupssman\n'''\n\n\nclass Severity:\n BLOCKER = 'blocker'\n CRITICAL = 'critical'\n NORMAL = 'normal'\n MINOR = 'minor'\n TRIVIAL = 'trivial'\n\n\nclass Status:\n FAILED = 'failed'\n BROKEN = 'broken'\n PASSED = 'passed'\n SKIPPED = 'skipped'\n\n\nFAILED_STATUSES = [Status.FAILED, Status.BROKEN]\n\n\nclass AttachmentType:\n TEXT = \"txt\"\n HTML = \"html\"\n XML = \"xml\"\n PNG = \"png\"\n JPG = \"jpg\"\n JSON = \"json\"\n OTHER = \"other\"\n\n\nALLURE_NAMESPACE = \"urn:model.allure.qatools.yandex.ru\"\n" } ]
11
tdealmeidamarcondes2019/Machine_Learning-Apprentice_Chef
https://github.com/tdealmeidamarcondes2019/Machine_Learning-Apprentice_Chef
0ab452613cd0d45dcda50b7fcfe1956f8e2062c3
219d45d316a4e94d24cfbc430a712e2608ff50df
70b1afc00810b87901855e554331853cf464ff19
refs/heads/master
2022-08-09T00:34:44.320772
2020-05-02T04:16:39
2020-05-02T04:16:39
260,609,567
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4649507999420166, "alphanum_fraction": 0.46723470091819763, "avg_line_length": 41.954715728759766, "blob_id": "04ce541dcd2925d5e3b6ff7bb1911586623a4f9e", "content_id": "d6190c9bcceab9b75fe5a308fdaaaa314b57b5ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11384, "license_type": "no_license", "max_line_length": 113, "num_lines": 265, "path": "/A1_Model.py", "repo_name": "tdealmeidamarcondes2019/Machine_Learning-Apprentice_Chef", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Importing necessary packages: \nimport pandas as pd \nimport random as rand\nimport statsmodels.formula.api as smf \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nimport sklearn.linear_model\n\n\n# In[2]:\n\n\n# Extracting and reading file: \nfile = 'app_chef_model_version.xlsx'\napp_chef = pd.read_excel(file)\n\n\n# In[3]:\n\n\n# Preparing data for statsmodel: \n\n# Dropping revenue from the explanatory variable set:\napp_chef_explanatory = app_chef.drop(['revenue', 'share_revenue',\n 'out_revenue_hi','out_share_revenue_hi'], axis = 1)\n\n# Dropping also discrete variables: \napp_chef_explanatory = app_chef_explanatory.drop(['name','email','first_name','family_name',\n 'domain', 'domain_group', 'rating_category',\n 'cust_serv_status'],axis = 1)\n\n# Formatting explanatory variable for statsmodels:\nfor val in app_chef_explanatory:\n print(f\"app_chef['{val}'] +\")\n\n\n# In[4]:\n\n\n# Building statsmodel with all explanatory variables: \n\nlm_full = smf.ols(formula =\"\"\" app_chef['revenue']~\n app_chef['cross_sell'] +\n app_chef['total_meals'] +\n app_chef['unique_meals'] +\n app_chef['contact_cust_serv'] +\n app_chef['prod_cat_view'] +\n app_chef['avg_time_vis'] +\n app_chef['mob_number'] +\n app_chef['early_cancel'] +\n app_chef['late_cancel'] +\n app_chef['tastes_pref'] +\n app_chef['pc_logins'] +\n app_chef['mob_logins'] +\n app_chef['week_plan'] +\n app_chef['early_deliv'] +\n app_chef['late_deliv'] +\n app_chef['pack_lock'] +\n app_chef['ref_lock'] +\n app_chef['follow_rec_pct'] +\n app_chef['avg_prep_time'] +\n app_chef['larger_order'] +\n app_chef['master_classes'] +\n app_chef['med_meal_rate'] +\n app_chef['avg_clicks'] +\n app_chef['total_photos'] +\n app_chef['m_family_name'] +\n app_chef['avg_tckt_order'] +\n app_chef['avg_contact_cust_serv'] +\n app_chef['pct_late_deliv'] +\n app_chef['pct_early_deliv'] +\n app_chef['share_total_meals'] +\n app_chef['out_avg_time_hi'] +\n app_chef['out_avg_prep_lo'] +\n app_chef['out_avg_prep_hi'] +\n app_chef['out_total_meals_hi'] +\n app_chef['out_unique_meals_hi'] +\n app_chef['out_cont_cust_serv_lo'] +\n app_chef['out_cont_cust_serv_hi'] +\n app_chef['out_canc_bef_noon_hi'] +\n app_chef['out_late_deliv_hi'] +\n app_chef['out_larg_order_lo'] +\n app_chef['out_larg_order_hi'] +\n app_chef['out_avg_clicks_lo'] +\n app_chef['out_avg_clicks_hi'] +\n app_chef['out_total_photos_hi'] +\n app_chef['out_pct_late_deliv_hi'] +\n app_chef['out_pct_early_deliv_hi'] +\n app_chef['out_share_total_meals_hi'] +\n app_chef['thr_total_meals'] +\n app_chef['thr_unique_meals'] +\n app_chef['thr_contact_cust_serv'] +\n app_chef['thr_avg_time_vis'] +\n app_chef['thr_early_cancel'] +\n app_chef['thr_late_cancel'] +\n app_chef['thr_late_deliv'] +\n app_chef['thr_avg_prep_time'] +\n app_chef['thr_total_photos'] +\n app_chef['thr_avg_tckt_order'] +\n app_chef['thr_pct_late_deliv'] +\n app_chef['thr_pct_early_deliv'] +\n app_chef['Negative'] +\n app_chef['Neutral'] +\n app_chef['Positive'] +\n app_chef['business'] +\n app_chef['personal'] +\n app_chef['Satisfied'] +\n app_chef['Unhappy']\"\"\", \n data = app_chef)\n\n# Fitting the results:\nresults_full = lm_full.fit()\n\n# Printing summary:\nresults_full.summary()\n\n\n# In[5]:\n\n\n# Selecting explanatory variables and splitting dataset: \n\n# Dropping all insignificant variables:\napp_chef_data = app_chef_explanatory.drop(['tastes_pref','mob_logins','med_meal_rate','week_plan',\n 'mob_number','mob_number','pack_lock','ref_lock','pc_logins',\n 'prod_cat_view','early_cancel','late_cancel','early_deliv',\n 'follow_rec_pct','pct_early_deliv','avg_clicks','out_late_deliv_hi',\n 'out_larg_order_lo','out_larg_order_hi','out_avg_clicks_lo',\n 'out_avg_clicks_hi','out_total_photos_hi','thr_unique_meals',\n 'thr_early_cancel','thr_late_deliv','thr_avg_prep_time',\n 'thr_pct_early_deliv', 'out_pct_late_deliv_hi', \n 'out_pct_early_deliv_hi','share_total_meals'],\n axis = 1)\n\n# Selecting response variable:\napp_chef_target = app_chef.loc[:, 'revenue']\n\n\n# Splitting dataset:\nX_train, X_test, y_train, y_test = train_test_split(\n app_chef_data,\n app_chef_target,\n test_size = 0.25,\n random_state = 222)\n\n# Checking training set:\nprint(X_train.shape)\nprint(y_train.shape)\n\n# Checking testing set:\nprint(X_test.shape)\nprint(y_test.shape)\n\n# Selecting explanatory variables:\nx_variables = ['total_meals', 'unique_meals', 'contact_cust_serv', 'avg_time_vis','late_deliv','avg_prep_time',\n 'larger_order', 'master_classes','total_photos','thr_total_meals','thr_contact_cust_serv',\n 'thr_avg_time_vis','thr_late_cancel','thr_total_photos','Negative','Neutral','Positive',\n 'business','personal', 'avg_tckt_order','avg_contact_cust_serv',\n 'pct_late_deliv','thr_avg_tckt_order','thr_pct_late_deliv', 'Satisfied', 'Unhappy']\n\n# Creating loop to include variables in the model:\nfor val in x_variables:\n print(f\"app_chef_train['{val}'] +\")\n\n\n# In[6]:\n\n\n# Statsmodel: \n\n# Merging x and y train:\napp_chef_train = pd.concat([X_train, y_train], axis = 1)\n\n\n# Building the model with selected explanatory variables:\nlm_best = smf.ols(formula = \"\"\"revenue ~\n app_chef_train['total_meals'] +\n app_chef_train['unique_meals'] +\n app_chef_train['contact_cust_serv'] +\n app_chef_train['avg_time_vis'] +\n app_chef_train['late_deliv'] +\n app_chef_train['avg_prep_time'] +\n app_chef_train['larger_order'] +\n app_chef_train['master_classes'] +\n app_chef_train['total_photos'] +\n app_chef_train['thr_total_meals'] +\n app_chef_train['thr_contact_cust_serv'] +\n app_chef_train['thr_avg_time_vis'] +\n app_chef_train['thr_late_cancel'] +\n app_chef_train['thr_total_photos'] +\n app_chef_train['Negative'] +\n app_chef_train['Neutral'] +\n app_chef_train['Positive'] +\n app_chef_train['business'] +\n app_chef_train['personal'] +\n app_chef_train['avg_tckt_order'] +\n app_chef_train['avg_contact_cust_serv'] +\n app_chef_train['pct_late_deliv'] +\n app_chef_train['thr_avg_tckt_order'] +\n app_chef_train['thr_pct_late_deliv'] +\n app_chef_train['Satisfied'] +\n app_chef_train['Unhappy']\"\"\", \n data = app_chef_train)\n\n\n# Fitting model:\nresults = lm_best.fit()\n\n# Summarizing model:\nprint(results.summary())\n\n\n# In[7]:\n\n\n# Scikit-learn models: \n# Instantiating a model object considering all models:\nlr = LinearRegression()\nridge_model = sklearn.linear_model.Ridge()\nlasso_model = sklearn.linear_model.Lasso( )\n#ard_model = sklearn.linear_model.ARDRegression()\n\n# Fitting to the training data per model:\nlr_fit = lr.fit(X_train, y_train)\nridge_fit = ridge_model.fit(X_train, y_train)\nlasso_fit = lasso_model.fit(X_train,y_train)\n#ard_fit = ard_model.fit(X_train,y_train)\n\n# Predicting new data with test dataset:\nlr_pred = lr_fit.predict(X_test)\nridge_pred = ridge_fit.predict(X_test)\nlasso_pred = lasso_fit.predict(X_test)\n#ard_pred = ard_fit.predict(X_test)\n\n# Generating train and test score per model:\nlr_train_score = lr.score(X_train, y_train).round(4)\nlr_test_score = lr.score(X_test, y_test).round(4)\nridge_train_score = ridge_model.score(X_train, y_train).round(4)\nridge_test_score = ridge_model.score(X_test, y_test).round(4)\nlasso_train_score = lasso_model.score(X_train,y_train).round(4)\nlasso_test_score = lasso_model.score(X_test,y_test).round(4)\n#ard_train_score = ard_model.score(X_train,y_train).round(4)\n#ard_test_score = ard_model.score(X_test,y_test).round(4)\n\n# Comparing results per model:\n\nprint(f\"\"\"\nModel Train Score Test Score\n----- ----------- ----------\nOLS {lr_train_score} {lr_test_score}\nRidge {ridge_train_score} {ridge_test_score}\nLasso {lasso_train_score} {lasso_test_score}\"\"\" # move it down if including ard model \n#Bayesian ARD {ard_train_score} {ard_test_score}\n)\n\nprint(\"\"\"\nBayesian ARD model was removed from the analysis due the time it takes to run.\nAlthough, it is still on the code. By just removing the '#'s, it is possible \nto include it again.\"\"\")\n\n" }, { "alpha_fraction": 0.7912652492523193, "alphanum_fraction": 0.7976878881454468, "avg_line_length": 49.225807189941406, "blob_id": "2de68ab1af6d7f301ab9632d102dd939c8e07886", "content_id": "b22e438bb751029cca6e2ef0776c5d0534b41167", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1557, "license_type": "no_license", "max_line_length": 506, "num_lines": 31, "path": "/README.md", "repo_name": "tdealmeidamarcondes2019/Machine_Learning-Apprentice_Chef", "src_encoding": "UTF-8", "text": "## Machine-Learning | Apprentice-Chef\n\nThe objective of this analysis was to build a regression based analysis and a classification-based predictive model using Apprentice Chef database. \n\nApprentice Chef is an innovative company with a unique spin on cooking at home. Their targeted customer is the busy professional with little to no skills in the kitchen, but appreciate a good meal. \n\nThe first analysis (A1) is destined to better understand how much revenue to expect from each customer within their first year of orders.\n\nThe second analysis (A2) explores which variables impact most for the success of their cross-sell, Halfway There, a promotion where subscribers receive a half bottle with the meal every Wednesday. The objective here is to understand which customer will be more succeptible to purchase this promotion.\n\n<strong> A1: Regression based analysis </strong>\n\nFiles:\n\nA1_Analysis.ipynb \n\nA1_Model.py\n\nA1_Write_Up\n\n<strong> A2: Classification-based predictive model </strong>\n\nFiles:\n\nA2_Analysis.ipynb \n\nA2_Model.py\n\nA2_Write_Up\n\nIn both assignments, we have three different files. <strong> Analysis </strong> comprehend the exploratory process of handling the data to find the build the model and find the business insights. <strong> Model </strong> contains only the code needed to run the final model, giving the respective score. Lastly, <strong> Write_Up </strong> is where we summarized the analysis with the most impactful business insights that we were able to gather from the analysis, followed by an actionable recommendation.\n" }, { "alpha_fraction": 0.5209750533103943, "alphanum_fraction": 0.5305072665214539, "avg_line_length": 33.99412155151367, "blob_id": "9d0f2e1e0505d18009e4074ada13e6f1812c9f76", "content_id": "5e5fbddf5fbe59723f69961cc55063903cec5815", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 47628, "license_type": "no_license", "max_line_length": 122, "num_lines": 1361, "path": "/A2_Model.py", "repo_name": "tdealmeidamarcondes2019/Machine_Learning-Apprentice_Chef", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ***\n# ***\n# ***\n# \n# # Classification Predictive Model<br>\n# \n# ***\n# ***\n\n# ***\n# <h3> Feature Engineering </h3>\n\n# In[ ]:\n\n\n# Importing necessary packages: \nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport seaborn as sns \nimport random as rand\nimport statsmodels.formula.api as smf\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix \nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import export_graphviz\nfrom sklearn.externals.six import StringIO\nfrom IPython.display import Image\nimport pydotplus\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.ensemble import RandomForestClassifier \nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import make_scorer\n\n\n# In[ ]:\n\n\n# Reading external file: \nfile = 'Apprentice_Chef_Dataset.xlsx'\napp_chef = pd.read_excel(file)\n\n\n# In[ ]:\n\n\n# Changing column names: \n# Changing variable names\napp_chef = app_chef.rename(columns={'REVENUE' :'revenue',\n 'CROSS_SELL_SUCCESS' :'cross_sell',\n 'NAME' :'name',\n 'EMAIL' :'email',\n 'FIRST_NAME' :'first_name',\n 'FAMILY_NAME' :'family_name',\n 'TOTAL_MEALS_ORDERED' :'total_meals',\n 'UNIQUE_MEALS_PURCH' :'unique_meals',\n 'CONTACTS_W_CUSTOMER_SERVICE' :'contact_cust_serv',\n 'PRODUCT_CATEGORIES_VIEWED' :'prod_cat_view',\n 'AVG_TIME_PER_SITE_VISIT' :'avg_time_vis',\n 'MOBILE_NUMBER' :'mob_number',\n 'CANCELLATIONS_BEFORE_NOON' :'early_cancel',\n 'CANCELLATIONS_AFTER_NOON' :'late_cancel',\n 'TASTES_AND_PREFERENCES' :'tastes_pref',\n 'PC_LOGINS' :'pc_logins',\n 'MOBILE_LOGINS' :'mob_logins',\n 'WEEKLY_PLAN' :'week_plan',\n 'EARLY_DELIVERIES' :'early_deliv',\n 'LATE_DELIVERIES' :'late_deliv',\n 'PACKAGE_LOCKER' :'pack_lock',\n 'REFRIGERATED_LOCKER' :'ref_lock',\n 'FOLLOWED_RECOMMENDATIONS_PCT':'follow_rec_pct',\n 'AVG_PREP_VID_TIME' :'avg_prep_time',\n 'LARGEST_ORDER_SIZE' :'larger_order',\n 'MASTER_CLASSES_ATTENDED' :'master_classes',\n 'MEDIAN_MEAL_RATING' :'med_meal_rate',\n 'AVG_CLICKS_PER_VISIT' :'avg_clicks',\n 'TOTAL_PHOTOS_VIEWED' :'total_photos'})\n\n\n# In[ ]:\n\n\n# Filling missing values: \n# Creating loop:\nfor c in app_chef:\n if app_chef[c].isnull().astype(int).sum() > 0:\n app_chef['m_'+c] = app_chef[c].isnull().astype(int)\n\n# Imputing value\napp_chef['family_name'] = app_chef['family_name'].fillna('Unknown')\n\n\n# <strong> New variables </strong><br>\n\n# In[ ]:\n\n\n# Creating new variables (continuous): \n\n# Average ticket per order:\napp_chef['avg_tckt_order'] = app_chef['revenue']/app_chef['total_meals']\napp_chef['avg_tckt_order'] = app_chef['avg_tckt_order'].round(2)\n\n# Average contacts per order:\napp_chef['avg_contact_cust_serv'] = app_chef['contact_cust_serv']/app_chef['total_meals']\napp_chef['avg_contact_cust_serv'] = app_chef['avg_contact_cust_serv'].round(2)\n\n# Ratio of orders delivered late:\napp_chef['pct_late_deliv'] = app_chef['late_deliv']/app_chef['total_meals']\napp_chef['pct_late_deliv'] = app_chef['pct_late_deliv'].round(2)\n\n# Ratio of orders delivered early:\napp_chef['pct_early_deliv'] = app_chef['early_deliv']/app_chef['total_meals']\napp_chef['pct_early_deliv'] = app_chef['pct_early_deliv'].round(2)\n\n# Ratio of unique meals:\napp_chef['pct_unique_meals'] = app_chef['unique_meals']/app_chef['total_meals']\napp_chef['pct_unique_meals'] = app_chef['pct_unique_meals'].round(2)\n\n# Total logins:\napp_chef['total_logins'] = app_chef['mob_logins'] + app_chef['pc_logins']\n\n# Ratio of mobile login:\napp_chef['pct_mob_logins'] = app_chef['mob_logins']/app_chef['total_logins']\napp_chef['pct_mob_logins'] = app_chef['pct_mob_logins'].round(2)\n\n# Share of total revenue:\napp_chef['share_revenue'] = app_chef['revenue']/app_chef['revenue'].sum()\napp_chef['share_revenue'] = app_chef['share_revenue'].round(4)\n\n# Share of total meals:\napp_chef['share_total_meals'] = app_chef['total_meals']/app_chef['total_meals'].sum()\napp_chef['share_total_meals'] = app_chef['share_total_meals'].round(4)\n\n\n# In[ ]:\n\n\n# Creating new variables (categorical): \n\n## 1st: Email domain group\n\n# Creating empty list to fill it later\nemail_lst = []\n\n# Creating loop to split email address:\nfor index, col in app_chef.iterrows():\n split_email = app_chef.loc[index, 'email'].split(sep = '@')\n email_lst.append(split_email)\n\n# Filling list and converting into a dataframe:\nemail_df = pd.DataFrame(email_lst)\n\n# Changing column names:\nemail_df.columns = ['name','email']\n\n# Looping again to get only the name of the domain (removing '.com'):\nemail_lst_2 = []\nfor index, col in email_df.iterrows():\n split_email = email_df.loc[index, 'email'].split(sep = '.')\n email_lst_2.append(split_email)\n\n# Filling list, converting into a DataFrame and changing column names:\nemail_df_2 = pd.DataFrame(email_lst_2)\nemail_df_2.columns = ['domain','.com']\n\n# Including column in our main dataset:\napp_chef = pd.concat([app_chef, email_df_2['domain']],\n axis = 1)\n\n# Grouping email domain types:\npersonal_email_domains = ['gmail', 'protonmail','yahoo']\nbusiness_email_domains = ['amex','merck','mcdonalds','jnj','cocacola','apple',\n 'nike','ibm','ge','dupont','chevron','microsoft','travelers',\n 'unitedhealth','exxon','boeing','caterpillar','mmm','verizon','pg',\n 'disney','walmart','visa','pfizer','jpmorgan','cisco','goldmansacs',\n 'unitedtech','homedepot','intel']\njunk_email_domains = ['me','aol','hotmail','live','msn','passport']\n\n# Looping one more time to massively classify the domains:\nemail_group = []\nfor group in app_chef['domain']:\n if group in personal_email_domains:\n email_group.append('personal')\n \n elif group in business_email_domains:\n email_group.append('business')\n \n elif group in junk_email_domains:\n email_group.append('junk')\n \n else:\n print('Unknown')\n\n# Concatenating with our original DataFrame:\napp_chef['domain_group'] = pd.Series(email_group)\n\n## 2nd Rating category\n# Creating loop to define categories according to ratings\nrating_lst = []\n\nfor row,col in app_chef.iterrows():\n if app_chef.loc[row,'med_meal_rate'] <= 2:\n rating_lst.append('Negative')\n elif app_chef.loc[row,'med_meal_rate'] >= 4:\n rating_lst.append('Positive')\n else:\n rating_lst.append('Neutral')\n\n# Adding new variable to dataset\napp_chef['rating_category'] = pd.Series(rating_lst)\n\n\n## 3rd Followed recommendations category\n# Creating loop to define categories according to ratings\nfollow_lst = []\nfor row,col in app_chef.iterrows():\n if app_chef.loc[row,'follow_rec_pct'] <= 30:\n follow_lst.append('Rarely')\n elif app_chef.loc[row,'follow_rec_pct'] <= 70:\n follow_lst.append('Sometimes')\n else:\n follow_lst.append('Frequently')\n\n# Adding new variable to dataset\napp_chef['follow_rec_category'] = pd.Series(follow_lst)\n\n## 4th Critical customer (too many contacts on customer service):\napp_chef['cust_serv_status'] = 0\ngood_cust_serv = app_chef.loc[0:,'cust_serv_status'][app_chef['avg_contact_cust_serv'] <= 0.5]\napp_chef['cust_serv_status'].replace(to_replace = good_cust_serv,\n value = 'Satisfied',\n inplace = True)\n\nbad_cust_serv = app_chef.loc[0:,'cust_serv_status'][app_chef['avg_contact_cust_serv'] > 0.5]\n\napp_chef['cust_serv_status'].replace(to_replace = bad_cust_serv,\n value = 'Unhappy',\n inplace = True)\n\n\n# In[ ]:\n\n\n# Creating binary variable: \n# Negative ratings:\napp_chef['attended_master_class'] = 0\nrate_1 = app_chef.loc[0:,'attended_master_class'][app_chef['master_classes'] > 0]\n\napp_chef['attended_master_class'].replace(to_replace = rate_1,\n value = 1,\n inplace = True)\nrate_2 = app_chef.loc[0:,'attended_master_class'][app_chef['master_classes'] == 0]\n\napp_chef['attended_master_class'].replace(to_replace = rate_2,\n value = 0,\n inplace = True)\n\n\n# ***\n# <h3> Exploratory analysis </h3>\n\n# In[ ]:\n\n\n# Setting outlier thresholds: \n\n# Explanatory variables:\navg_time_hi = 250\navg_prep_lo = 70\navg_prep_hi = 280\ntotal_meals_hi = 250\nunique_meals_hi = 10\ncont_cust_serv_lo = 2.5\ncont_cust_serv_hi = 12.5\ncanc_bef_noon_hi = 6\nlate_deliv_hi = 10\nlarg_order_lo = 2\nlarg_order_hi = 8\navg_clicks_lo = 8\navg_clicks_hi = 18\ntotal_photos_hi = 500\navg_tckt_order_hi = 80\navg_contact_cust_serv_hi = 0.3\npct_late_deliv_hi = 0.3\npct_early_deliv_hi = 0.15\nshare_total_meals_hi = 0.0018\npct_unique_meals_hi = 0.3\n\n# Average visit time:\napp_chef['out_avg_time_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_avg_time_hi'][app_chef['avg_time_vis'] > avg_time_hi]\n\napp_chef['out_avg_time_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Average preparation time:\n## Low:\napp_chef['out_avg_prep_lo'] = 0\ncondition_hi = app_chef.loc[0:,'out_avg_prep_lo'][app_chef['avg_prep_time'] < avg_prep_lo]\n\napp_chef['out_avg_prep_lo'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n## High\napp_chef['out_avg_prep_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_avg_prep_hi'][app_chef['avg_prep_time'] > avg_prep_hi]\n\napp_chef['out_avg_prep_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Total Meals:\napp_chef['out_total_meals_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_total_meals_hi'][app_chef['total_meals'] > total_meals_hi]\n\napp_chef['out_total_meals_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Unique Meals:\napp_chef['out_unique_meals_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_unique_meals_hi'][app_chef['unique_meals'] > unique_meals_hi]\n\napp_chef['out_unique_meals_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Contact customer service:\n## High\napp_chef['out_cont_cust_serv_lo'] = 0\ncondition_hi = app_chef.loc[0:,'out_cont_cust_serv_lo'][app_chef['contact_cust_serv'] < cont_cust_serv_lo]\n\napp_chef['out_cont_cust_serv_lo'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n## Low\napp_chef['out_cont_cust_serv_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_cont_cust_serv_hi'][app_chef['contact_cust_serv'] > cont_cust_serv_hi]\n\napp_chef['out_cont_cust_serv_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Cancelation before noon:\napp_chef['out_canc_bef_noon_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_canc_bef_noon_hi'][app_chef['late_cancel'] > canc_bef_noon_hi]\n\napp_chef['out_canc_bef_noon_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Late Deliveries:\napp_chef['out_late_deliv_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_late_deliv_hi'][app_chef['late_deliv'] > late_deliv_hi]\n\napp_chef['out_late_deliv_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Largest order per customer:\n## Low\napp_chef['out_larg_order_lo'] = 0\ncondition_hi = app_chef.loc[0:,'out_larg_order_lo'][app_chef['larger_order'] < larg_order_lo]\n\napp_chef['out_larg_order_lo'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n## High\napp_chef['out_larg_order_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_larg_order_hi'][app_chef['larger_order'] > larg_order_hi]\n\napp_chef['out_larg_order_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Average clicks:\n## Low\napp_chef['out_avg_clicks_lo'] = 0\ncondition_hi = app_chef.loc[0:,'out_avg_clicks_lo'][app_chef['avg_clicks'] < avg_clicks_lo]\n\napp_chef['out_avg_clicks_lo'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n## High\napp_chef['out_avg_clicks_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_avg_clicks_hi'][app_chef['avg_clicks'] > avg_clicks_hi]\n\napp_chef['out_avg_clicks_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Total Photos:\napp_chef['out_total_photos_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_total_photos_hi'][app_chef['total_photos'] > total_photos_hi]\n\napp_chef['out_total_photos_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Late Deliveries (% of total):\napp_chef['out_pct_late_deliv_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_pct_late_deliv_hi'][app_chef['pct_late_deliv'] > pct_late_deliv_hi]\n\napp_chef['out_pct_late_deliv_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Early Deliveries (% of total):\napp_chef['out_pct_early_deliv_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_pct_early_deliv_hi'][app_chef['pct_early_deliv'] > pct_early_deliv_hi]\n\napp_chef['out_pct_early_deliv_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Total meals:\napp_chef['out_share_total_meals_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_share_total_meals_hi'][app_chef['share_total_meals'] > share_total_meals_hi]\n\napp_chef['out_share_total_meals_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Response variable:\nrevenue_hi = 5000\nshare_revenue_hi = 0.0013\n\n# Revenue:\napp_chef['out_revenue_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_revenue_hi'][app_chef['revenue'] > revenue_hi]\n\napp_chef['out_revenue_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Share revenue:\napp_chef['out_share_revenue_hi'] = 0\ncondition_hi = app_chef.loc[0:,'out_share_revenue_hi'][app_chef['share_revenue'] > share_revenue_hi]\n\napp_chef['out_share_revenue_hi'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n# Ratio unique meals:\napp_chef['out_pct_unique_meals'] = 0\ncondition_hi = app_chef.loc[0:,'out_pct_unique_meals'][app_chef['pct_unique_meals'] > pct_unique_meals_hi]\n\napp_chef['out_pct_unique_meals'].replace(to_replace = condition_hi,\n value = 1,\n inplace = True)\n\n\n# In[ ]:\n\n\n# Creating one binary variable per categorical type: \n\n# For rating category, we will create a different column per different rank (1 to 5)\n# For email domain, we will create one column for 'professional' and another for 'personal'\n\n# Generating binary categorical variables\none_hot_med_meal_rate = pd.get_dummies(app_chef['rating_category'])\none_hot_domain_group = pd.get_dummies(app_chef['domain_group'])\none_hot_cust_serv_status = pd.get_dummies(app_chef['cust_serv_status'])\none_hot_follow_rec_category = pd.get_dummies(app_chef['follow_rec_category'])\n\n# Including binary variables in the dataframe\napp_chef = app_chef.join([one_hot_med_meal_rate, one_hot_domain_group, \n one_hot_cust_serv_status, one_hot_follow_rec_category])\n\n\n# ***\n# <h3> Classification Model </h3>\n\n# In[ ]:\n\n\n# Setting explanatory and response variable \n\n# Explanatory variable:\napp_chef_data = app_chef.drop(['cross_sell'], axis = 1)\n\n# Dropping discrete variables: \napp_chef_data = app_chef_data.drop(['name','email','first_name','family_name',\n 'domain', 'domain_group', 'rating_category',\n 'cust_serv_status', 'follow_rec_category'],axis = 1)\n\n# Preparing the target variable\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n\n# In[ ]:\n\n\n# Splitting dataset in train and test with stratification: \nX_train, X_test, y_train, y_test = train_test_split(\n app_chef_data,\n app_chef_target,\n test_size = 0.25,\n random_state = 222,\n stratify = app_chef_target)\n\n# Creating training dataset for statsmodel:\napp_chef_train = pd.concat([X_train, y_train], axis = 1)\n\n# Printing explanatory variables in the format to be included in the model:\n#for val in app_chef_data:\n# print(f\"{val} +\")\n\n\n# In[ ]:\n\n\n# Creating empty dataframe to compare models: \nmodel_performance = []\n\n\n# <h4> Logistic Regression Model </h4>\n\n# In[ ]:\n\n\n## Setting Logistic Regression will all explanatory variables: \n# Building model\nlogistic_full = smf.logit(formula = \"\"\" cross_sell ~\n revenue +\n total_meals +\n unique_meals +\n contact_cust_serv +\n prod_cat_view +\n avg_time_vis +\n early_cancel +\n late_cancel +\n tastes_pref +\n week_plan +\n early_deliv +\n late_deliv +\n pack_lock +\n ref_lock +\n follow_rec_pct +\n avg_prep_time +\n larger_order +\n med_meal_rate +\n avg_clicks +\n total_photos +\n m_family_name +\n avg_tckt_order +\n avg_contact_cust_serv +\n pct_late_deliv +\n pct_early_deliv +\n pct_unique_meals +\n total_logins +\n pct_mob_logins +\n attended_master_class +\n out_avg_time_hi +\n out_avg_prep_lo +\n out_avg_prep_hi +\n out_total_meals_hi +\n out_unique_meals_hi +\n out_late_deliv_hi +\n out_larg_order_lo +\n out_larg_order_hi +\n out_avg_clicks_lo +\n out_avg_clicks_hi +\n out_total_photos_hi +\n out_pct_late_deliv_hi +\n out_pct_early_deliv_hi +\n out_revenue_hi +\n out_pct_unique_meals +\n Negative +\n Positive +\n business +\n Unhappy +\n Frequently +\n Rarely \"\"\",\n data = app_chef_train)\n\n# We removed the following variables to allow the model to run: 'pc_logins', 'mobile_logins','mob_number','share_revenue',\n# 'share_total_meals', 'Neutral','personal','Satisfied','Sometimes'\n\n# Fitting the model object\nresults_full = logistic_full.fit()\n\n\n# In[ ]:\n\n\n## Defining significant variables: \n# Building model only with significant variables (p-value lower than 0.1)\nlogit_sig = smf.logit(formula = \"\"\" cross_sell ~\n unique_meals +\n early_cancel +\n tastes_pref +\n follow_rec_pct +\n pct_unique_meals +\n out_revenue_hi +\n out_pct_unique_meals +\n pct_mob_logins +\n business \"\"\",\n data = app_chef_train)\n\n# Fitting:\nlogit_sig = logit_sig.fit()\n\n\n# In[ ]:\n\n\n## Creating a dictionary to store different variable packs: \n\ncandidate_dict = {\n\n # Model with all explanatory variables:\n 'logit_full' : ['revenue','total_meals','unique_meals','contact_cust_serv','prod_cat_view',\n 'avg_time_vis','early_cancel','late_cancel','tastes_pref','week_plan',\n 'early_deliv','late_deliv','pack_lock','ref_lock','follow_rec_pct','avg_prep_time',\n 'larger_order','med_meal_rate','avg_clicks','total_photos','m_family_name','avg_tckt_order',\n 'avg_contact_cust_serv','pct_late_deliv','pct_early_deliv','pct_unique_meals','total_logins',\n 'pct_mob_logins','attended_master_class','out_avg_time_hi','out_avg_prep_lo','out_avg_prep_hi',\n 'out_total_meals_hi','out_unique_meals_hi','out_late_deliv_hi','out_larg_order_lo',\n 'out_larg_order_hi','out_avg_clicks_lo','out_avg_clicks_hi','out_total_photos_hi',\n 'out_pct_late_deliv_hi','out_pct_early_deliv_hi','out_revenue_hi','out_pct_unique_meals',\n 'Negative','Positive','business','Unhappy','Frequently','Rarely'],\n \n # Model only with significant variables:\n 'logit_sig' : ['unique_meals','early_cancel','tastes_pref','follow_rec_pct','pct_unique_meals',\n 'out_revenue_hi','out_pct_unique_meals','pct_mob_logins','business'],\n \n 'tree_sig' : []\n\n}\n\n\n# In[ ]:\n\n\n## Model with all variables: \napp_chef_data = app_chef.loc[ : , candidate_dict['logit_full']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n\n# Splitting dataset in train and test:\nX_train, X_test, y_train, y_test = train_test_split(\n app_chef_data,\n app_chef_target,\n test_size = 0.25,\n random_state = 222,\n stratify = app_chef['follow_rec_pct'])\n\n# Instantiating:\nlogreg = LogisticRegression(solver = 'lbfgs',\n C = 1,\n random_state = 222)\n\n\n# Fitting:\nlogreg_fit = logreg.fit(X_train, y_train)\n\n\n# Predicting:\nlogreg_pred = logreg_fit.predict(X_test)\n\n# Getting Area Under the ROC Curve (AUC): \nroc_auc_score(y_true = y_test,\n y_score = logreg_pred)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['Logistic Regression: all',\n logreg_fit.score(X_train, y_train).round(4),\n logreg_fit.score(X_test, y_test).round(4),\n roc_auc_score(y_true = y_test,\n y_score = logreg_pred).round(4)])\n\n\n# In[ ]:\n\n\n## Standardized model with all variables: \n# Divide a standardized data set into train and test variable to run models side by side\napp_chef_data = app_chef.loc[ : , candidate_dict['logit_full']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n# Instantiating StandardScaler()\nscaler = StandardScaler()\n\n# Fitting:\nscaler.fit(app_chef_data)\n\n\n# Tranforming the independent variable data:\nX_scaled = scaler.transform(app_chef_data)\n\n\n# Converting to a DataFrame:\nX_scaled_df = pd.DataFrame(X_scaled) \n\n\n# Spliting dataset again, now with scaled data:\nX_train_scaled, X_test_scaled, y_train_scaled, y_test_scaled = train_test_split(\n X_scaled_df,\n app_chef_target,\n random_state = 222,\n test_size = 0.25,\n stratify = app_chef['follow_rec_pct'])\n# Instantiating:\nlogreg = LogisticRegression(solver = 'liblinear',\n C = 1,\n random_state = 222)\n\n\n# Fitting:\nlogreg_fit = logreg.fit(X_train_scaled, y_train_scaled)\n\n\n# Predicting:\nlogreg_pred = logreg_fit.predict(X_test_scaled)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['Logistic Regression: standard/all',\n logreg_fit.score(X_train_scaled, y_train_scaled).round(4),\n logreg_fit.score(X_test_scaled, y_test_scaled).round(4),\n roc_auc_score(y_true = y_test_scaled,\n y_score = logreg_pred).round(4)])\n\n\n# In[ ]:\n\n\n## Model with significant variables: \napp_chef_data = app_chef.loc[ : , candidate_dict['logit_sig']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n\n# Splitting dataset:\nX_train, X_test, y_train, y_test = train_test_split(\n app_chef_data,\n app_chef_target,\n test_size = 0.25,\n random_state = 222,\n stratify = app_chef['follow_rec_pct'])\n\n# Instantiating:\nlogreg = LogisticRegression(solver = 'lbfgs',\n C = 1,\n random_state = 222)\n\n# Fitting:\nlogreg_fit = logreg.fit(X_train, y_train)\n\n# Predicting:\nlogreg_pred = logreg_fit.predict(X_test)\n\n# Getting Area Under the ROC Curve (AUC): \nroc_auc_score(y_true = y_test,\n y_score = logreg_pred)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['Logistic Regression: significant',\n logreg_fit.score(X_train, y_train).round(4),\n logreg_fit.score(X_test, y_test).round(4),\n roc_auc_score(y_true = y_test,\n y_score = logreg_pred).round(4)])\n\n\n# In[ ]:\n\n\n## Standardized model with significant variables: \n# Divide a standardized data set into train and test variable to run models side by side\napp_chef_data = app_chef.loc[ : , candidate_dict['logit_sig']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n# Instantiating:\nscaler = StandardScaler()\n\n# Fitting:\nscaler.fit(app_chef_data)\n\n\n# Transforming the independent variable data:\nX_scaled = scaler.transform(app_chef_data)\n\n\n# Converting to a DataFrame:\nX_scaled_df = pd.DataFrame(X_scaled) \n\n\n# Spliting dataset again, now with scaled data:\nX_train_scaled, X_test_scaled, y_train_scaled, y_test_scaled = train_test_split(\n X_scaled_df,\n app_chef_target,\n random_state = 222,\n test_size = 0.25,\n stratify = app_chef['follow_rec_pct'])\n# Instantiating:\nlogreg = LogisticRegression(solver = 'liblinear',\n C = 1,\n random_state = 222)\n\n\n# Fitting:\nlogreg_fit = logreg.fit(X_train_scaled, y_train_scaled)\n\n\n# Predicting:\nlogreg_pred = logreg_fit.predict(X_test_scaled)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['Logistic Regression: standard/significant',\n logreg_fit.score(X_train_scaled, y_train_scaled).round(4),\n logreg_fit.score(X_test_scaled, y_test_scaled).round(4),\n roc_auc_score(y_true = y_test_scaled,\n y_score = logreg_pred).round(4)])\n\n\n# <h4> KNN: Neighbors Regressor Classifier </h4>\n\n# In[ ]:\n\n\n# Creating function to get optimal_neighbors: \ndef optimal_neighbors(X_data,\n y_data,\n standardize = True,\n pct_test=0.25,\n seed=222,\n response_type='reg',\n max_neighbors=20,\n show_viz=True): \n \n if standardize == True:\n scaler = StandardScaler()\n scaler.fit(X_data)\n X_scaled = scaler.transform(X_data)\n X_scaled_df = pd.DataFrame(X_scaled)\n X_data = X_scaled_df\n\n # Splitting:\n X_train, X_test, y_train, y_test = train_test_split(X_data,\n y_data,\n test_size = pct_test,\n random_state = seed)\n\n # creating lists for training set accuracy and test set accuracy\n training_accuracy = []\n test_accuracy = []\n \n # Setting neighbor range\n neighbors_settings = range(1, max_neighbors + 1)\n\n for n_neighbors in neighbors_settings:\n if response_type == 'reg':\n clf = KNeighborsRegressor(n_neighbors = n_neighbors)\n clf.fit(X_train, y_train)\n \n elif response_type == 'class':\n clf = KNeighborsClassifier(n_neighbors = n_neighbors)\n clf.fit(X_train, y_train) \n \n else:\n print(\"Error: response_type must be 'reg' or 'class'\")\n \n # Scoring:\n training_accuracy.append(clf.score(X_train, y_train))\n test_accuracy.append(clf.score(X_test, y_test))\n\n\n # Plotting accuracy:\n if show_viz == True:\n fig, ax = plt.subplots(figsize=(12,8))\n plt.plot(neighbors_settings, training_accuracy, label = \"training accuracy\")\n plt.plot(neighbors_settings, test_accuracy, label = \"test accuracy\")\n plt.ylabel(\"Accuracy\")\n plt.xlabel(\"n_neighbors\")\n plt.legend()\n plt.show() \n \n # Getting optimal number of neighbors:\n print(f\"The optimal number of neighbors is: {test_accuracy.index(max(test_accuracy))+1}\")\n return test_accuracy.index(max(test_accuracy))+1\n\n\n# In[ ]:\n\n\n## Model with all variables: \napp_chef_data = app_chef.loc[ : , candidate_dict['logit_full']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n\n# Note that we used the most significant variable to stratify\nX_train, X_test, y_train, y_test = train_test_split(\n app_chef_data,\n app_chef_target,\n test_size = 0.25,\n random_state = 222,\n stratify = app_chef['follow_rec_pct'])\n\n# Instantiating:\nknn_opt = KNeighborsClassifier(n_neighbors = optimal_neighbors(X_train, \n y_train,show_viz=False))\n\n# Fitting:\nknn_fit = knn_opt.fit(X_train, y_train)\n\n# Predicting:\nknn_pred = knn_fit.predict(X_test)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['KNN Classification: all',\n knn_fit.score(X_train, y_train).round(4),\n knn_fit.score(X_test, y_test).round(4),\n roc_auc_score(y_true = y_test,\n y_score = knn_pred).round(4)])\n\n\n# In[ ]:\n\n\n## Standardized model with all variables: \n# Divide a standardized data set into train and test variable to run models side by side\napp_chef_data = app_chef.loc[ : , candidate_dict['logit_full']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n# Instantiating StandardScaler()\nscaler = StandardScaler()\n\n# Fitting:\nscaler.fit(app_chef_data)\n\n\n# Transforming:\nX_scaled = scaler.transform(app_chef_data)\n\n\n# Converting to a DataFrame:\nX_scaled_df = pd.DataFrame(X_scaled) \n\n\n# Spliting dataset again, now with scaled data:\nX_train_scaled, X_test_scaled, y_train_scaled, y_test_scaled = train_test_split(\n X_scaled_df,\n app_chef_target,\n random_state = 222,\n test_size = 0.25,\n stratify = app_chef['follow_rec_pct'])\n\n# Instantiating scaled data:\nknn_opt = KNeighborsClassifier(n_neighbors = optimal_neighbors(X_train, \n y_train,\n show_viz = False))\n\n\n# Fitting:\nknn_fit = knn_opt.fit(X_train_scaled, y_train_scaled)\n\n\n# Predicting:\nknn_pred = knn_fit.predict(X_test_scaled)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['KNN Classification: standard/all',\n knn_fit.score(X_train_scaled, y_train_scaled).round(4),\n knn_fit.score(X_test_scaled, y_test_scaled).round(4),\n roc_auc_score(y_true = y_test_scaled,\n y_score = knn_pred).round(4)])\n\n\n# In[ ]:\n\n\n## Model with significant variables: \napp_chef_data = app_chef.loc[ : , candidate_dict['logit_sig']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n\n# Note that we used the most significant variable to stratify\nX_train, X_test, y_train, y_test = train_test_split(\n app_chef_data,\n app_chef_target,\n test_size = 0.25,\n random_state = 222,\n stratify = app_chef['follow_rec_pct'])\n\n# Instantiating:\nknn_opt = KNeighborsClassifier(n_neighbors = optimal_neighbors(X_train, \n y_train,\n show_viz = False))\n\n\n# Fitting:\nknn_fit = knn_opt.fit(X_train, y_train)\n\n\n# Predicting:\nknn_pred = knn_fit.predict(X_test)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['KNN Classification: significant',\n knn_fit.score(X_train, y_train).round(4),\n knn_fit.score(X_test, y_test).round(4),\n roc_auc_score(y_true = y_test,\n y_score = knn_pred).round(4)])\n\n\n# In[ ]:\n\n\n## Standardized model with significant variables: \n# Divide a standardized data set into train and test variable to run models side by side\napp_chef_data = app_chef.loc[ : , candidate_dict['logit_sig']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n# Instantiating StandardScaler():\nscaler = StandardScaler()\n\n# Fitting the independent variable data:\nscaler.fit(app_chef_data)\n\n\n# Transforming the independent variable data:\nX_scaled = scaler.transform(app_chef_data)\n\n\n# Converting to a DataFrame:\nX_scaled_df = pd.DataFrame(X_scaled) \n\n\n# Spliting dataset again, now with scaled data:\nX_train_scaled, X_test_scaled, y_train_scaled, y_test_scaled = train_test_split(\n X_scaled_df,\n app_chef_target,\n random_state = 222,\n test_size = 0.25,\n stratify = app_chef['follow_rec_pct'])\n\n# Instantiating scaled data:\nknn_opt = KNeighborsClassifier(n_neighbors = optimal_neighbors(X_train, \n y_train,\n show_viz = False))\n\n\n# Fitting:\nknn_fit = knn_opt.fit(X_train_scaled, y_train_scaled)\n\n\n# Predicting:\nknn_pred = knn_fit.predict(X_test_scaled)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['KNN Classification: standard/significant',\n knn_fit.score(X_train_scaled, y_train_scaled).round(4),\n knn_fit.score(X_test_scaled, y_test_scaled).round(4),\n roc_auc_score(y_true = y_test_scaled,\n y_score = knn_pred).round(4)])\n\n\n# <h4> Decision Tree Classifier </h4>\n\n# In[ ]:\n\n\n## Model with all variables: \napp_chef_data = app_chef.loc[ : , candidate_dict['logit_full']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n# Note that we used the most significant variable to stratify\nX_train, X_test, y_train, y_test = train_test_split(\n app_chef_data,\n app_chef_target,\n test_size = 0.25,\n random_state = 222,\n stratify = app_chef['follow_rec_pct'])\n\n# Building decision tree model:\ntree_pruned = DecisionTreeClassifier(max_depth = 4,\n min_samples_leaf = 25,\n random_state = 802)\n\n# Fitting:\ntree_pruned_fit = tree_pruned.fit(X_train, y_train)\n\n\n# Predicting:\ntree_pred = tree_pruned_fit.predict(X_test)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['Decision Tree: all',\n tree_pruned_fit.score(X_train, y_train).round(4),\n tree_pruned_fit.score(X_test, y_test).round(4),\n roc_auc_score(y_true = y_test,\n y_score = tree_pred).round(4)])\n\n\n# In[ ]:\n\n\n## Model with significant variables: \napp_chef_data = app_chef.loc[ : , candidate_dict['logit_sig']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n\n# Note that we used the most significant variable to stratify\nX_train, X_test, y_train, y_test = train_test_split(\n app_chef_data,\n app_chef_target,\n test_size = 0.25,\n random_state = 222,\n stratify = app_chef['follow_rec_pct'])\n\n# Building decision tree model:\ntree_pruned = DecisionTreeClassifier(max_depth = 4,\n min_samples_leaf = 25,\n random_state = 802)\n\n# Fitting:\ntree_pruned_fit = tree_pruned.fit(X_train, y_train)\n\n\n# Predicting:\ntree_pred = tree_pruned_fit.predict(X_test)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['Decision Tree: significant',\n tree_pruned_fit.score(X_train, y_train).round(4),\n tree_pruned_fit.score(X_test, y_test).round(4),\n roc_auc_score(y_true = y_test,\n y_score = tree_pred).round(4)])\n\n\n# <h4> Random Forest Classifier </h4>\n\n# In[ ]:\n\n\n## Model with all variables: \napp_chef_data = app_chef.loc[ : , candidate_dict['logit_full']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n\n# Note that we used the most significant variable to stratify\nX_train, X_test, y_train, y_test = train_test_split(\n app_chef_data,\n app_chef_target,\n test_size = 0.25,\n random_state = 222,\n stratify = app_chef['follow_rec_pct'])\n\n# Instantiating:\nrndfor = RandomForestClassifier(criterion = 'gini',\n bootstrap = True, \n max_depth = 4, \n n_estimators = 10,\n min_samples_leaf = 25, \n random_state = 222)\n\n# Fitting:\nrndfor_fit = rndfor.fit(X_train, y_train)\n\n# Predicting:\nrndfor_pred = rndfor_fit.predict(X_test)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['Random Forrest: all',\n rndfor_fit.score(X_train, y_train).round(4),\n rndfor_fit.score(X_test, y_test).round(4),\n roc_auc_score(y_true = y_test,\n y_score = rndfor_pred).round(4)])\n\n\n# In[ ]:\n\n\n## Tunned model with all variables: \n#app_chef_data = app_chef.loc[ : , candidate_dict['logit_full']]\n#app_chef_target = app_chef.loc[ : , 'cross_sell']\n\n# Declaring a hyperparameter space:\n#estimator_space = pd.np.arange(100, 1100, 250)\n#leaf_space = pd.np.arange(1, 31, 10)\n#criterion_space = ['gini', 'entropy']\n#bootstrap_space = [True, False]\n#warm_start_space = [True, False]\n\n\n# Creating a hyperparameter grid:\n#param_grid = {'n_estimators' : estimator_space,\n# 'min_samples_leaf' : leaf_space,\n# 'criterion' : criterion_space,\n# 'bootstrap' : bootstrap_space,\n# 'warm_start' : warm_start_space}\n\n\n# Instantiating without hyperparameters:\n#full_forest_grid = RandomForestClassifier(random_state = 222)\n\n\n# GridSearchCV object:\n#full_forest_cv = GridSearchCV(estimator = full_forest_grid,\n# param_grid = param_grid,\n# cv = 3,\n# scoring = make_scorer(roc_auc_score,\n# needs_threshold = False))\n\n\n# Fitting:\n#full_forest_cv.fit(app_chef_data, app_chef_target)\n\n# Instantiating with hyperparameters:\n#full_rf_tuned = RandomForestClassifier(bootstrap = True,\n# criterion = 'gini',\n# min_samples_leaf = 11,\n# n_estimators = 850,\n# warm_start = True,\n# random_state = 222)\n\n\n# Fitting:\n#full_rf_tuned_fit = full_rf_tuned.fit(X_train, y_train)\n\n\n# Predicting:\n#full_rf_tuned_pred = full_rf_tuned_fit.predict(X_test)\n\n# Scoring:\n#print('Training ACCURACY:', full_rf_tuned_fit.score(X_train, y_train).round(4))\n#print('Testing ACCURACY:', full_rf_tuned_fit.score(X_test, y_test).round(4))\n#print('AUC Score :', roc_auc_score(y_true = y_test,\n# y_score = full_rf_tuned_pred).round(4))\n\n# Adding model results to consolidated table:\nmodel_performance.append(['Tunned Random Forest: all',\n 0.8273,\n 0.7823,\n 0.7703])\n\n\n# <h4> Gradient Booster Classifier</h4>\n\n# In[ ]:\n\n\n## Model with significant variables: \napp_chef_data = app_chef.loc[ : , candidate_dict['logit_sig']]\napp_chef_target = app_chef.loc[ : , 'cross_sell']\n\n\n# Note that we used the most significant variable to stratify\nX_train, X_test, y_train, y_test = train_test_split(\n app_chef_data,\n app_chef_target,\n test_size = 0.25,\n random_state = 222,\n stratify = app_chef['follow_rec_pct'])\n\n# Instantiating:\ng_boost = GradientBoostingClassifier(loss = 'deviance',\n criterion = 'mae',\n learning_rate = 0.1,\n n_estimators = 100,\n max_features = 3,\n random_state = 222)\n\n# Fitting:\ng_boost_fit = g_boost.fit(X_train, y_train)\n\n# Predicting:\ng_boost_pred = g_boost_fit.predict(X_test)\n\n# Adding model results to consolidated table:\nmodel_performance.append(['GradientBoosting: significant',\n g_boost_fit.score(X_train, y_train).round(4),\n g_boost_fit.score(X_test, y_test).round(4),\n roc_auc_score(y_true = y_test,\n y_score = g_boost_pred).round(4)])\n\n\n# In[ ]:\n\n\n## Tunned model with significant variables: \n#app_chef_data = app_chef.loc[ : , candidate_dict['logit_sig']]\n#app_chef_target = app_chef.loc[ : , 'cross_sell']\n\n# Declaring a hyperparameter space:\n#learn_space = pd.np.arange(0.1, 1.6, 0.3)\n#estimator_space = pd.np.arange(50, 250, 50)\n#depth_space = pd.np.arange(1, 10)\n\n\n# Creating a hyperparameter grid:\n#param_grid = {'learning_rate' : learn_space,\n# 'max_depth' : depth_space,\n# 'n_estimators' : estimator_space}\n\n\n# Instantiating without hyperparameters:\n#full_gbm_grid = GradientBoostingClassifier(random_state = 222)\n\n\n# GridSearchCV object:\n#full_gbm_cv = GridSearchCV(estimator = full_gbm_grid,\n# param_grid = param_grid,\n# cv = 3,\n# scoring = make_scorer(roc_auc_score,\n# needs_threshold = False))\n\n\n# Fitting:\n#full_gbm_cv.fit(app_chef_data, app_chef_target)\n\n# Instantiating with hyperparameters:\n#gbm_tuned = GradientBoostingClassifier(learning_rate = 0.1,\n# max_depth = 2,\n# n_estimators = 100,\n# random_state = 222)\n\n# Fitting:\n#gbm_tuned_fit = gbm_tuned.fit(X_train, y_train)\n\n# Predicting:\n#gbm_tuned_pred = gbm_tuned_fit.predict(X_test)\n\n# Scoring:\n#print('Training ACCURACY:', gbm_tuned_fit.score(X_train, y_train).round(4))\n#print('Testing ACCURACY:', gbm_tuned_fit.score(X_test, y_test).round(4))\n#print('AUC Score :', roc_auc_score(y_true = y_test,\n# y_score = gbm_tuned_pred).round(4))\n\n# Adding model results to consolidated table:\nmodel_performance.append(['Tunned Gradient Boosting: significant',\n 0.8136,\n 0.7906,\n 0.7905])\n\n\n# <h4> Comparing models </h4>\n\n# In[ ]:\n\n\n# List of all built models with respective results: \nmodel_performance = pd.DataFrame(model_performance)\nmodel_performance = model_performance.rename(columns={0: 'Model', \n 1: 'Training Accuracy',\n 2: 'Testing Accuracy', \n 3: 'AUC Value'})\nmodel_performance\n\n" } ]
3
Sriramnat100/Discord_Bot
https://github.com/Sriramnat100/Discord_Bot
044fd5018b0fdb4a73dbd3a069f9a5bae1b90309
309fe14d52e5999cccb5f06bdea26ac4d3df0d55
0f141a73db22b8f4e14f19fbcec24a6d999ef1bf
refs/heads/main
2023-04-20T15:46:45.006461
2021-05-11T02:08:23
2021-05-11T02:08:23
366,228,367
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.663273274898529, "alphanum_fraction": 0.6679717898368835, "avg_line_length": 25.978872299194336, "blob_id": "431b86ba9ddf4a11c82f0bcf3ee57431502e309d", "content_id": "379c4a653be265930fb4c144991990de9bac4255", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3837, "license_type": "no_license", "max_line_length": 96, "num_lines": 142, "path": "/bot.py", "repo_name": "Sriramnat100/Discord_Bot", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport discord\nimport requests\nimport random\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot\nimport ast\nimport json\nimport youtube_dl\n\n\nclient = commands.Bot(command_prefix = \"$\")\n\ndef get_quote():\n#Getting quote from the API\n response = requests.get(\"https://api.kanye.rest/\")\n json_data = json.loads(response.text)\n quote = \"Kanye once said:\" + \" \" + json_data['quote']\n return(quote)\n\n\[email protected]\n#Creates function that detects when bot is ready\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n\n#command is a piece of code that happens when the user tells the bot to do something\[email protected]()\nasync def speed(ctx):\n await ctx.send(f'Speed is {round (client.latency * 1000)}ms')\n\n#we are defining amount has 5 bc if no one puts anything for amnt, it will clear 5\[email protected]()\nasync def clear(ctx, amount = 5):\n await ctx.channel.purge(limit=amount + 1)\n\n#echo feature\[email protected]()\nasync def echo(ctx, *,args):\n await ctx.send(args)\n await ctx.message.delete()\n\n#Kanye quote\[email protected]()\nasync def kanye(ctx):\n quote = get_quote()\n await ctx.send(quote)\n\n#poll feature\[email protected]()\nasync def poll(ctx, *, args):\n no = \"❌\"\n yes = \"☑️\"\n await ctx.message.delete()\n user_poll = await ctx.send(args)\n await user_poll.add_reaction(yes)\n await user_poll.add_reaction(no)\n\n#/////////START OF MUSIC FUNCTION/////////////////\n\n#Joining the VC\[email protected]()\nasync def join(ctx,*,args):\n #creating a vc to go in, name = args is vc name bot must join\n voiceChannel = discord.utils.get(ctx.guild.voice_channels, name=args)\n await voiceChannel.connect()\n #creating a voice client\n voice = discord.utils.get(client.voice_clients, guild=ctx.guild) \n\n\n#Playing the song\[email protected]()\nasync def play(ctx, url : str):\n song_there = os.path.isfile(\"song.mp3\")\n try:\n #Downloading and deleting song from computer after played\n if song_there:\n os.remove(\"song.mp3\")\n except PermissionError:\n await ctx.send(\"Wait for current playing music to end or use stop command\")\n return\n\n voice = discord.utils.get(client.voice_clients, guild=ctx.guild)\n\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '192',\n }],\n }\n\n #Downloads youtube url\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download([url])\n for file in os.listdir(\"./\"):\n if file.endswith(\".mp3\"):\n os.rename(file, \"song.mp3\")\n voice.play(discord.FFmpegPCMAudio(\"song.mp3\"))\n\n\n#Leaving function\[email protected]()\nasync def leave(ctx):\n voice = discord.utils.get(client.voice_clients, guild=ctx.guild)\n #Defining when the bot is connected, it will only disconnect when the leave function is used\n if voice.is_connected():\n await voice.disconnect()\n else: \n await ctx.send(\"The bot is not connected to a vc\")\n\n#Defining the pause function\[email protected]()\nasync def pause(ctx):\n #Defining when bot should pause, it will only pause when pause fucntion called\n voice = discord.utils.get(client.voice_clients, guild=ctx.guild)\n if voice.is_playing():\n voice.pause()\n else:\n await ctx.send(\"The bot is not playing music\")\n\n#Defining resume command\[email protected]()\nasync def resume(ctx):\n voice = discord.utils.get(client.voice_clients, guild=ctx.guild)\n if voice.is_paused():\n voice.resume()\n else:\n await ctx.send(\"The bot is not paused\")\n\n#Telling the bot to stop \[email protected]()\nasync def stop(ctx):\n voice = discord.utils.get(client.voice_clients, guild=ctx.guild)\n voice.stop()\n\n\n\nclient.run('token')\n" }, { "alpha_fraction": 0.7547169923782349, "alphanum_fraction": 0.7547169923782349, "avg_line_length": 16.66666603088379, "blob_id": "e797ed90793ff9e8eb139424cf5cf2bb19740e22", "content_id": "b8f6ee1ff2a39a1500491a25e5e903268f70e7f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 53, "license_type": "no_license", "max_line_length": 37, "num_lines": 3, "path": "/README.md", "repo_name": "Sriramnat100/Discord_Bot", "src_encoding": "UTF-8", "text": "# Discord_Bot\n\nThis is my Discord Bot that I created\n" } ]
2
brankomijuskovic/cs_capacity
https://github.com/brankomijuskovic/cs_capacity
2c6de52da4208ebecb716616d8c85141aa926a58
cf0e1d94b05e88a825ff28a4f2320bd984e24c3d
f1f214a5e968cc0edb42320709a489d1c88e6371
refs/heads/master
2020-03-31T22:55:57.752189
2018-10-12T11:19:26
2018-10-12T11:19:26
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6129032373428345, "alphanum_fraction": 0.619860827922821, "avg_line_length": 36.64285659790039, "blob_id": "c107db2ab2f055e24ad8c4fa8efcf86666eb08cf", "content_id": "07e55ea5c2bafab57171d07fc10f7091e5fabbca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1581, "license_type": "no_license", "max_line_length": 108, "num_lines": 42, "path": "/app.py", "repo_name": "brankomijuskovic/cs_capacity", "src_encoding": "UTF-8", "text": "import time\nimport json\nimport datetime\nimport os\nimport sys\nfrom cs import CloudStack\nfrom influxdb import InfluxDBClient\n\nsleep_time = os.environ['SLEEP']\ninfluxdb_host = os.environ['INFLUXDB_HOST']\n\ntry:\n config = json.loads(os.environ['CONFIG'])\nexcept Exception as err:\n print(\"No access parameters provided, exiting. {}\".format(err))\n sys.exit(1)\n\nwhile True:\n try:\n client = InfluxDBClient(influxdb_host, 8086, 'root', 'root', 'cs_capacity')\n client.create_database('cs_capacity')\n break\n except Exception as err:\n print(\"{} - Can't connect to InfluxDB, sleeping.\".format(datetime.datetime.now()))\n print(err)\n time.sleep(5)\n\nwhile True:\n for zone, params in config.items():\n try:\n cs = CloudStack(endpoint=params['api_url'], key=params['api_key'], secret=params['secret_key'])\n mem = cs.listCapacity(type=0)['capacity'][0]['percentused']\n cpu = cs.listCapacity(type=1)['capacity'][0]['percentused']\n vms = cs.listVirtualMachines(state='running', listall='true')['count']\n client.write_points([{\"measurement\": zone + \" - CPU\", \"fields\": {\"value\": float(cpu)}}])\n client.write_points([{\"measurement\": zone + \" - RAM\", \"fields\": {\"value\": float(mem)}}])\n client.write_points([{\"measurement\": zone + \" - VMs running\", \"fields\": {\"value\": float(vms)}}])\n except Exception as err:\n print(\"{} - Something went wrong. {}\".format(datetime.datetime.now(), err))\n time.sleep(5)\n\n time.sleep(int(sleep_time))\n" }, { "alpha_fraction": 0.726190447807312, "alphanum_fraction": 0.75, "avg_line_length": 27, "blob_id": "e39230f67eb7acafb158e8a11d3f215a859a99d1", "content_id": "ca25ef420e7547692518e89e008c94ce6d277d97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 252, "license_type": "no_license", "max_line_length": 50, "num_lines": 9, "path": "/Dockerfile", "repo_name": "brankomijuskovic/cs_capacity", "src_encoding": "UTF-8", "text": "FROM python:3.6-alpine\nLABEL maintainer=\"branko.mijuskovic\"\nENV SLEEP=3600\nENV INFLUXDB_HOST=influxdb\nWORKDIR /usr/src/app\nCOPY requirements.txt .\nRUN pip install --no-cache-dir -r requirements.txt\nCOPY app.py .\nENTRYPOINT [\"python\", \"-u\", \"./app.py\"]\n" }, { "alpha_fraction": 0.597484290599823, "alphanum_fraction": 0.6247379183769226, "avg_line_length": 18.83333396911621, "blob_id": "8b3df1ab0722c4ef12c01cb300511a13ccaaf32c", "content_id": "0a15216a2de0ca495d19fa15cf681d40a431f90f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 477, "license_type": "no_license", "max_line_length": 40, "num_lines": 24, "path": "/docker-compose.yml", "repo_name": "brankomijuskovic/cs_capacity", "src_encoding": "UTF-8", "text": "version: '3'\nservices:\n cs_capacity:\n image: enemy/cs_capacity:latest\n env_file: ./config.json\n environment:\n - SLEEP=3600\n - INFLUXDB_HOST=influxdb\n restart: always\n influxdb:\n image: influxdb\n volumes:\n - \"influxdb_vol:/var/lib/influxdb\"\n restart: always\n grafana:\n image: grafana/grafana\n ports:\n - \"3000:3000\"\n volumes:\n - \"grafana_vol:/var/lib/grafana\"\n restart: always\nvolumes:\n grafana_vol:\n influxdb_vol:\n\n" } ]
3
n00py/Black-Hat-Python
https://github.com/n00py/Black-Hat-Python
cacb845624c8f2680045f857e3324ed1ef2ea880
3d65dad0926626b0fb8c132a8c46e882b5c839e3
55ba46afc51d9dc3b17b7fb685f24ee581aace9b
refs/heads/master
2021-01-10T22:45:38.167222
2015-05-26T20:15:01
2015-05-26T20:15:01
70,357,017
1
1
null
2016-10-08T20:57:33
2016-07-26T10:29:43
2015-05-26T20:15:06
null
[ { "alpha_fraction": 0.6042531132698059, "alphanum_fraction": 0.6234439611434937, "avg_line_length": 30.62295150756836, "blob_id": "be3a5262d9528b791fc13ed16f719a3ccd156ff6", "content_id": "17c70e4235eb44cf7b5d697005740e2a327975f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1928, "license_type": "no_license", "max_line_length": 120, "num_lines": 61, "path": "/proxy.py", "repo_name": "n00py/Black-Hat-Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\n\nimport sys\nimport socket\nimport threading\n\ndef server_loop(local_host,local_port,remote_host,remote_port,receive_first):\n \n # create the server object\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \n # lets see if we can stand up the server\n try:\n server.bind((local_host,local_port))\n except:\n print \"[!!] Failed to listen on %s:%d\" % (local_host, local_port)\n print \"[!!] Check for other listening sockets or correct permissions\"\n sys.exit(0)\n \n # listen with 5 backlogged--queued--connections\n server.listen(5)\n \n while True:\n client_socket, addr = server.accept()\n \n # print out the local connection information \n print\"[+] Received incomming connections from %s:%d\" % (addr[0],addr[1])\n \n # start a new thread to talk to the remote host\n proxy_thread = threading.Thread(target=proxy_handler,args=(client_socket,remote_host,remote_port,receive_first))\n \n proxy_thread.start()\n \ndef main():\n # cursory check of command line args\n if len(sys.argv[1:]) != 5:\n print \"Usage: ./proxy.py [localhost] [localport] [remotehost] [remoteport] [reveive_first]\"\n print \"Example: ./proxy.py 127.0.0.1 9000 10.11.132.1 9000 True\"\n sys.exit(0)\n \n # set up listening parameters\n local_host = sys.argv[1]\n local_port = int(sys.argv[2])\n \n # set up remote targets\n remote_host = sys.argv[3]\n remote_port = int(sys.argv[4])\n \n # this tells our proxy to connect and receive data before sending to the remote host\n receive_first = sys.argv[5]\n \n if \"True\" in receive_first:\n receive_first = True\n else:\n receive_first = False\n \n # now spin up our listening socket\n server_loop(local_host,local_port,remote_host,remote_port,receive_first)\n \nif __name__ == \"__main__\":\n main()" } ]
1
jason-klein/dsad-picoctf-2018-dog-or-frog
https://github.com/jason-klein/dsad-picoctf-2018-dog-or-frog
6035f22afdece5ef846849d3da885c191b8e74d2
e7bf0a0d16841a68aaa85ab6bdf79a4f6d39d67d
6a7ed290276e1fd2e2a43a000baa38198d95067c
refs/heads/master
2022-04-23T21:38:57.883023
2020-04-22T05:33:51
2020-04-22T05:33:51
257,800,619
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6724879741668701, "alphanum_fraction": 0.6922298073768616, "avg_line_length": 38.108909606933594, "blob_id": "60e48edaaf9c611ca42c3b738fea768a46584d64", "content_id": "7f9e2da7b21cc97b425cc8f9c98b757dcbd0dfc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3951, "license_type": "no_license", "max_line_length": 128, "num_lines": 101, "path": "/solution_frog.py", "repo_name": "jason-klein/dsad-picoctf-2018-dog-or-frog", "src_encoding": "UTF-8", "text": "# Based on https://tcode2k16.github.io/blog/posts/picoctf-2018-writeup/general-skills/#dog-or-frog\n\nfrom keras.applications.mobilenet import preprocess_input\nfrom keras.models import load_model\nfrom keras.preprocessing.image import img_to_array, array_to_img\nfrom PIL import Image\nfrom imagehash import phash\nimport numpy as np\nfrom keras import backend as K\n\nIMAGE_DIMS = (224, 224)\nCATEGORY_IDX = 31\nCATEGORY_STR = \"tree_frog\"\n\n# I'm pretty sure I borrowed this function from somewhere, but cannot remember\n# the source to cite them properly.\ndef hash_hamming_distance(h1, h2):\n s1 = str(h1)\n s2 = str(h2)\n return sum(map(lambda x: 0 if x[0] == x[1] else 1, zip(s1, s2)))\n\n\ndef is_similar_img(path1, path2):\n image1 = Image.open(path1)\n image2 = Image.open(path2)\n\n dist = hash_hamming_distance(phash(image1), phash(image2))\n return dist <= 1\n\n\ndef prepare_image(image, target=IMAGE_DIMS):\n # if the image mode is not RGB, convert it\n if image.mode != \"RGB\":\n image = image.convert(\"RGB\")\n\n # resize the input image and preprocess it\n image = image.resize(target)\n image = img_to_array(image)\n image = np.expand_dims(image, axis=0)\n image = preprocess_input(image)\n # return the processed image\n return image\n\n\ndef create_img(img_path, img_res_path, model_path, target_str, target_idx, des_conf=0.95):\n original_image = Image.open(img_path).resize(IMAGE_DIMS)\n original_image = prepare_image(original_image)\n model = load_model(model_path)\n\n model_input_layer = model.layers[0].input\n model_output_layer = model.layers[-1].output\n\n max_change_above = original_image + 0.01\n max_change_below = original_image - 0.01\n\n # Create a copy of the input image to hack on\n hacked_image = np.copy(original_image)\n\n # How much to update the hacked image in each iteration\n learning_rate = 0.01\n\n # Define the cost function.\n # Our 'cost' will be the likelihood out image is the target class according to the pre-trained model\n cost_function = model_output_layer[0, CATEGORY_IDX]\n\n # We'll ask Keras to calculate the gradient based on the input image and the currently predicted class\n # In this case, referring to \"model_input_layer\" will give us back image we are hacking.\n gradient_function = K.gradients(cost_function, model_input_layer)[0]\n\n # Create a Keras function that we can call to calculate the current cost and gradient\n grab_cost_and_gradients_from_model = K.function([model_input_layer, K.learning_phase()], [cost_function, gradient_function])\n\n cost = 0.0\n\n # In a loop, keep adjusting the hacked image slightly so that it tricks the model more and more\n # until it gets to at least 80% confidence\n while cost < 0.99:\n # Check how close the image is to our target class and grab the gradients we\n # can use to push it one more step in that direction.\n # Note: It's really important to pass in '0' for the Keras learning mode here!\n # Keras layers behave differently in prediction vs. train modes!\n cost, gradients = grab_cost_and_gradients_from_model([hacked_image, 0])\n\n # Move the hacked image one step further towards fooling the model\n # print gradients\n hacked_image += np.sign(gradients) * learning_rate\n\n # Ensure that the image doesn't ever change too much to either look funny or to become an invalid image\n hacked_image = np.clip(hacked_image, max_change_below, max_change_above)\n hacked_image = np.clip(hacked_image, -1.0, 1.0)\n\n print(\"Model's predicted likelihood that the image is a tree frog: {:.8}%\".format(cost * 100))\n\n hacked_image = hacked_image.reshape((224,224,3))\n img = array_to_img(hacked_image)\n img.save(img_res_path)\n\n\nif __name__ == \"__main__\":\n create_img(\"./trixi.png\", \"./trixi_frog.png\", \"./model.h5\", CATEGORY_STR, CATEGORY_IDX)\n assert is_similar_img(\"./trixi.png\", \"./trixi_frog.png\")\n\n" }, { "alpha_fraction": 0.7132353186607361, "alphanum_fraction": 0.7226890921592712, "avg_line_length": 25.41666603088379, "blob_id": "8084bfce175e6eaebd9dfff7136ae6a189f96720", "content_id": "be321ffba18c3c6a638b78437ac01d8a0bec9c1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 952, "license_type": "no_license", "max_line_length": 57, "num_lines": 36, "path": "/prediction.py", "repo_name": "jason-klein/dsad-picoctf-2018-dog-or-frog", "src_encoding": "UTF-8", "text": "# organize imports\nimport sys\nimport numpy as np\nfrom keras.models import Model\nfrom keras.preprocessing import image\nfrom keras.applications import imagenet_utils, mobilenet\n\n# process an image to be mobilenet friendly\ndef process_image(img_path):\n img = image.load_img(img_path, target_size=(224, 224))\n img_array = image.img_to_array(img)\n img_array = np.expand_dims(img_array, axis=0)\n pImg = mobilenet.preprocess_input(img_array)\n return pImg\n\n# main function\nif __name__ == '__main__':\n\n # path to image\n #img_path = \"trixi.png\"\n #img_path = \"trixi_frog.png\"\n #img_path = \"trixi_sealion.png\"\n img_path = sys.argv[1]\n\n # process the image\n pImg = process_image(img_path)\n\n # define the mobilenet model\n mobilenet = mobilenet.MobileNet()\n\n # make predictions on image using mobilenet\n prediction = mobilenet.predict(pImg)\n\n # obtain the top-5 predictions\n results = imagenet_utils.decode_predictions(prediction)\n print(results)\n\n" }, { "alpha_fraction": 0.6237481832504272, "alphanum_fraction": 0.6537911295890808, "avg_line_length": 28.08333396911621, "blob_id": "ccd892f218935ace869e54a0f1032d33efa5c7f0", "content_id": "5a11bc9494c943893546f1e2460d9195e105b6b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 699, "license_type": "no_license", "max_line_length": 78, "num_lines": 24, "path": "/difference.py", "repo_name": "jason-klein/dsad-picoctf-2018-dog-or-frog", "src_encoding": "UTF-8", "text": "import sys\nfrom PIL import Image\nfrom imagehash import phash\n\n# I'm pretty sure I borrowed this function from somewhere, but cannot remember\n# the source to cite them properly.\ndef hash_hamming_distance(h1, h2):\n s1 = str(h1)\n s2 = str(h2)\n return sum(map(lambda x: 0 if x[0] == x[1] else 1, zip(s1, s2)))\n\ndef is_similar_img(path1, path2):\n image1 = Image.open(path1)\n image2 = Image.open(path2)\n\n dist = hash_hamming_distance(phash(image1), phash(image2))\n return dist\n\nif __name__ == \"__main__\":\n #img_path = \"./trixi_frog.png\"\n img_path = sys.argv[1]\n\n dist = is_similar_img(\"./trixi.png\", img_path)\n print('P hash distance from original dog photo: %s'%(dist))\n\n" } ]
3
UJ-Codes/Dojo-Solo-Project
https://github.com/UJ-Codes/Dojo-Solo-Project
588fa921473658dcd9dbda1fd7df34a30809b25b
5de8f10ea321c8d740a3ff9b162675f25b6da90f
752ed738208c78e04c93afe60bf3c119be459e10
refs/heads/main
2023-03-02T04:30:34.536305
2021-02-09T23:30:25
2021-02-09T23:30:25
337,564,239
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6191263198852539, "alphanum_fraction": 0.6200708150863647, "avg_line_length": 29.257143020629883, "blob_id": "21511dd0f4b357e80ae325aa3c82e262f61afc80", "content_id": "e590ef6c20b05ba2952d69802de5e4d29930ed85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4235, "license_type": "no_license", "max_line_length": 153, "num_lines": 140, "path": "/views.py", "repo_name": "UJ-Codes/Dojo-Solo-Project", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom django.shortcuts import render, redirect\nfrom django.db import models\nfrom datetime import date, datetime\nfrom django.contrib import messages\nfrom .models import User\n#from .models import Wish\nimport bcrypt\nimport re\n\n\ndef login_page(request):\n# context = {\n# 'wishes': Wish.objects.all()\n# }\n return render(request, 'login.html')\n print('I am here')\n\n\ndef register(request):\n if request.method == \"POST\":\n print('I am registering now')\n errors = User.objects.login_validator(request.POST)\n if len(errors) > 0:\n for key, value in errors.items():\n messages.error(request, value)\n return redirect('/register')\n print('I am registered')\n else:\n hashed_pw = bcrypt.hashpw(request.POST['password'].encode(), bcrypt.gensalt()).decode()\n print(hashed_pw)\n user = User.objects.create(first_name=request.POST['first_name'], \n last_name=request.POST['last_name'],\n email=request.POST['email'], \n password=hashed_pw)\n request.session['user_id'] = user.id\n messages.success(request, \"You have successfully registered!\") \n return redirect('/account') \n return redirect('/login_page') \n\n\n\ndef login(request):\n user = User.objects.filter(email=request.POST['email'])\n if len(user) > 0:\n#TAKE VALUE FROM THE LIST AND MAKE IT THE VALUE OF THE USER. instead of having a whole list\n user = user[0]\n if bcrypt.checkpw(request.POST['password'].encode(), user.password.encode()):\n request.session['user_id'] = user.id\n# messages.success(request, \"You have logged in successfully!\")\n return redirect('/account')\n#do not need else, code will folllow to this line\n messages.error(request, \"Email or password is incorrect\")\n return redirect('/login_page') \n\n\ndef success(request):\n if 'user_id' not in request.session:\n messages.error(request, \"You need to log in!\")\n return redirect('/')\n context = {\n#we can use get instead of filter because we know it is in database\n 'user': User.objects.get(id=request.session['user_id']),\n 'all_wishes': Wish.objects.all()\n }\n return render(request, 'account.html', context)\n\ndef logout(request):\n request.session.flush()\n return redirect('/')\n\n\ndef about(request):\n# context = {\n# 'wishes': Wish.objects.all()\n# }\n return render(request, 'about.html')\n print('I am here')\n\n\ndef account(request):\n# context = {\n# 'wishes': Wish.objects.all()\n# }\n return render(request, 'account.html')\n print('I am here')\n\n\n\ndef schedule(request):\n# context = {\n# 'wishes': Wish.objects.all()\n# }\n return render(request, 'schedule.html')\n print('I am here')\n\ndef update(request):\n# context = {\n# 'wishes': Wish.objects.all()\n# }\n return render(request, 'update.html')\n print('I am here')\n\n\ndef work(request):\n# context = {\n# 'wishes': Wish.objects.all()\n# }\n return render(request, 'work.html')\n print('I am here')\n\n\ndef location(request):\n# context = {\n# 'wishes': Wish.objects.all()\n# }\n return render(request, 'location.html')\n print('I am here')\n\ndef review(request):\n# context = {\n # 'wish': wish_one\n # }\n return render(request, 'review.html')\n print('I am here')\n\ndef create_wish(request):\n errors = Wish.objects.wish_validator(request.POST)\n if len(errors) > 0:\n for key, value in errors.items():\n messages.error(request, value)\n return redirect('/')\n Wish.objects.create(item = request.POST['item'], description = request.POST['description'], poster = User.objects.get(id=request.session['user_id']))\n###########\n# poster = User.objects.get(id=request.session['id'])\n# item = Wish.objects.get(id=id)\n# poster = User.objects.get(id=request.session['id'])\n# Wish.objects.create(item = request.POST['item'], description = request.POST['description'])\n #Wish.objects.create(item = request.POST['item'], poster=poster, description = request.POST['description'])\n return redirect('/review')" }, { "alpha_fraction": 0.6427228450775146, "alphanum_fraction": 0.6525009274482727, "avg_line_length": 41.90322494506836, "blob_id": "8d404d842154ad4a5160b37f7eeb8b5815d9a480", "content_id": "e0e8d656d3c6aa02825988dab6a4581c68cc96d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2659, "license_type": "no_license", "max_line_length": 111, "num_lines": 62, "path": "/models.py", "repo_name": "UJ-Codes/Dojo-Solo-Project", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom django.contrib import messages\nfrom django.db import models\nfrom datetime import date, datetime\nimport re\n\nclass LoginValidation(models.Manager):\n#remember to look into what is suppose to come after self,\n def login_validator(self, form):\n errors = {}\n # VALIDATES EMAIL\n EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z]+$')\n if len(form['first_name']) < 2:\n errors[\"first_name\"] = \"First name should be at least 2 characters\"\n#!!!!WHEN SHOULD A DOUBLE TICK OR SINGLE TICK BE USED IN THE ERRORS[]!!!\n if len(form['last_name']) < 2:\n errors[\"last_name\"] = \"Last name should be at least 3 characters\"\n#PASSWORD\n if len(form['password']) < 8:\n errors['password'] = \"Password should be at least 8 characters\"\n# PASSWORD CONFIRMATION LOOKING FOR MATCH\n if form['password'] != form['pw_confirm']:\n errors['pw_confirm'] = \"Password for account does not match\"\n# CHECK TO SEE IF EMAIL IN CORRECT FORMAT\n if not EMAIL_REGEX.match(form['email']):\n errors['regex'] = \"Incorrect email format!\"\n users_with_same_email = User.objects.filter(email=form['email'])\n if len(users_with_same_email) > 0:\n errors['duplicate'] = \"Email already taken, try another one\" \n return errors\n\nclass User(models.Model):\n first_name = models.CharField(max_length=55)\n last_name = models.CharField(max_length=55)\n email = models.EmailField(max_length=60)\n password = models.CharField(max_length=255)\n created_at = models.DateTimeField(auto_now_add = True)\n updated_at = models.DateTimeField(auto_now = True)\n objects = LoginValidation()\n\n\n\nclass WishManager(models.Manager):\n def wish_validator(self, form):\n errors = {}\n if len(form['item']) < 3:\n errors[\"item\"] = \"A wish must have 3 characters\"\n if len(form['description']) < 1:\n errors['description'] = \"A description must be provided\"\n return errors\n\nclass Wish(models.Model):\n item = models.CharField(max_length=100)\n description = models.TextField()\n poster = models.ForeignKey(User, related_name='wishes', on_delete=models.CASCADE)\n granted = models.BooleanField(default=False)\n ## do not focus on many many; could be empty; do not need it for red belt; make sure I have the foreign key\n ###user.wishes\n user_likes = models.ManyToManyField(User, related_name='liked_posts')\n created_at = models.DateTimeField(auto_now_add = True)\n updated_at = models.DateTimeField(auto_now = True)\n objects = WishManager()" }, { "alpha_fraction": 0.6407079696655273, "alphanum_fraction": 0.6407079696655273, "avg_line_length": 28.789474487304688, "blob_id": "da32193271b5c7f01098e31a0a12081d4560faf6", "content_id": "2dc056f0c7682d037d7cc63e0662907a1470a8b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 565, "license_type": "no_license", "max_line_length": 43, "num_lines": 19, "path": "/urls.py", "repo_name": "UJ-Codes/Dojo-Solo-Project", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.about),\n path('about', views.about),\n path('login_page', views.login_page),\n path('register', views.register),\n path('login', views.login),\n path('logout', views.logout),\n path('success', views.success),\n path('account', views.account),\n path('schedule', views.schedule),\n path('update', views.update),\n path('consult', views.work),\n path('location', views.location),\n path('review', views.review),\n path('create_wish', views.create_wish),\n]" } ]
3
sphere-engine/Scarky2
https://github.com/sphere-engine/Scarky2
aa35506844fb2d8f341e4c3dd8783af81e8c72a4
f6a5c6d9d2ef0c4b02670f27beba16cdc572d223
c458d7d0a5c38685bdeca83d7382392f36537449
refs/heads/master
2021-01-10T03:39:50.292809
2015-07-09T02:10:51
2015-07-09T02:10:51
53,985,637
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7739726305007935, "alphanum_fraction": 0.8082191944122314, "avg_line_length": 28.200000762939453, "blob_id": "83e1129bdc328aba5cd5072401709857ac50fc1d", "content_id": "2eea6dd10ffdbf4e5c088e5a32e39bf18fc58b0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 146, "license_type": "permissive", "max_line_length": 86, "num_lines": 5, "path": "/requirements.txt", "repo_name": "sphere-engine/Scarky2", "src_encoding": "UTF-8", "text": "django==1.8\ndjango-bower\ndjango-debug-toolbar\nMySQL-python\n-e git://github.com/sphere-engine/[email protected]#egg=sphereengine-python\n" }, { "alpha_fraction": 0.59560227394104, "alphanum_fraction": 0.6080306172370911, "avg_line_length": 42.58333206176758, "blob_id": "04e376a61a6596832b36f058daa40e1830cfcafe", "content_id": "0fa91fd72e14f408c0af11c2e2dcc374be75d357", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1046, "license_type": "permissive", "max_line_length": 120, "num_lines": 24, "path": "/builder/urls.py", "repo_name": "sphere-engine/Scarky2", "src_encoding": "UTF-8", "text": "#-*- coding: utf-8 -*-\n\n#django\nfrom django.conf.urls import patterns, include, url\nfrom django.views.generic import RedirectView\n\nurlpatterns = patterns('builder',\n \n url(r'^builder/upload$', 'views.builder_upload', name='builder_upload'),\n url(r'^builder/(?P<pid>\\w+)', 'views.builder', name='builder'),\n \n \n url(r'^problems', 'views.problems', name='problems'),\n url(r'^problem/(?P<pid>\\w+)', 'views.problem', name='problem'),\n url(r'^widget/(?P<pid>\\w+).js$', 'views.widget_js', name='widget_js'),\n url(r'^widget/(?P<pid>\\w+)$', 'views.widget', name='widget'),\n \n url(r'^api/1/problems/?$', 'views.api_1_problems', name='api_1_problems'),\n url(r'^api/1/problems/(?P<pid>\\w+)/?$', 'views.api_1_problem', name='api_1_problem'),\n url(r'^api/1/problems/(?P<pid>\\w+)/submissions/?$', 'views.api_1_submissions', name='api_1_submissions'),\n url(r'^api/1/problems/(?P<pid>\\w+)/submissions/(?P<sid>\\d+)/?$', 'views.api_1_submission', name='api_1_submission'),\n \n url(r'^', 'views.home', name='home'),\n)\n" } ]
2
MarripellyNavya/DjangoProject1
https://github.com/MarripellyNavya/DjangoProject1
a17fa820a998c85e43429396119896e3163a4342
5ea50c73d5debdf03088971797880b1d1d9d79d6
384562654a2e012234faa27e114e3495657791a3
refs/heads/master
2023-08-02T02:57:58.312708
2021-09-28T11:52:08
2021-09-28T11:52:08
411,261,240
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7034782767295837, "alphanum_fraction": 0.7104347944259644, "avg_line_length": 28.487178802490234, "blob_id": "a544352c4962fabb3b11c53c651bdf3b02aba787", "content_id": "5cb79c9054acc25330129d684c58d544b78fb04f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1150, "license_type": "no_license", "max_line_length": 74, "num_lines": 39, "path": "/sample/cuisine/models.py", "repo_name": "MarripellyNavya/DjangoProject1", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nSTATUS_CHOICES = (\n ('draft', 'Draft'),\n ('published', 'Published'),\n)\nCATG_CHOICES = (\n ('dessert', 'Dessert'),\n ('snack', 'Snack'),\n ('food', 'Food'),\n)\nclass Cuisine(models.Model):\n name = models.CharField(max_length=20)\n type = models.CharField(max_length=8,\n choices=(('veg','Veg'),('non veg','NV')),\n default='non veg')\n catg = models.CharField(max_length=8,\n choices=CATG_CHOICES,\ndefault='food')\n slug = models.SlugField(max_length=30, unique_for_date='publish')\n desc = models.TextField()\n pic = models.ImageField(upload_to='cuisine_pic', blank=True, null=True, )\n author = models.ForeignKey(User,\n related_name='cuisine_user',\n on_delete=models.CASCADE,)\n publish = models.DateTimeField(default=timezone.now)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n status = models.CharField(max_length=10,\n choices=STATUS_CHOICES,\ndefault='draft')\n class Meta:\n ordering = ('-publish',)\n def __str__(self):\n return self.name\n" } ]
1
grandeotos/the-chamber-web
https://github.com/grandeotos/the-chamber-web
1aa2805413b8d6ecfd4c40d9214cc40935aa0eb1
840e050aa9c46bb85f9dd76e6e1764fffd6da26a
d1e3b2205582f671b4d567dc28b6b8be06531d13
refs/heads/main
2023-04-22T11:16:52.733982
2021-05-03T16:16:48
2021-05-03T16:16:48
347,159,658
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5880721211433411, "alphanum_fraction": 0.6352288722991943, "avg_line_length": 43.5625, "blob_id": "b223d6cf65e86c5ddc9965c04a18f02cc3629ad8", "content_id": "04d1aaa83a1c70768c65e12fa9e4c00713974264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 721, "license_type": "no_license", "max_line_length": 412, "num_lines": 16, "path": "/generadorcheckpoints.py", "repo_name": "grandeotos/the-chamber-web", "src_encoding": "UTF-8", "text": "import random\n\ntestId = 3\nlevelsAmount = 1\npuzzlesAmount = 11\nsoftSkillsAmount = 2\ntimeElapsedMin = 30\ntimeElapsedMax = 120\nscoreMin = 68\nscoreMax = 100\n\n\nfor level in range(1, levelsAmount + 1):\n for puzzle in range(1, puzzlesAmount + 1):\n for softSkill in range(1, softSkillsAmount + 1):\n print(\"INSERT INTO `checkpoints` (`checkpointid`, `test_testId`, `checkpointScore`, `checkpointMaxScore`, `softSkillId`, `levelId`, `puzzleId`, `timeElapsed`, `timeStamp`) VALUES (NULL, '\" + str(testId) + \"','\" + str(random.randrange(0,100)) + \"','\" + str(100) + \"','\" + str(softSkill) + \"','\" + str(level) + \"','\" + str(puzzle) + \"','\" + str(random.randrange(60,1200)) + \"', current_timestamp());\")\n " }, { "alpha_fraction": 0.5111111402511597, "alphanum_fraction": 0.644444465637207, "avg_line_length": 14.333333015441895, "blob_id": "29343cf7ba22d0041c742df5451da9f160c58af0", "content_id": "4db30088dd06bad525f7a5f7395a2d150c488c52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 45, "license_type": "no_license", "max_line_length": 24, "num_lines": 3, "path": "/config/jwt.js", "repo_name": "grandeotos/the-chamber-web", "src_encoding": "UTF-8", "text": "module.exports = {\n key: \"Numeric123123\"\n}" }, { "alpha_fraction": 0.5592734217643738, "alphanum_fraction": 0.5630975365638733, "avg_line_length": 26.552631378173828, "blob_id": "73883f9100ef618145aae87e326c066c553e062c", "content_id": "537345133e24bc0d7a012204e31fb44b9220373e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1046, "license_type": "no_license", "max_line_length": 60, "num_lines": 38, "path": "/routes/game.js", "repo_name": "grandeotos/the-chamber-web", "src_encoding": "UTF-8", "text": "var express = require('express');\nvar router = express.Router();\n\nvar controller = require('../controllers/game.controller');\n\nconst middleware = express.Router();\nmiddleware.use((req, res, next) => {\n const token = req.headers[\"auth-token\"];\n\n if (token) {\n //valid\n jwt.verify(token, jwtconfig.key, (err, decoded) => {\n if (err) {\n return res.json({\n mensaje: \"Token invalido\"\n })\n } else {\n console.log(decoded.accountId)\n console.log(decoded.username)\n req.decoded = decoded\n next()\n }\n });\n } else {\n res.send({\n mensaje: \"Token no proporcionado\"\n })\n }\n\n})\n\n//localhost:8020/game/cars\nrouter.get('/api', controller.HelloApi)\nrouter.post('/login', controller.AuthUser)\nrouter.post('/prueba', controller.SubmitTest);\nrouter.post('/checkpoint' ,controller.SetCheckPoint);\nrouter.post('/finish', controller.finishTest);\nmodule.exports = router;" }, { "alpha_fraction": 0.5458412170410156, "alphanum_fraction": 0.5496219396591187, "avg_line_length": 22.786516189575195, "blob_id": "b77627d13d3856eda409e44ed0cdbaae9e676cb0", "content_id": "e7cf85ef19055473746c330f1629e60f42623f32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2116, "license_type": "no_license", "max_line_length": 61, "num_lines": 89, "path": "/app (2).js", "repo_name": "grandeotos/the-chamber-web", "src_encoding": "UTF-8", "text": "// var (scope global), let (scope especifico)\n\nvar mysql = require('mysql');\nconst jwt = require('jsonwebtoken');\nvar session = require('express-session');\nvar path = require('path');\nconst config = require('./config/jwt');\nconst sqlconfig = require('./helpers/config');\nconst e = require('express');\nvar connection = mysql.createConnection(sqlconfig);\nvar thechamber = require('./routes/game');\nvar express = require('express');\nvar router = express.Router();\nvar controller = require('./controllers/game.controller');\nconst { PORT = 42069 } = process.env\n\n// clave valor\nconst app = express();\napp.set(\"key\", config.key); \napp.use(session({\n secret: 'secret',\n resave: true,\n saveUninitialized: true\n}));\n\napp.use(express.json());\n\napp.listen(PORT, () => {\n console.log(`Server iniciado en el pueto ${PORT}`);\n});\n\nexpress.Router();\nconst middleware = express.Router();\nmiddleware.use((req, res, next) => {\n const token = req.headers[\"auth-token\"];\n\n if (token) {\n //valid\n jwt.verify(token, app.get(\"key\"), (err, decoded) => {\n if (err) {\n return res.json({\n mensaje: \"Token invalido\"\n })\n } else {\n console.log(decoded.id)\n console.log(decoded.user)\n req.decoded = decoded\n next()\n }\n });\n } else {\n res.send({\n mensaje: \"Token no proporcionado\"\n })\n }\n\n})\n\napp.use('/game', thechamber)\n\napp.get('/user', middleware, (req, res) => {\n const datos = [{\n id: 1,\n nombre: \"Otos\"\n },\n {\n id: 2,\n nombre: \"Otos\"\n },\n {\n id: 3,\n nombre: \"Otos\"\n }\n ]\n\n res.json(datos)\n})\n\napp.get('/', (req, res) => {\n res.json({\n mensaje : \"Este sitio esta arriba, ve a /api\"\n });\n})\n\napp.get('/api', controller.HelloApi)\napp.post('/login', controller.AuthUser)\napp.post('/prueba', controller.SubmitTest);\napp.post('/checkpoint' ,controller.SetCheckPoint);\napp.post('/finish', controller.finishTest);" }, { "alpha_fraction": 0.5744125247001648, "alphanum_fraction": 0.5744125247001648, "avg_line_length": 26.428571701049805, "blob_id": "ce967efeb01f3aad2420e906ef3e2efb2de6a63a", "content_id": "d236b90f83e83e08b002cb012620c1817fda3d03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 383, "license_type": "no_license", "max_line_length": 55, "num_lines": 14, "path": "/controllers/login.controller.js", "repo_name": "grandeotos/the-chamber-web", "src_encoding": "UTF-8", "text": "var mysql = require('mysql');\nvar config = require('../helpers/config');\nvar connection = mysql.createConnection(config);\n\nmodule.exports.loginRequest = (req, res) => {\n var sql = 'UNA QUERY SQL';\n connection.query(sql, (error, results, fields) => {\n if (error) {\n response.send(error);\n } else {\n response.send(results);\n }\n });\n}" }, { "alpha_fraction": 0.4847704768180847, "alphanum_fraction": 0.492778480052948, "avg_line_length": 42.1728401184082, "blob_id": "80e7a957b351ce42e5d291b3a8d2845f124e28f5", "content_id": "d3530432b72399465d54d58408a69c3e8d678c3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6994, "license_type": "no_license", "max_line_length": 253, "num_lines": 162, "path": "/controllers/game.controller.js", "repo_name": "grandeotos/the-chamber-web", "src_encoding": "UTF-8", "text": "const express = require('express');\nconst { response, json } = require('express');\nvar mysql = require('mysql');\nconst jwt = require('jsonwebtoken');\nconst jwtconfig = require('../config/jwt');\nvar session = require('express-session');\nconst { user } = require('../helpers/config');\nvar sqlconfig = require('../helpers/config');\nvar connection = mysql.createConnection(sqlconfig);\n\nmodule.exports.HelloApi = (request, response) => {\n response.json({\n mensaje : \"API hecha con <3 por Chayomix Studios\",\n version : \"TheChamberAPI v1.21 BUILD 3 @ 30042021 11:00 CDT\"\n });\n}\n\nmodule.exports.AuthUser = (request, response) => {\n var username = request.body.username;\n var password = request.body.password;\n var AuthQuery = 'SELECT accountId, username FROM account WHERE username = ? AND (rolid = 1 OR rolid = 6 OR rolid = 7) AND password = sha2(?,224)';\n var GameQuery = 'SELECT accountId, username FROM account WHERE username = ? AND (rolid = 0 OR rolid = 2 OR rolid = 3 OR rolid = 4 OR rolid = 5) AND password = sha2(?,224)';\n connection.query(AuthQuery,\n [username, password],\n (error, results, fields)=>{\n if(error){\n response.json(error)\n }\n else{\n if(results[0] == null){\n connection.query(GameQuery,\n [username, password],\n (error, results, fields)=>{\n if(error){\n response.send(error);\n }\n else{\n if(results[0] == null){\n response.json({\n error: \"Usuario no existe o contraseña incorrecta, Revisse credenciales y vuelve a intentar de nuevo\"\n });\n }else{\n response.json({\n error: \"Usuario no autorizado para hacer pruebas. Prueba finalizada anteriormente, o usuario sin registrar sus datos. Entre a TheChamberWeb para completar su registro\"\n });\n }\n \n }\n });\n }\n else{\n console.log(results[0].accountId);\n const payload = {\n id: results[0].accountId,\n user: request.body.username\n }\n \n const token = jwt.sign(payload, jwtconfig.key, {\n expiresIn: 7200\n });\n console.log(results);\n console.log(typeof(results));\n (results[0]).mensaje = \"Autenticado\";\n (results[0]).token = token;\n response.json(results[0]);\n }\n \n }\n });\n}\n\nmodule.exports.SubmitTest = (request, response) => {\n console.log(request)\n var accountId = request.body.accountId;\n console.log(accountId);\n var AuthQuery = 'INSERT INTO `tests` (`testId`, `accountId`, `testStatus_statusId`, `beganAtTimeStamp`, `duration`, `finishedAtTimeStamp`, `overallScore`) VALUES (NULL, ?, 2, current_timestamp(), NULL, NULL, NULL)';\n connection.query(AuthQuery,\n accountId,\n (error, results, fields)=>{\n if(error){\n response.send(error);\n }\n else{\n //console.log(fields);\n //response.json(results);\n response.json({\n mensaje: \"Prueba creada correctamente\",\n affectedRows: results.affectedRows,\n pruebaId: results.insertId\n });\n }\n });\n}\n\nmodule.exports.finishTest = (request, response) => {\n console.log(request)\n var duration = request.body.duration;\n var testId = request.body.testId;\n var overallScore = request.body.overallScore;\n var scores = [request.body.score1, request.body.score2]\n var durations = [request.body.duration1, request.body.duration2]\n var AuthQuery = 'UPDATE `tests` SET `testStatus_statusId` = 3, `duration` = ?, `overallScore` = ?, `finishedAtTimeStamp` = current_timestamp() WHERE `tests`.`testId` = ?';\n var Insert = 'INSERT INTO `scores` (`scoreId`, `test_testId`, `softSkill_idsoftSkill`, `softSkillScore`) VALUES (NULL, ?, ?, ?)'; \n connection.query(AuthQuery,\n [duration, overallScore, testId],\n (error, results, fields)=>{\n if(error){\n response.send(error);\n }\n else{\n for (var i = 1; i <= 2; i++) {\n connection.query(Insert,\n [testId, (i), scores[i-1], durations[i-1]],\n (error, results, fields)=>{\n console.log(\"Holaaa\")\n console.log(i)\n console.log(scores[i-1])\n console.log(durations[i-1])\n if(error){\n console\n console.error(error)\n response.send(error);\n }else{\n console.log(results)\n console.log(fields)\n }\n });\n }\n response.json({\n mensaje: \"Prueba finalizada correctamente\",\n affectedRows: results.affectedRows,\n });\n }\n });\n}\n\nmodule.exports.SetCheckPoint = (request,response) => {\n var testId = request.body.testId;\n var score = request.body.score;\n var maxScore = request.body.maxScore;\n var idsoftSkill = request.body.idsoftSkill;\n var idlevel = request.body.idlevel;\n var idPuzzle = request.body.idPuzzle;\n var timeElapsed = request.body.timeElapsed;\n console.log(testId, score)\n var CheckPointInsert = 'INSERT INTO `checkpoints` (`checkpointId`, `test_testId`, `checkpointScore`, `checkpointMaxScore`, `softSkillId`, `levelId`, `puzzleId`, `timeElapsed`, `timeStamp`) VALUES (NULL, ?, ?, ?, ?, ?, ?, NULL, current_timestamp())';\n //var CheckPointQuery = 'SELECT * FROM `checkpoints` WHERE checkpointid = ?'\n connection.query(CheckPointInsert,\n [testId,score,maxScore,idsoftSkill,idlevel,idPuzzle,timeElapsed],\n (error, results, fields)=>{\n if(error){\n response.send(error);\n }\n else{\n response.json({\n mensaje: \"Checkpoint creado correctamente\",\n affectedRows: results.affectedRows,\n insertId: results.insertId\n });\n }\n });\n}" }, { "alpha_fraction": 0.6615384817123413, "alphanum_fraction": 0.6717948913574219, "avg_line_length": 27, "blob_id": "56fccf89a25fe9f6eeee271c81eac9cd3a8e03c5", "content_id": "7b34f80bfd284e3c17c68f6bedb1f3bdcf43eb12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 195, "license_type": "no_license", "max_line_length": 69, "num_lines": 7, "path": "/helpers/config.js", "repo_name": "grandeotos/the-chamber-web", "src_encoding": "UTF-8", "text": "var config = {\n host: 'the-chamber-web.ckqbx0wdqtxo.us-east-1.rds.amazonaws.com',\n user: 'TheChamber_Game',\n password: 'n2TyHuJYPPP59SVu',\n database: 'thechamber'\n}\nmodule.exports = config;" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 19, "blob_id": "7cec578ad8bcfc3cdd6512edbcb6c716ab8ccdc8", "content_id": "aae254f632fd3f81040e2a912f890b1ef364f880", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 40, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/README.md", "repo_name": "grandeotos/the-chamber-web", "src_encoding": "UTF-8", "text": "# web-chambeador\n Web para chambeadores\n" }, { "alpha_fraction": 0.645348846912384, "alphanum_fraction": 0.6715116500854492, "avg_line_length": 37.33333206176758, "blob_id": "5155bc41fc46af8279f0a0464b2b015f329e6eb6", "content_id": "89e14b04c21a4d2457f98c8735de946b2d64df81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "no_license", "max_line_length": 218, "num_lines": 9, "path": "/generadorScores.py", "repo_name": "grandeotos/the-chamber-web", "src_encoding": "UTF-8", "text": "import random\n\ntestId = 2\nsoftSkillsAmount = 2\nscoreMin = 68\nscoreMax = 101\n\nfor softSkill in range(1, softSkillsAmount + 1):\n print(\"INSERT INTO `scores` (`scoreId`, `test_testId`, `softSkill_idsoftSkill`, `softSkillScore`) VALUES (NULL, '\" + str(testId) + \"', '\" + str(softSkill) + \"', '\" + str(random.randrange(scoreMin,scoreMax)) +\"');\")" } ]
9